javajavascriptjavax.script

javax script how to call a function in JavaScript from Java


I'm trying to call a function in JavaScript via Java. This works fine when directly reading a script as a string but I'm using CompiledScripts.

When I do this with a compiled script it gives me method not found if I also add bindings. Without bindings it works but of course the function fails because it needs the bindings.

Any ideas?

CompiledScript script = ... get script....

Bindings bindings = script.getEngine().createBindings();

Logger scriptLogger = LogManager.getLogger("TEST_SCRIPT");

bindings.put("log", scriptLogger);

//script.eval(bindings); -- this way fails
script.eval(); // -- this way works
Invocable invocable = (Invocable) script.getEngine();
invocable.invokeFunction(methodName);

TIA


Solution

  • Here's the solution if any one else bumps into this.

    import java.util.*;
    import javax.script.*;
    
    public class TestBindings {
        public static void main(String args[]) throws Exception {
            String script = "function doSomething() {var d = date}";
            ScriptEngine engine =  new ScriptEngineManager().getEngineByName("JavaScript");
            Compilable compilingEngine = (Compilable) engine;
            CompiledScript cscript = compilingEngine.compile(script);
    
            //Bindings bindings = cscript.getEngine().createBindings();
            Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
            for(Map.Entry me : bindings.entrySet()) {
                System.out.printf("%s: %s\n",me.getKey(),String.valueOf(me.getValue()));
            }
            bindings.put("date", new Date());
            //cscript.eval();
            cscript.eval(bindings);
    
            Invocable invocable = (Invocable) cscript.getEngine();
            invocable.invokeFunction("doSomething");
        }
    }