forked from micw/php-java-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvocablePhpScriptEngine.java
More file actions
319 lines (294 loc) · 11.8 KB
/
Copy pathInvocablePhpScriptEngine.java
File metadata and controls
319 lines (294 loc) · 11.8 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/*-*- mode: Java; tab-width:8 -*-*/
package php.java.script;
/*
* Copyright (C) 2003-2007 Jost Boekemeier
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.lang.reflect.Proxy;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptException;
import php.java.bridge.PhpProcedure;
import php.java.bridge.Util;
import php.java.bridge.http.IContext;
/**
* This class implements the ScriptEngine and the Invocable interface.<p>
* Example:
* <blockquote>
* <code>
* ScriptEngine e = (new ScriptEngineManager()).getEngineByName("php-invocable");<br>
* e.eval(<? function f() {return java_server_name();}?><br>
* System.out.println(((Invocable)e).invokeFunction("f", new Object[]{}));<br>
* ((Closeable)e).close();<br>
* </code>
* </blockquote><br>
* Another example which invokes a remote PHP "method" bound in the closed-over PHP environment. The PHP script "hello.php":
* <blockquote>
* <code>
* <?php require_once("java/Java.inc");<br>
* function f() {return java_server_name();};<br>
* java_call_with_continuation(java_closure());<br>
* ?><br>
* </code>
* </blockquote><br>
* The Java code:
* <blockquote>
* <code>
* ScriptEngine e = (new ScriptEngineManager()).getEngineByName("php-invocable");<br>
* e.eval(new php.java.script.URLReader(new url("http://localhost/hello.php")));<br>
* System.out.println(((Invocable)e).invokeMethod(e.get("php.java.bridge.PhpProcedure"), "f", new Object[]{}));<br>
* ((Closeable)e).close();<br>
* </code>
* </blockquote>
*/
public class InvocablePhpScriptEngine extends AbstractPhpScriptEngine implements Invocable {
private static final String X_JAVABRIDGE_INCLUDE = Util.X_JAVABRIDGE_INCLUDE;
private static final String PHP_JAVA_CONTEXT_CALL_JAVA_CLOSURE = "<?php java_context()->call(java_closure()); ?>";
protected static final Object EMPTY_INCLUDE = "@";
private static boolean registeredHook = false;
private static final List engines = new LinkedList();
private static final String PHP_EMPTY_SCRIPT = "<?php ?>";
/**
* Create a new ScriptEngine with a default context.
*/
public InvocablePhpScriptEngine() {
this(new PhpScriptEngineFactory());
}
/**
* Create a new ScriptEngine from a factory.
* @param factory The factory
* @see #getFactory()
*/
public InvocablePhpScriptEngine(PhpScriptEngineFactory factory) {
super(factory);
}
/**
* Create a new ScriptEngine with bindings.
* @param n the bindings
*/
public InvocablePhpScriptEngine(Bindings n) {
this();
setBindings(n, ScriptContext.ENGINE_SCOPE);
}
/* (non-Javadoc)
* @see javax.script.Invocable#call(java.lang.String, java.lang.Object[])
*/
protected Object invoke(String methodName, Object[] args)
throws ScriptException, NoSuchMethodException {
if (methodName==null) { release(); return null; }
if(scriptClosure==null) {
if (Util.logLevel>4) Util.warn("Evaluating an empty script either because eval() has not been called or release() has been called.");
eval(PHP_EMPTY_SCRIPT);
}
try {
return invoke(scriptClosure, methodName, args);
} catch (php.java.bridge.Request.AbortException e) {
release ();
throw new ScriptException(e);
} catch (NoSuchMethodError e) { // conform to jsr223
throw new NoSuchMethodException(String.valueOf(e.getMessage()));
}
}
/**{@inheritDoc}*/
public Object invokeFunction(String methodName, Object[] args)
throws ScriptException, NoSuchMethodException {
return invoke(methodName, args);
}
private void checkPhpClosure(Object thiz) {
if(thiz==null) throw new IllegalStateException("PHP script did not pass its continuation to us!. Please check if the previous call to eval() reported any errors. Or else check if it called OUR continuation.");
}
/* (non-Javadoc)
* @see javax.script.Invocable#call(java.lang.String, java.lang.Object, java.lang.Object[])
*/
protected Object invoke(Object thiz, String methodName, Object[] args)
throws ScriptException, NoSuchMethodException {
checkPhpClosure(thiz);
PhpProcedure proc = (PhpProcedure)(Proxy.getInvocationHandler(thiz));
try {
return proc.invoke(script, methodName, args);
} catch (ScriptException e) {
throw e;
} catch (NoSuchMethodException e) {
throw e;
} catch (RuntimeException e) {
throw e; // don't wrap RuntimeException
} catch (NoSuchMethodError e) { // conform to jsr223
throw new NoSuchMethodException(String.valueOf(e.getMessage()));
} catch (Error er) {
throw er;
} catch (Throwable e) {
throw new PhpScriptException("Invocation threw exception ", e);
}
}
/**{@inheritDoc}*/
public Object invokeMethod(Object thiz, String methodName, Object[] args)
throws ScriptException, NoSuchMethodException {
return invoke(thiz, methodName, args);
}
/**{@inheritDoc}*/
public Object getInterface(Class clasz) {
checkPhpClosure(script);
return getInterface(script, clasz);
}
/**{@inheritDoc}*/
public Object getInterface(Object thiz, Class clasz) {
checkPhpClosure(thiz);
Class[] interfaces = clasz==null?Util.ZERO_PARAM:new Class[]{clasz};
return PhpProcedure.createProxy(interfaces, (PhpProcedure)Proxy.getInvocationHandler(thiz));
}
protected Reader getLocalReader(Reader reader, boolean embedJavaInc) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(out);
String stdHeader = embedJavaInc ? null : ((IContext)getContext()).getRedirecturl("/JavaBridge");
Reader localReader = new StringReader(getStandardHeader(stdHeader));
char[] buf = new char[Util.BUF_SIZE];
int c;
try {
/* header: <? require_once("http://localhost:<ourPort>/JavaBridge/java/Java.inc"); ?> */
while((c=localReader.read(buf))>0) w.write(buf, 0, c);
localReader.close(); localReader = null;
/* the script: */
while((c=reader.read(buf))>0) w.write(buf, 0, c);
/* get the default, top-level, closure and call it, to stop the script from terminating */
localReader = new StringReader(PHP_JAVA_CONTEXT_CALL_JAVA_CLOSURE);
while((c=localReader.read(buf))>0) w.write(buf, 0, c);
localReader.close(); localReader = null;
w.close(); w = null;
/* now evaluate our script */
localReader = new InputStreamReader(new ByteArrayInputStream(out.toByteArray()));
return localReader;
} finally {
if (w!=null) try {w.close();} catch (IOException e) {/*ignore*/}
}
}
protected Object doEvalPhp(Reader reader, ScriptContext context) throws ScriptException {
if (reader instanceof URLReader) return eval((URLReader)reader, context);
if((continuation != null) || (reader == null) ) release();
if(reader==null) return null;
setNewContextFactory();
env.put(X_JAVABRIDGE_INCLUDE, EMPTY_INCLUDE);
Reader localReader = null;
try {
localReader = getLocalReader(reader, false);
this.script = doEval(localReader, context);
if (this.script!=null) {
/* get the proxy, either the one from the user script or our default proxy */
this.scriptClosure = script;
}
} catch (Exception e) {
Util.printStackTrace(e);
if (e instanceof RuntimeException) throw (RuntimeException)e;
if (e instanceof ScriptException) throw (ScriptException)e;
throw new ScriptException(e);
} finally {
if(localReader!=null) try { localReader.close(); } catch (IOException e) {/*ignore*/}
handleRelease();
}
return resultProxy;
}
protected Object doEvalCompiledPhp(Reader reader, ScriptContext context) throws ScriptException {
if((continuation != null) || (reader == null) ) release();
if(reader==null) return null;
setNewContextFactory();
env.put(X_JAVABRIDGE_INCLUDE, EMPTY_INCLUDE);
try {
this.script = doEval(reader, context);
if (this.script!=null) {
/* get the proxy, either the one from the user script or our default proxy */
this.scriptClosure = script;
}
} catch (Exception e) {
Util.printStackTrace(e);
if (e instanceof RuntimeException) throw (RuntimeException)e;
if (e instanceof ScriptException) throw (ScriptException)e;
throw new ScriptException(e);
} finally {
handleRelease();
}
return resultProxy;
}
protected Object eval(URLReader reader, ScriptContext context) throws ScriptException {
if((continuation != null) || (reader == null) ) release();
if(reader==null) return null;
setNewContextFactory();
env.put(X_JAVABRIDGE_INCLUDE, EMPTY_INCLUDE);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(out);
try {
this.script = doEval(reader, context);
if (this.script!=null) {
/* get the proxy, either the one from the user script or our default proxy */
this.scriptClosure = script;
}
} catch (Exception e) {
Util.printStackTrace(e);
if (e instanceof RuntimeException) throw (RuntimeException)e;
if (e instanceof ScriptException) throw (ScriptException)e;
throw new ScriptException(e);
} finally {
if(w!=null) try { w.close(); } catch (IOException e) {/*ignore*/}
handleRelease();
}
return resultProxy;
}
protected void handleRelease() {
// make sure to properly release them upon System.exit().
synchronized(engines) {
if(!registeredHook) {
registeredHook = true;
try {
Runtime.getRuntime().addShutdownHook(new Util.Thread() {
public void run() {
if (engines==null) return;
synchronized(engines) {
for(Iterator ii = engines.iterator(); ii.hasNext(); ii.remove()) {
InvocablePhpScriptEngine e = (InvocablePhpScriptEngine) ii.next();
e.releaseInternal();
}
}
}});
} catch (SecurityException e) {/*ignore*/}
}
engines.add(this);
}
}
private void releaseInternal() {
super.release();
}
/**{@inheritDoc}*/
public void release() {
synchronized(engines) {
releaseInternal();
engines.remove(this);
}
}
}