-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathPyScriptEngine.java
More file actions
257 lines (229 loc) · 9.28 KB
/
PyScriptEngine.java
File metadata and controls
257 lines (229 loc) · 9.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package org.python.jsr223;
import java.lang.reflect.Method;
import org.python.core.*;
import java.io.Reader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import org.python.util.PythonInterpreter;
public class PyScriptEngine extends AbstractScriptEngine implements Compilable, Invocable, AutoCloseable {
private final PythonInterpreter interp;
private final ScriptEngineFactory factory;
PyScriptEngine(ScriptEngineFactory factory) {
this.factory = factory;
interp = PythonInterpreter.threadLocalStateInterpreter(new PyScriptEngineScope(this, context));
}
public Object eval(String script, ScriptContext context) throws ScriptException {
return eval(compileScript(script, context), context);
}
private Object eval(PyCode code, ScriptContext context) throws ScriptException {
try {
interp.setIn(context.getReader());
interp.setOut(context.getWriter());
interp.setErr(context.getErrorWriter());
interp.setLocals(new PyScriptEngineScope(this, context));
// set sys.argv if FILENAME, ARGV attributes are defined
String filename = (String) context.getAttribute(ScriptEngine.FILENAME);
String[] argv = (String[]) context.getAttribute(ScriptEngine.ARGV);
if (argv != null || filename != null) {
PyList pyargv = new PyList();
if (filename != null) {
pyargv.append(Py.java2py(filename));
}
if (argv != null) {
for (int i = 0; i < argv.length; i++) {
pyargv.append(Py.java2py(argv[i]));
}
}
interp.getSystemState().argv = pyargv;
}
return interp.eval(code).__tojava__(Object.class);
} catch (PyException pye) {
throw scriptException(pye);
}
}
public Object eval(Reader reader, ScriptContext context) throws ScriptException {
return eval(compileScript(reader, context), context);
}
public Bindings createBindings() {
return new SimpleBindings();
}
public ScriptEngineFactory getFactory() {
return factory;
}
public CompiledScript compile(String script) throws ScriptException {
return new PyCompiledScript(compileScript(script, context));
}
public CompiledScript compile(Reader reader) throws ScriptException {
return new PyCompiledScript(compileScript(reader, context));
}
private PyCode compileScript(String script, ScriptContext context) throws ScriptException {
try {
String filename = (String) context.getAttribute(ScriptEngine.FILENAME);
if (filename == null) {
return interp.compile(script);
} else {
interp.getLocals().__setitem__(Py.newString("__file__"), Py.newString(filename));
return interp.compile(script, filename);
}
} catch (PyException pye) {
throw scriptException(pye);
}
}
private PyCode compileScript(Reader reader, ScriptContext context) throws ScriptException {
try {
String filename = (String) context.getAttribute(ScriptEngine.FILENAME);
if (filename == null) {
return interp.compile(reader);
} else {
interp.getLocals().__setitem__(Py.newString("__file__"), Py.newString(filename));
return interp.compile(reader, filename);
}
} catch (PyException pye) {
throw scriptException(pye);
}
}
public Object invokeMethod(Object thiz, String name, Object... args) throws ScriptException,
NoSuchMethodException {
try {
interp.setLocals(new PyScriptEngineScope(this, context));
if (!(thiz instanceof PyObject)) {
thiz = Py.java2py(thiz);
}
PyObject method = ((PyObject) thiz).__findattr__(name);
if (method == null) {
throw new NoSuchMethodException(name);
}
//return method.__call__(Py.javas2pys(args)).__tojava__(Object.class);
PyObject result;
if(args != null) {
result = method.__call__(Py.javas2pys(args));
} else {
result = method.__call__();
}
return result.__tojava__(Object.class);
} catch (PyException pye) {
throw scriptException(pye);
}
}
public Object invokeFunction(String name, Object... args) throws ScriptException,
NoSuchMethodException {
try {
interp.setLocals(new PyScriptEngineScope(this, context));
PyObject function = interp.get(name);
if (function == null) {
throw new NoSuchMethodException(name);
}
PyObject result;
if(args != null) {
result = function.__call__(Py.javas2pys(args));
} else {
result = function.__call__();
}
return result.__tojava__(Object.class);
} catch (PyException pye) {
throw scriptException(pye);
}
}
public <T> T getInterface(Class<T> clazz) {
return getInterface(new PyModule("__jsr223__", interp.getLocals()), clazz);
}
public <T> T getInterface(Object obj, Class<T> clazz) {
if (obj == null) {
throw new IllegalArgumentException("object expected");
}
if (clazz == null || !clazz.isInterface()) {
throw new IllegalArgumentException("interface expected");
}
interp.setLocals(new PyScriptEngineScope(this, context));
final PyObject thiz = Py.java2py(obj);
@SuppressWarnings("unchecked")
T proxy = (T) Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[] { clazz },
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
interp.setLocals(new PyScriptEngineScope(PyScriptEngine.this, context));
PyObject pyMethod = thiz.__findattr__(method.getName());
if (pyMethod == null)
throw new NoSuchMethodException(method.getName());
PyObject result;
if(args != null) {
result = pyMethod.__call__(Py.javas2pys(args));
} else {
result = pyMethod.__call__();
}
return result.__tojava__(Object.class);
} catch (PyException pye) {
throw scriptException(pye);
}
}
});
return proxy;
}
private static ScriptException scriptException(PyException pye) {
ScriptException se = null;
try {
pye.normalize();
PyObject type = pye.type;
PyObject value = pye.value;
PyTraceback tb = pye.traceback;
if (__builtin__.isinstance(value, Py.SyntaxError)) {
PyObject filename = value.__findattr__("filename");
PyObject lineno = value.__findattr__("lineno");
PyObject offset = value.__findattr__("offset");
value = value.__findattr__("msg");
se = new ScriptException(
Py.formatException(type, value),
filename == null ? "<script>" : filename.toString(),
lineno == null ? 0 : lineno.asInt(),
offset == null ? 0 : offset.asInt());
} else if (tb != null) {
String filename;
if (tb.tb_frame == null || tb.tb_frame.f_code == null) {
filename = null;
} else {
filename = tb.tb_frame.f_code.co_filename;
}
se = new ScriptException(
Py.formatException(type, value),
filename,
tb.tb_lineno);
} else {
se = new ScriptException(Py.formatException(type, value));
}
se.initCause(pye);
return se;
} catch (Exception ee) {
se = new ScriptException(pye);
}
return se;
}
private class PyCompiledScript extends CompiledScript {
private PyCode code;
PyCompiledScript(PyCode code) {
this.code = code;
}
@Override
public ScriptEngine getEngine() {
return PyScriptEngine.this;
}
@Override
public Object eval(ScriptContext ctx) throws ScriptException {
return PyScriptEngine.this.eval(code, ctx);
}
}
public void close() {
interp.close();
}
}