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 ValueExpression resolveVariable(String variableName) { int scope = scriptContext.getAttributesScope(variableName); if (scope != -1) { Object value = scriptContext.getAttribute(variableName, scope); if (value instanceof ValueExpression) { // Just return the existing ValueExpression return (ValueExpression) value; } else { // Create a new ValueExpression based on the variable value return expressionFactory.createValueExpression(value, Object.class); } } return null; }
@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); } }
private ELContext createElContext(final ScriptContext scriptCtx) { Object existingELCtx = scriptCtx.getAttribute("elcontext"); if (existingELCtx instanceof ELContext) { return (ELContext) existingELCtx; scriptCtx.setAttribute("context", scriptCtx, ScriptContext.ENGINE_SCOPE); scriptCtx.setAttribute("out:print", getPrintMethod(), ScriptContext.ENGINE_SCOPE); scriptCtx.setAttribute("lang:import", getImportMethod(), ScriptContext.ENGINE_SCOPE); scriptCtx.setAttribute("elcontext", elContext, ScriptContext.ENGINE_SCOPE); return elContext;
public String eval(String line) throws ScriptException { final ScriptContext context = engine.getContext(); final StringWriter sw = new StringWriter(); context.setWriter(new PrintWriter(sw)); engine.eval(line, context); final String result = sw.toString(); return result; } }
public static void main(String[] args) throws ScriptException, IOException { StringWriter writer = new StringWriter(); //ouput will be stored here ScriptEngineManager manager = new ScriptEngineManager(); ScriptContext context = new SimpleScriptContext(); context.setWriter(writer); //configures output redirection ScriptEngine engine = manager.getEngineByName("python"); engine.eval(new FileReader("numbers.py"), context); System.out.println(writer.toString()); }
@Override public SpicyPlate spicyPlate( SpicyContext globalContext, String template ) { NullArgumentException.ensureNotNull( "Global context", globalContext ); NullArgumentException.ensureNotEmpty( "Template", template ); StringWriter errorWriter = new StringWriter(); try { ScriptContext scriptContext = new SimpleScriptContext(); scriptContext.setErrorWriter( errorWriter ); scriptContext.setAttribute( "__spicy_plates_raw_template", template, ScriptContext.ENGINE_SCOPE ); Object erb = ruby.eval( new InputStreamReader( getClass().getResourceAsStream( "template_reader.rb" ) ), scriptContext ); return new ERubySpicyPlate( ruby, globalContext, erb ); } catch ( ScriptException ex ) { throw new SpicyPlatesFailure( "Unable to create ERB object from template content", ex ).andLogError( "Ruby error output was:\n" + Strings.indent( errorWriter.toString(), 1, " ", "| " ) ); } }
@Override public <T> T executeTemplate(String template, HttpRequest request, Class<? extends DTO<T>> dtoClass) { T result = null; try { Writer writer = new StringWriter(); ScriptContext context = engine.getContext(); context.setWriter(writer); context.setAttribute("request", new HttpRequestTemplateObject(request), ScriptContext.ENGINE_SCOPE); engine.eval(template); logFormatter.info(TEMPLATE_GENERATED, request, "generated output:{}from template:{}for request:{}", writer.toString(), template, request); result = httpTemplateOutputDeserializer.deserializer(request, writer.toString(), dtoClass); } catch (Exception e) { throw new RuntimeException(formatLogMessage("Exception transforming template:{}for request:{}", template, request), e); } return result; } }
public void testEvalWithReader() throws ScriptException, FileNotFoundException { //Check that multiple evals don't cause an NPE. //See issue http://bugs.jython.org/issue1536 final ScriptEngineManager manager = new ScriptEngineManager(); final String engineType = "jython"; final ScriptEngine engine = manager.getEngineByName(engineType); final StringWriter stdout = new StringWriter(); final StringWriter stderr = new StringWriter(); engine.getContext().setWriter(stdout); engine.getContext().setErrorWriter(stderr); final Bindings bindings = new SimpleBindings(); bindings.put("firstLevelNodes", 10); bindings.put("secondLevelNodes", 5); engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); final Reader dfsScript = new FileReader("tests/python/dfs.py"); for (int i = 1; i <= 10; i++) { engine.eval(dfsScript); assertEquals(61, engine.get("result")); } }
public EmbeddedScriptEngine(String name, ScriptEngine engine) { this.name = name; this.engine = engine; this.ctx = new SimpleScriptContext(); ctx.setWriter(new StringWriter()); ctx.setErrorWriter(new StringWriter()); ctx.setReader(new StringReader("")); }
public ScriptHandler(GVRContext gvrContext) { prompt = ""; mScriptEngine = gvrContext.getScriptManager().getEngine(GVRScriptManager.LANG_JAVASCRIPT); mScriptContext = mScriptEngine.getContext(); mWriter = new StringWriter(); mScriptContext.setWriter(mWriter); mScriptContext.setErrorWriter(mWriter); }
String javaScriptExpression = "sayHello(name);"; Reader javaScriptFile = new StringReader( "function sayHello(name) {\n" + " println('Hello, '+name+'!');\n" + "}"); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory .getEngineByName("JavaScript"); ScriptContext context = engine.getContext(); context.setAttribute("name", "JavaScript", ScriptContext.ENGINE_SCOPE); engine.eval(javaScriptFile); engine.eval(javaScriptExpression);
ScriptEngineManager mgr = new ScriptEngineManager(); engineName = cl.getOptionValue(engine.getOpt()); ScriptEngine engine = mgr.getEngineByName(engineName); if (engine == null) { shellState.printException(new Exception(engineName + " not found")); ScriptContext ctx = new SimpleScriptContext(); Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); putConnector(b, shellState.getAccumuloClient()); b.put("client", shellState.getAccumuloClient()); ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("nashorn"); ScriptContext ctx = new SimpleScriptContext(); ctx.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE); engine.eval("function hello() { return 'Hello!'; }", ctx); engine.setContext(ctx); ((Invocable) engine).invokeFunction("hello");
ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("nashorn"); ScriptContext context = new SimpleScriptContext(); int scope = context.getScopes().get(0); context.setAttribute("japan", 100, scope); context.setAttribute("london", 10, scope); context.setAttribute("jhon", -10, scope); context.setAttribute("last", 1000, scope); String str = "usa_newyork= japan / london * 44 + jhon < last - 987"; Object usa_newyork = engine.eval(str, context); System.out.println(usa_newyork);
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 }
ScriptEngine engine = enginePool.getEngine(); try { ScriptContext context = engine.getContext(); context.setAttribute("page", page, ScriptContext.ENGINE_SCOPE); context.setAttribute("config", site, ScriptContext.ENGINE_SCOPE); try { switch (language) { case JavaScript: engine.eval(defines + "\n" + script, context); RubyHash oRuby = (RubyHash) engine.eval(defines + "\n" + script, context); Iterator itruby = oRuby.entrySet().iterator(); while (itruby.hasNext()) { e.printStackTrace();
public InteractiveConsole(String kernel) { ScriptEngineManager manager = new ScriptEngineManager(); engine = manager.getEngineByName(kernel); if (engine == null) { System.out.println("Classpath is " + System.getProperty("java.class.path")); throw new RuntimeException("ScriptEngine '"+kernel+"' not found. Please check your classpath."); } engine.getContext().setWriter(stdoutWriter); engine.getContext().setErrorWriter(stderrWriter); }
scriptEngine = cachedEngines.get(language); if (scriptEngine == null) { scriptEngine = scriptEngineManager.getEngineByName(language); scriptEngine.getContext().setAttribute("#jsr223.groovy.engine.keep.globals", "weak", ScriptContext.ENGINE_SCOPE); } catch (Exception ignore) { Object threadingParameter = scriptEngine.getFactory().getParameter("THREADING"); if (threadingParameter != null) { scriptEngine = scriptEngineManager.getEngineByName(language);
scriptEngine.getContext().setWriter(writer); scriptEngine.put("catalog", catalog); scriptEngine.put("connection", connection); scriptEngine.put("chain", chain);