Monday, August 13, 2012

Executing Javascript code in Java

Here some snippet how to execute Javascript code in Java


final String script = "function test(){ return 'abc' + 'def'; } test();";

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");

Object result = engine.eval(script);

Assert.assertEquals("java.lang.String", result.getClass().getName());
Assert.assertEquals("abcdef", result.toString());

And some other code


final String script = "function execute(){ return { 'U.1' : function(){ return { 'u': '2', 'r': '', 'f':'U' }; }, 'R.5': function(){ return 'B' } } } execute();";

ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js");
js.getContext().setAttribute("out", System.out, ScriptContext.ENGINE_SCOPE);

Object jsResult = js.eval(script);
NativeObject obj = (NativeObject) jsResult;
Object objUserRole = NativeObject.getProperty(obj, "U.1");

SimpleBindings bindings = new SimpleBindings();
bindings.put("foomethod", objUserRole);
log.debug("RESULT: " + js.eval("foomethod();", bindings));
log.debug("RESULT: " + js.eval("foomethod().u", bindings));
log.debug("RESULT: " + js.eval("foomethod().r", bindings));
log.debug("RESULT: " + js.eval("foomethod().f", bindings));

Assert.assertEquals("2", js.eval("foomethod().u", bindings).toString());
Assert.assertEquals("", js.eval("foomethod().r", bindings).toString());
Assert.assertEquals("U", js.eval("foomethod().f", bindings).toString());

objUserRole = NativeObject.getProperty(obj, "R.5");
bindings.put("foomethod", objUserRole);
log.debug("RESULT: " + js.eval("foomethod();", bindings));
Assert.assertEquals("B",js.eval("foomethod();", bindings).toString());

No comments: