ludc
2025-01-16 986aa62ed00bee39363bab41b4eeb8259d446efd
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.  
 * Use is subject to license terms.
 *
 * Redistribution and use in source and binary forms, with or without modification, are 
 * permitted provided that the following conditions are met: Redistributions of source code 
 * must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of 
 * conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution. Neither the name of the Sun Microsystems nor the names of 
 * is contributors may be used to endorse or promote products derived from this software 
 * without specific prior written permission. 
 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
 
 
/*
 * GroovyScriptEngine.java
 * @author Mike Grogan
 * @author A. Sundararajan
 */
package org.jbpm.pvm.internal.script;
import java.io.*;
import java.util.*;
import javax.script.*;
import groovy.lang.*;
import org.codehaus.groovy.syntax.SyntaxException;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.MetaClassHelper;
import org.codehaus.groovy.runtime.MethodClosure;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.CompilationFailedException;
import java.lang.reflect.*;
 
public class GroovyScriptEngine 
    extends AbstractScriptEngine implements Compilable, Invocable {
 
    private static boolean DEBUG = false;
 
    // script-string-to-generated Class map
    private Map<String, Class> classMap;
    // global closures map - this is used to simulate a single
    // global functions namespace 
    private Map<String, Closure> globalClosures;
    // class loader for Groovy generated classes
    private GroovyClassLoader loader;
    // lazily initialized factory
    private volatile GroovyScriptEngineFactory factory;
 
    // counter used to generate unique global Script class names
    private static int counter;
 
    static {
        counter = 0;
    }
    
    public GroovyScriptEngine() {    
        classMap = Collections.synchronizedMap(new HashMap<String, Class>());
        globalClosures = Collections.synchronizedMap(new HashMap<String, Closure>());
        loader = new GroovyClassLoader(getParentLoader(),
                                       new CompilerConfiguration());
    }
 
    public Object eval(Reader reader, ScriptContext ctx) 
                       throws ScriptException {
        return eval(readFully(reader), ctx);
    }
    
    public Object eval(String script, ScriptContext ctx) 
                       throws ScriptException {
        try {
            return eval(getScriptClass(script), ctx);
        } catch (SyntaxException e) {
            throw new ScriptException(e.getMessage(), 
                                      e.getSourceLocator(), e.getLine());
        } catch (Exception e) {
            if (DEBUG) e.printStackTrace();
            throw new ScriptException(e);
        }
    }
    
    public Bindings createBindings() {
        return new SimpleBindings();
    }
    
    public ScriptEngineFactory getFactory() {
        if (factory == null) {
            synchronized (this) {
                if (factory == null) {
                    factory = new GroovyScriptEngineFactory();
                }
            }
        }
        return factory;
    }
   
    // javax.script.Compilable methods 
    public CompiledScript compile(String scriptSource) throws ScriptException {
        try {
            return new GroovyCompiledScript(this, 
                                    getScriptClass(scriptSource));
        } catch (SyntaxException e) {
            throw new ScriptException(e.getMessage(), 
                                      e.getSourceLocator(), e.getLine());
        } catch (IOException e) {
            throw new ScriptException(e);
        } catch (CompilationFailedException ee) {
            throw new ScriptException(ee);
        }
    }   
    
    public CompiledScript compile(Reader reader) throws ScriptException {
        return compile(readFully(reader));
    }
   
    // javax.script.Invocable methods.
    public Object invokeFunction(String name, Object... args) 
             throws ScriptException, NoSuchMethodException  {
        return invokeImpl(null, name, args);
    }
   
    public Object invokeMethod(Object thiz, String name, Object... args) 
             throws ScriptException, NoSuchMethodException  {
        if (thiz == null) {
            throw new IllegalArgumentException("script object is null");
        }
        return invokeImpl(thiz, name, args);
    }
            
    public <T> T getInterface(Class<T> clasz) {
        return makeInterface(null, clasz);
    }
 
    public <T> T getInterface(Object thiz, Class<T> clasz) {
        if (thiz == null) {
            throw new IllegalArgumentException("script object is null");
        }
        return makeInterface(thiz, clasz);
    }
 
    // package-privates
    Object eval(Class scriptClass, final ScriptContext ctx) throws ScriptException {
        //add context to bindings
        ctx.setAttribute("context", ctx, ScriptContext.ENGINE_SCOPE);
        
        //direct output to ctx.getWriter
        Writer writer = ctx.getWriter();
        ctx.setAttribute("out", (writer instanceof PrintWriter) ? 
                                 writer :
                                 new PrintWriter(writer),
                                 ScriptContext.ENGINE_SCOPE);
        /*
         * We use the following Binding instance so that global variable lookup
         * will be done in the current ScriptContext instance.
         */
        Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) {
                              @Override
                              public Object getVariable(String name) {
                                  synchronized (ctx) {
                                      int scope = ctx.getAttributesScope(name);
                                      if (scope != -1) {
                                          return ctx.getAttribute(name, scope);
                                      }
                                  }
                                  throw new MissingPropertyException(name, getClass());
                              }
                              @Override
                              public void setVariable(String name, Object value) {
                                  synchronized (ctx) {
                                      int scope = ctx.getAttributesScope(name);
                                      if (scope == -1) {    
                                          scope = ScriptContext.ENGINE_SCOPE;
                                      } 
                                      ctx.setAttribute(name, value, scope);
                                  }
                              }
                          };
 
        try {
            Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
 
            // create a Map of MethodClosures from this new script object
            Method[] methods = scriptClass.getMethods();
            Map<String, Closure> closures = new HashMap<String, Closure>();
            for (Method m : methods) {
                String name = m.getName();
                closures.put(name, new MethodClosure(scriptObject, name));
            }
 
            // save all current closures into global closures map
            globalClosures.putAll(closures);
 
            MetaClass oldMetaClass = scriptObject.getMetaClass();
 
            /*
             * We override the MetaClass of this script object so that we can
             * forward calls to global closures (of previous or future "eval" calls)
             * This gives the illusion of working on the same "global" scope.
             */
            scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {
                        @Override
                        public Object invokeMethod(Object object, String name, Object args) {
                            if (args == null) {
                                return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                            }
                            if (args instanceof Tuple) {
                                return invokeMethod(object, name, ((Tuple)args).toArray());
                            }
                            if (args instanceof Object[]) {
                                return invokeMethod(object, name, (Object[]) args);
                            } else {
                                return invokeMethod(object, name, new Object[] { args });
                            }
                        }
 
                        @Override
                        public Object invokeMethod(Object object, String name, Object[] args) {
                            try {
                                return super.invokeMethod(object, name, args);
                            } catch (MissingMethodException mme) {
                                return callGlobal(name, args, ctx);
                            }
                        }
                        @Override
                        public Object invokeStaticMethod(Object object, String name, Object[] args) {
                            try {
                                return super.invokeStaticMethod(object, name, args);
                            } catch (MissingMethodException mme) {
                                return callGlobal(name, args, ctx);
                            }
                        }
                    });
 
            return scriptObject.run();
        } catch (Exception e) {
            throw new ScriptException(e);
        }
    }
 
    Class getScriptClass(String script) 
                         throws SyntaxException, 
                                CompilationFailedException, 
                                IOException {
        Class clazz = classMap.get(script);
        if (clazz != null) {
            return clazz;
        }
       
        InputStream stream = new ByteArrayInputStream(script.getBytes()); 
        clazz = loader.parseClass(stream, generateScriptName());
        classMap.put(script, clazz);
        return clazz;
    }
 
    //-- Internals only below this point
 
    // invokes the specified method/function on the given object.
    private Object invokeImpl(Object thiz, String name, Object... args) 
             throws ScriptException, NoSuchMethodException  {
        if (name == null) {
            throw new NullPointerException("method name is null");
        }
 
        try {
            if (thiz != null) {
                return InvokerHelper.invokeMethod(thiz, name, args);
            } else {
                return callGlobal(name, args);
            }
        } catch (MissingMethodException mme) {
            throw new NoSuchMethodException(mme.getMessage());
        } catch (Exception e) {
            throw new ScriptException(e);
        }
    } 
 
    // call the script global function of the given name
    private Object callGlobal(String name, Object[] args) {
        return callGlobal(name, args, context);
    }
 
    private Object callGlobal(String name, Object[] args, ScriptContext ctx) {
        Closure closure = globalClosures.get(name);
        if (closure != null) {
            return closure.call(args);
        } else {
            // Look for closure valued variable in the 
            // given ScriptContext. If available, call it.
            Object value = ctx.getAttribute(name);
            if (value instanceof Closure) {
                return ((Closure)value).call(args);
            } // else fall thru..
        }
        throw new MissingMethodException(name, getClass(), args);     
    }
 
    // generate a unique name for top-level Script classes
    private synchronized String generateScriptName() {
        return "Script" + (++counter) + ".groovy";
    }
 
    private <T> T makeInterface(Object obj, Class<T> clazz) {
        final Object thiz = obj;
        if (clazz == null || !clazz.isInterface()) {
            throw new IllegalArgumentException("interface Class expected");
        }
        return (T) Proxy.newProxyInstance(
            clazz.getClassLoader(),
            new Class[] { clazz },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method m, Object[] args)
                                     throws Throwable {
                    return invokeImpl(thiz, m.getName(), args);
                }
            });
    }
 
    // determine appropriate class loader to serve as parent loader
    // for GroovyClassLoader instance
    private ClassLoader getParentLoader() {
        // check whether thread context loader can "see" Groovy Script class
        ClassLoader ctxtLoader = Thread.currentThread().getContextClassLoader();
        try {
            Class c = ctxtLoader.loadClass("org.codehaus.groovy.Script");
            if (c == Script.class) {
                return ctxtLoader;
            }
        } catch (ClassNotFoundException cnfe) {
        }
        // exception was thrown or we get wrong class
        return Script.class.getClassLoader();
    }
 
    private String readFully(Reader reader) throws ScriptException {
        char[] arr = new char[8*1024]; // 8K at a time
        StringBuilder buf = new StringBuilder();
        int numChars;
        try {
            while ((numChars = reader.read(arr, 0, arr.length)) > 0) {
                buf.append(arr, 0, numChars);
            }
        } catch (IOException exp) {
            throw new ScriptException(exp);
        }
        return buf.toString();
    }