4import java.io.IOException;
6import java.io.StringReader;
7import org.mozilla.javascript.Context;
8import org.mozilla.javascript.NativeJavaObject;
9import org.mozilla.javascript.Script;
10import org.mozilla.javascript.Scriptable;
12import org.springframework.scripting.ScriptCompilationException;
13import org.springframework.scripting.ScriptSource;
15import script.GenericScriptFactory;
19 * Factory for Javascript (Rhino) scripts.
23public class RhinoScriptFactory extends GenericScriptFactory {
25 private Scriptable scope;
27 public RhinoScriptFactory(String scriptSourceLocator, String beanName, Class returnType, Scriptable scope) {
28 super(scriptSourceLocator, beanName, returnType);
35 * Javascript scope to use when running the script.
37 public void setScope(Scriptable scope) {
41 public Object getScriptedObject(ScriptSource scriptSource, Class[] actualInterfaces) throws IOException, ScriptCompilationException {
42 synchronized (getScriptClassMonitor()) {
43 if (getScriptResult() == null || scriptSource.isModified()) {
44 Context cx = Context.enter();
46 Scriptable threadScope = cx.newObject(scope);
48 StringReader sr = new StringReader(scriptSource.getScriptAsString());
50 Script script = cx.compileReader(sr, "<cmd>", 1, null);
52 script.exec(cx, threadScope);
54 if (getScriptInterfaces() != null && getScriptInterfaces().length > 0) {
55 String tmpscript = getBeanName() + " = new Packages." + getScriptInterfaces()[0].getName() + "(" + getBeanName() + ");";
56 cx.evaluateString(threadScope, tmpscript.toString(), "<cmd>", 1, null);
59 NativeJavaObject njo = (NativeJavaObject) cx.evaluateString(threadScope, getBeanName(), "<cmd>", 1, null);
60 setScriptResult(njo.unwrap());
63 throw new ScriptCompilationException("Could not exec rhino script: " + scriptSource, e);
71 return getScriptResult();