protected Object evaluateExpression(Object expression, Map<String, Object> parameters) { try { Object result = null; StringWriter writer = new StringWriter(); ScriptContext context = new SimpleScriptContext(); for (Map.Entry<String, Object> property : engineProperties.entrySet()) { context.setAttribute(property.getKey(), property.getValue(), ScriptContext.ENGINE_SCOPE); } Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); bindings.putAll(parameters); context.setBindings(bindings, ScriptContext.ENGINE_SCOPE); context.setWriter(writer); if (expression instanceof CompiledScript) { logger.debug("About to evaluate compiled expression {} with bindings {} on engine", expression, parameters, scriptEngine); result = ((CompiledScript) expression).eval(context); } else { logger.debug("About to evaluate expression {} with bindings {} on engine", expression, parameters, scriptEngine); result = scriptEngine.eval(expression.toString(), context); } if (result == null) { result = writer.toString(); } return result; } catch (ScriptException e) { throw new RuntimeException("Error when evaluating script", e); } }
@Override public Object eval(Reader reader, ScriptContext context) throws ScriptException { try { // Get engine bindings and send them to Clojure Bindings engineBindings = context.getBindings(ScriptContext.ENGINE_SCOPE); engineBindings.entrySet().forEach((entry) -> Var.intern(Namespace.findOrCreate(NAMESPACE_SYMBOL), Symbol.create(entry.getKey().intern()), entry.getValue(), true)); Var.pushThreadBindings( RT.map(RT.CURRENT_NS, RT.CURRENT_NS.deref(), RT.IN, new LineNumberingPushbackReader(context.getReader()), RT.OUT, context.getWriter(), RT.ERR, context.getErrorWriter())); Object result = Compiler.load(reader); return result; } catch (Exception e) { throw new ScriptException(e); } finally { Namespace.remove(NAMESPACE_SYMBOL); } }
Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) { @Override public Object getVariable(String name) {
private void registerBindingTypes(final ScriptContext context) { if (typeCheckingEnabled) { final Map<String, ClassNode> variableTypes = new HashMap<>(); clearVarTypes(); // use null for the classtype if the binding value itself is null - not fully sure if that is // a sound way to deal with that. didn't see a class type for null - maybe it should just be // unknown and be "Object". at least null is properly being accounted for now. context.getBindings(ScriptContext.GLOBAL_SCOPE).forEach((k, v) -> variableTypes.put(k, null == v ? null : ClassHelper.make(v.getClass()))); context.getBindings(ScriptContext.ENGINE_SCOPE).forEach((k, v) -> variableTypes.put(k, null == v ? null : ClassHelper.make(v.getClass()))); COMPILE_OPTIONS.get().put(COMPILE_OPTIONS_VAR_TYPES, variableTypes); } }
public class MyServlet extends HttpServlet { private ThreadLocal<ScriptEngine> engineHolder; @Override public void init() throws ServletException { engineHolder = new ThreadLocal<ScriptEngine>() { @Override protected ScriptEngine initialValue() { return new ScriptEngineManager().getEngineByName("nashorn"); } }; } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { try (PrintWriter writer = res.getWriter()) { ScriptContext newContext = new SimpleScriptContext(); newContext.setBindings(engineHolder.get().createBindings(), ScriptContext.ENGINE_SCOPE); Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE); engineScope.put("writer", writer); Object value = engineHolder.get().eval("writer.print('Hello, World!');", engineScope); writer.close(); } catch (IOException | ScriptException ex) { Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex); } } }
@Override @SuppressWarnings("unchecked") public Object eval(ScriptContext context) throws ScriptException { try { Map<String, Object> map = new HashMap<String, Object>(); for (Iterator it = context.getScopes().iterator(); it.hasNext();) { int scope = ((Integer) it.next()).intValue(); Bindings bindings = context.getBindings(scope); Set keys = bindings.keySet(); for (Object key : keys) { map.put((String) key, bindings.get(key)); } } return this.expression.execute(map); } catch (Exception e) { throw new ScriptException(e); } }
/** * Resets the entire {@code GremlinGroovyScriptEngine} by clearing script caches, recreating the classloader, * clearing bindings. */ public void reset() { internalReset(); getContext().getBindings(ScriptContext.ENGINE_SCOPE).clear(); }
private static void test6() throws ScriptException { NashornScriptEngine engine = createEngine(); ScriptContext defaultContext = engine.getContext(); defaultContext.getBindings(ScriptContext.GLOBAL_SCOPE).put("foo", "hello"); ScriptContext customContext = new SimpleScriptContext(); customContext.setBindings(defaultContext.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.ENGINE_SCOPE); Bindings bindings = new SimpleBindings(); bindings.put("foo", "world"); customContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE); // engine.eval("foo = 23;"); // overrides foo in all contexts, why??? engine.eval("print(foo)"); // hello engine.eval("print(foo)", customContext); // world engine.eval("print(foo)", defaultContext); // hello }
private static void test3() throws ScriptException { NashornScriptEngine engine = createEngine(); ScriptContext defaultContext = engine.getContext(); Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); SimpleScriptContext context = new SimpleScriptContext(); context.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); engine.eval("function foo() { print('bar') };", context); engine.eval("foo();", context); Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); System.out.println(bindings.get("foo")); System.out.println(context.getAttribute("foo")); }
private static void test4() throws ScriptException { NashornScriptEngine engine = createEngine(); engine.eval("function foo() { print('bar') };"); ScriptContext defaultContext = engine.getContext(); Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); SimpleScriptContext context = new SimpleScriptContext(); context.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); engine.eval("foo();", context); System.out.println(context.getAttribute("foo")); }
Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException { final Binding binding = new Binding(context.getBindings(ScriptContext.ENGINE_SCOPE)) { @Override public Object getVariable(String name) {
Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) { @Override public Object getVariable(String name) {
private static void test8() throws ScriptException { NashornScriptEngine engine = createEngine(); engine.eval("var obj = { foo: 23 };"); ScriptContext defaultContext = engine.getContext(); Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); SimpleScriptContext context1 = new SimpleScriptContext(); context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); SimpleScriptContext context2 = new SimpleScriptContext(); context2.getBindings(ScriptContext.ENGINE_SCOPE).put("obj", defaultBindings.get("obj")); engine.eval("obj.foo = 44;", context1); engine.eval("print(obj.foo);", context1); engine.eval("print(obj.foo);", context2); }
private static void test7() throws ScriptException { NashornScriptEngine engine = createEngine(); engine.eval("var foo = 23;"); ScriptContext defaultContext = engine.getContext(); Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); SimpleScriptContext context1 = new SimpleScriptContext(); context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); SimpleScriptContext context2 = new SimpleScriptContext(); context2.getBindings(ScriptContext.ENGINE_SCOPE).put("foo", defaultBindings.get("foo")); engine.eval("foo = 44;", context1); engine.eval("print(foo);", context1); engine.eval("print(foo);", context2); }
bindings.putAll(scriptEngine.getContext().getBindings(ScriptContext.ENGINE_SCOPE)); bindings.put(this.translator.getTraversalSource().toString(), this.traversalSource); translatedTraversal = (Traversal.Admin<?, ?>) scriptEngine.eval(bytecode, bindings, this.translator.getTraversalSource().toString());
private static void test5() throws ScriptException { NashornScriptEngine engine = createEngine(); engine.eval("var obj = { foo: 'foo' };"); engine.eval("function printFoo() { print(obj.foo) };"); ScriptContext defaultContext = engine.getContext(); Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); SimpleScriptContext context1 = new SimpleScriptContext(); context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); SimpleScriptContext context2 = new SimpleScriptContext(); context2.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); engine.eval("obj.foo = 'bar';", context1); engine.eval("printFoo();", context1); engine.eval("printFoo();", context2); }
/** {@inheritDoc} */ public void set(final String name, final Object value) { int scope = scriptContext.getAttributesScope(name); if (scope == -1) { // not found, default to engine scope = ScriptContext.ENGINE_SCOPE; } scriptContext.getBindings(scope).put(name , value); }
/** {@inheritDoc} */ public boolean has(final String name) { Bindings bnd = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); return bnd.containsKey(name); }
@Override public void customizeBindings(final ScriptContext context, final int scope, final Map<String, Object> customizations) { Bindings bindings = context.getBindings(scope); applyDefaultBindings(bindings); for (Entry<String, Object> entry : customizations.entrySet()) { bindings.put(entry.getKey(), entry.getValue()); } }
public Object evaluate(Serializable expression, ScriptContext context) throws ScriptException { try { return MVEL.executeExpression(expression, context.getBindings(ScriptContext.ENGINE_SCOPE)); } catch (Exception e) { throw new ScriptException(e); } } }