I have been struggling with an issue using the java scripting API to control the execution of some user defined javascript. I am using the builtin Rhino engine under the hood, which says you can set the InstructionObserverThreshold and it will take care of stopping execution if the limit is reached. I have been playing with the following sample app for a while now and I am stumped as to why it won't work. You will see that I have set the MaximumInterpreterStackDepth, as well. This works perfectly, but the instruction observer doesn't appear to do anything.
Any ideas on what is missing with this code to make it work?
Thanks!
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import com.sun.script.javascript.RhinoScriptEngine;
public class RhinoTester2 {
public static void main(String[] args) {
new RhinoScriptEngine(); // initialize the global context.
sun.org.mozilla.javascript.internal.ContextFactory cx = sun.org.mozilla.javascript.internal.ContextFactory.getGlobal();
cx.addListener( new sun.org.mozilla.javascript.internal.ContextFactory.Listener() {
public void contextCreated( sun.org.mozilla.javascript.internal.Context cxt ) {
cxt.setInstructionObserverThreshold(10000 ); // This should stop after 10 seconds or so.
cxt.setMaximumInterpreterStackDepth(1); // this should not be a factor for the moment
System.out.println("Context Factory threshold set. "+cxt.getInstructionObserverThreshold());
}
@Override
public void contextReleased(
sun.org.mozilla.javascript.internal.Context arg0) {
System.out.println("Context Released.");
}
});
// Now run the script to see if it will be stopped after a short time.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("javascript");
try {
// engine.eval("while(true){println(\"hello\");};"); // This will fail immediately due to the interpreter stack depth.
engine.eval("while(true){};"); // this never fails. runs happily forever.
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}