Skip to content

Instantly share code, notes, and snippets.

@NoUsername
Last active October 29, 2016 05:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NoUsername/2d6611305fcaea0f6de83ca82d88cecc to your computer and use it in GitHub Desktop.
Save NoUsername/2d6611305fcaea0f6de83ca82d88cecc to your computer and use it in GitHub Desktop.
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