changelog shortlog tags changeset files revisions annotate raw

src/script/rhino/RhinoScriptFactory.java

changeset 8: 846b10b4db8a
parent:eae6d4ec8bde
author: jason@briggs.net.nz
date: Thu Nov 01 21:59:09 2007 +1300 (2 years ago)
permissions: -rw-r--r--
description: add readme.txt
1package script.rhino;
2
3import script.jython.*;
4import java.io.IOException;
5
6import java.io.StringReader;
7import org.mozilla.javascript.Context;
8import org.mozilla.javascript.NativeJavaObject;
9import org.mozilla.javascript.Script;
10import org.mozilla.javascript.Scriptable;
11
12import org.springframework.scripting.ScriptCompilationException;
13import org.springframework.scripting.ScriptSource;
14
15import script.GenericScriptFactory;
16
17
18/**
19 * Factory for Javascript (Rhino) scripts.
20 *
21 * @author jason
22 */
23public class RhinoScriptFactory extends GenericScriptFactory {
24
25 private Scriptable scope;
26
27 public RhinoScriptFactory(String scriptSourceLocator, String beanName, Class returnType, Scriptable scope) {
28 super(scriptSourceLocator, beanName, returnType);
29
30
31 setScope(scope);
32 }
33
34 /**
35 * Javascript scope to use when running the script.
36 */
37 public void setScope(Scriptable scope) {
38 this.scope = scope;
39 }
40
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();
45 try {
46 Scriptable threadScope = cx.newObject(scope);
47
48 StringReader sr = new StringReader(scriptSource.getScriptAsString());
49
50 Script script = cx.compileReader(sr, "<cmd>", 1, null);
51
52 script.exec(cx, threadScope);
53
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);
57 }
58
59 NativeJavaObject njo = (NativeJavaObject) cx.evaluateString(threadScope, getBeanName(), "<cmd>", 1, null);
60 setScriptResult(njo.unwrap());
61 }
62 catch (Exception e) {
63 throw new ScriptCompilationException("Could not exec rhino script: " + scriptSource, e);
64 }
65 finally {
66 cx.exit();
67 }
68 }
69 }
70
71 return getScriptResult();
72 }
73}