package com.rescripter.script;
import java.io.IOException;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptRunner {
private static final String ENGINE_NAME = "rhino-nonjdk";
private static final String SCRIPT_STACK_EXPORT_NAME = "Load";
private final ScriptEngine context;
private final ScriptContext scope;
public ScriptRunner(ScriptStack scriptStack) {
context = createContext();
scope = createScope();
putProperty(SCRIPT_STACK_EXPORT_NAME, scriptStack);
}
protected ScriptEngine createContext() {
ScriptEngineManager mgr = new ScriptEngineManager();
return mgr.getEngineByName(ENGINE_NAME);
}
private ScriptContext createScope() {
ScriptContext scriptContext = context.getContext();
scriptContext.setBindings(context.createBindings(), ScriptContext.ENGINE_SCOPE);
return scriptContext;
}
public void run(String source) throws IOException {
try {
runInScope(source);
} catch (ScriptException e) {
throw new IOException(e);
}
}
private void runInScope(String source) throws ScriptException {
context.eval(source, scope);
}
public void putProperty(String name, Object object) {
scope.getBindings(ScriptContext.ENGINE_SCOPE).put(name, object);
}
public Object getProperty(String name) {
return scope.getBindings(ScriptContext.ENGINE_SCOPE).get(name);
}
}