Monday, January 11, 2010

Javascript on Java

This post illustrates two versions of a simple Java helper class that enables scripting on Java. Its assumed that the reader is aware of the basics of running JavaScript on Java.

The first version uses "Mozilla's Rhino Engine" directly, the second uses the more standard "Java 6" scripting interface (JSR-223).

Using "Mozilla's Rhino Engine" directly:-
import java.util.HashMap;
import java.util.Map;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

/**
* High level wrapper to Mozilla Rhino Engine.
*/
public class ScriptSession {
private Map scopeObjects = new HashMap();

public void put(String key, Object value) {
scopeObjects.put(key, value);
}

public Object execute(String script) {
Object result = null;
try {
Context ctx = Context.enter();
Scriptable scope = ctx.initStandardObjects();
for(String key : scopeObjects.keySet()) {
scope.put(key, scope, scopeObjects.get(key));
}
result = ctx.evaluateString(scope, script, "embedded_script", 1, null);
} catch(Exception e) {
e.printStackTrace();
} finally {
Context.exit();
}
return result;
}

public static ScriptSession createInstance() {
return new ScriptSession();
}
}


Using Java 6 standard interface:-
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
* High level wrapper to JDK 6 scripting API.
*/
public class ScriptSession {
private ScriptEngine engine;

private ScriptSession() {
ScriptEngineManager factory = new ScriptEngineManager();
engine = factory.getEngineByName("JavaScript");
}

public void put(String key, Object value) {
engine.put(key, value);
}

public Object execute(String script) {
Object result = null;
try {
result = engine.eval(script);
} catch(Exception e) {
e.printStackTrace();
}
return result;
}

public static ScriptSession createInstance() {
return new ScriptSession();
}
}


Usage:-
ScriptSession ss = ScriptSession.createInstance();
// put all the context objects you want using
// session.put("", );
Object result = ss.execute("javascript as text");

Inside JavaScript you can access all your context objects the same way you would access Java objects.

No comments:

Post a Comment