Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of how to call functions from a JavaScript snippet running inside the Java8 Nashorn engine
function testMe() {
ui.showMessage('this should show up in the UI this is running in');
}
[main] INFO a.p.d.blogpost.TestScriptExecutor - trying to run: testMe
[main] INFO a.p.d.blogpost.TestScriptExecutor - showMessage called: this should show up in the UI this is running in
package at.paukl.dynclient.blogpost;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileReader;
import static org.slf4j.LoggerFactory.getLogger;
/**
* @author Paul Klingelhuber
*/
public class TestScriptExecutor {
private static final Logger LOG = getLogger(TestScriptExecutor.class);
private NashornScriptEngine engine;
public static void main(String[] args) throws Exception {
final TestScriptExecutor test = new TestScriptExecutor();
test.loadScript(IOUtils.toString(new FileReader("exampleScript.js")));
test.invokeScriptFunction("testMe");
}
public TestScriptExecutor() {
ScriptEngineManager engineManager = new ScriptEngineManager();
engine = (NashornScriptEngine) engineManager.getEngineByName("nashorn");
}
public void loadScript(String script) {
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("ui", this);
try {
engine.compile(script).eval(bindings);
} catch (ScriptException e) {
LOG.warn("scripterror: ", e);
}
}
public void invokeScriptFunction(String functionName) {
try {
LOG.info("trying to run: {}", functionName);
engine.invokeFunction(functionName);
} catch (ScriptException e) {
LOG.warn("script error!");
} catch (NoSuchMethodException e) {
LOG.info("method not defined");
}
}
public void showMessage(String message) {
LOG.info("showMessage called: {}", message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment