javakotlinhttp-redirectjavax.script

Redirect stdout of KotlinScriptEngine in javax.script API


I am executing kotlin scripts using javax.script API. I want to capture the output and print the logs later.

I am able to do this for nashorn script engine , but the same does not work on KotlinScriptEngine.

    public void testExampleNashorn() throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        ScriptContext context = engine.getContext();
        StringWriter writer = new StringWriter();
        context.setWriter(writer);

        engine.eval("print(\"Welocme to java worldddd\")");

        String output = writer.toString();

        System.out.println("Script output: " + output);
    }

Output for Nashorn

Script output: Welocme to java worldddd

The same code snippet when adjusted for kotlin as below

    public void testExampleKotlin() throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("kotlin");
        ScriptContext context = engine.getContext();
        StringWriter writer = new StringWriter();
        context.setWriter(writer);

        engine.eval("println(\"Welocme to java worldddd\")");

        String output = writer.toString();

        System.out.println("Script output: " + output);
    }

Output for kotlin

Welocme to java worldddd
Script output: 
null

I am using kotlin version 1.3.72 Any help is highly appreciated. Thanks.


Solution

  • This is how I managed to capture logs of KotlinScriptEngine execution.

    public Object captureOut(String script,Bindings bindings)  {
            Object result=null;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(os);
            PrintStream console = System.out;
            System.setOut(ps);
    
            try {
                result = kotlinScriptingEngine.eval(script,bindings);
            } catch (ScriptException scriptException) {
                scriptException.printStackTrace(ps);
            }  finally {
                System.out.flush();
                System.setOut(console);
            }
            System.out.println("Kotlin Script Output: " + os.toString());
            return result;
    }