Using JAva 6 New Scripting Capabilities

06 Sep 2007

I was working on my thesis work where I had a requirement to execute certain code snippets of JavaScript and see if they make calls or modify a specific set of objects. For example, I wanted to see if the code I wish to run sets "location" property. So I wanted to use the Rhino Engine to execute the Javascript and the major problem with that is that Rhino is just an engine for JavaScript and does not provide any DOM API. So any DOM calls made in the JavaScript would terminate the execution. So we have to expose a set of objects by ourselves to the engine. Anyway in the mean time I came across an article which used Java 6 Scripting Engines! I knew Java 6 had some scripting facilities but never gave it a hard thought. It is a really simple API and works really well. In the past I have tried to use Rhino to run javascript but it is really a tedious process. anyway here is how it is done using javax.script package.

import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import com.sun.script.javascript.RhinoScriptEngine;

public class TestScripting {
public static void main(String[] args)
{
ScriptEngineManager mgr = new ScriptEngineManager();
RhinoScriptEngine js = (RhinoScriptEngine)mgr.getEngineByName("js");
try {
js.put("location",new TestScripting()); // tell the script engine to use the object passed when it encounters "location"
js.eval("function alert(x) { print(x);}"); // implement your own global alert function
try {
js.eval(new FileReader("/home/krishna/workspace/SuriLearning/bin/test.js"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void write(Object mesg)
{
System.out.println(mesg);
}

public void replace(String mesg)
{
System.out.println("Called location.replace to go to : "+mesg);
}

}

Then I have updated the test.js file with some statement like "location.replace("http://google.com")". This is a basic idea on how we can use Rhino to detect redirections, which is portion of my work.