List of usage examples for javax.script SimpleScriptContext SimpleScriptContext
public SimpleScriptContext()
From source file:org.openscore.lang.runtime.bindings.ScriptEvaluator.java
public Serializable evalExpr(String expr, Map<String, ? extends Serializable> context) { ScriptContext scriptContext = new SimpleScriptContext(); for (Map.Entry<String, ? extends Serializable> entry : context.entrySet()) { scriptContext.setAttribute(entry.getKey(), entry.getValue(), ScriptContext.ENGINE_SCOPE); }// w w w . j av a 2s.c o m if (scriptContext.getAttribute(TRUE) == null) scriptContext.setAttribute(TRUE, Boolean.TRUE, ScriptContext.ENGINE_SCOPE); if (scriptContext.getAttribute(FALSE) == null) scriptContext.setAttribute(FALSE, Boolean.FALSE, ScriptContext.ENGINE_SCOPE); try { return (Serializable) engine.eval(expr, scriptContext); } catch (ScriptException e) { ScriptException scriptException = new ScriptException(e); throw new RuntimeException("Error in running script expression or variable reference, for expression: '" + expr + "', Script exception is: \n" + scriptException.getMessage(), scriptException); } }
From source file:io.lavagna.service.ApiHooksService.java
private static void executeScript(String name, CompiledScript script, Map<String, Object> scope) { try {//from ww w. ja v a 2 s . c o m ScriptContext newContext = new SimpleScriptContext(); Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE); engineScope.putAll(scope); engineScope.put("log", LOG); engineScope.put("GSON", Json.GSON); engineScope.put("restTemplate", new RestTemplate()); script.eval(newContext); } catch (ScriptException ex) { LOG.warn("Error while executing script " + name, ex); } }
From source file:org.nuxeo.connect.connector.http.proxy.NashornProxyPacResolver.java
@Override public String[] findPacProxies(String url) { ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); ScriptContext context = new SimpleScriptContext(); engine.setContext(context); // set as default context, for invokeFunctino SimpleBindings bindings = new SimpleBindings(); context.setBindings(bindings, ScriptContext.ENGINE_SCOPE); try {/*w ww . j av a 2 s . c o m*/ // Register internet functions as Java upcalls engine.eval("var NashornProxyPacResolver = Java.type('" + getClass().getName() + "');" + "var dnsResolve = NashornProxyPacResolver.dnsResolve;" + "var myIpAddress = NashornProxyPacResolver.myIpAddress"); // Register others pac methods engine.eval(getFileReader(PAC_FUNCTIONS_FILE)); // Register remote pac function engine.eval(getRemotePacBodyReader()); // Call and return pac resolution function String proxies = (String) ((Invocable) engine).invokeFunction(EXEC_PAC_FUNC, url, getHost(url)); return proxies.split(";"); } catch (IOException | ScriptException | NoSuchMethodException e) { log.warn(e, e); } return null; }
From source file:be.solidx.hot.JSR223ScriptExecutor.java
@Override public Object execute(Script<CompiledScript> script) throws ScriptException { try {//from w w w.java 2 s . c om ScriptEngine scriptEngine = getEngine(); CompiledScript compiledScript = getCachedScript(script); ScriptContext scriptContext = new SimpleScriptContext(); executePreExecuteScripts(scriptContext); Object object = compiledScript.eval(scriptContext); if (object == null) return scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE); return object; } catch (javax.script.ScriptException e) { throw new ScriptException(e); } }
From source file:org.apache.sling.scripting.sightly.js.impl.JsEnvironment.java
public void runResource(Resource scriptResource, Bindings globalBindings, Bindings arguments, UnaryCallback callback) {/*from w ww . j a va 2s . co m*/ ScriptContext scriptContext = new SimpleScriptContext(); CommonJsModule module = new CommonJsModule(); Bindings scriptBindings = buildBindings(scriptResource, globalBindings, arguments, module); scriptContext.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE); scriptContext.setAttribute(ScriptEngine.FILENAME, scriptResource.getPath(), ScriptContext.ENGINE_SCOPE); runScript(scriptResource, scriptContext, callback, module); }
From source file:be.solidx.hot.JSR223ScriptExecutor.java
@Override public Object execute(Script<CompiledScript> script, Map<String, Object> contextVars) throws ScriptException { try {//from w w w . ja va 2 s . c om ScriptEngine scriptEngine = getEngine(); Bindings bindings = scriptEngine.createBindings(); ScriptContext scriptContext = new SimpleScriptContext(); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); bindings.putAll(contextVars); executePreExecuteScripts(scriptContext); CompiledScript compiledScript = getCachedScript(script); Object object = compiledScript.eval(scriptContext); if (object == null) return bindings; return object; } catch (javax.script.ScriptException e) { throw new ScriptException(e); } }
From source file:org.apache.accumulo.shell.commands.ScriptCommand.java
@Override public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }//from w ww.j a v a 2s . c om ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:org.apache.accumulo.core.util.shell.commands.ScriptCommand.java
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }//from w ww .j a va 2 s .c o m ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:org.fireflow.engine.modules.script.ScriptEngineHelper.java
private static Object evaluateJSR233Expression(RuntimeContext rtCtx, Expression fireflowExpression, Map<String, Object> contextObjects) { ScriptEngine scriptEngine = rtCtx.getScriptEngine(fireflowExpression.getLanguage()); ScriptContext scriptContext = new SimpleScriptContext(); Bindings engineScope = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); engineScope.putAll(contextObjects);//ww w . java 2s. c o m try { Object result = scriptEngine.eval(fireflowExpression.getBody(), scriptContext); return result; } catch (ScriptException e) { throw new RuntimeException("Can NOT evaluate the expression. ", e); } }
From source file:org.jahia.services.render.scripting.JSR223Script.java
/** * Execute the script and return the result as a string * * @param resource resource to display//from w ww .ja v a2 s .c o m * @param context * @return the rendered resource * @throws org.jahia.services.render.RenderException */ public String execute(Resource resource, RenderContext context) throws RenderException { ScriptEngine scriptEngine = null; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(view.getModule().getChainedClassLoader()); try { scriptEngine = ScriptEngineUtils.getInstance().scriptEngine(view.getFileExtension()); if (scriptEngine != null) { ScriptContext scriptContext = new SimpleScriptContext(); final Bindings bindings = new SimpleBindings(); Enumeration<?> attrNamesEnum = context.getRequest().getAttributeNames(); while (attrNamesEnum.hasMoreElements()) { String currentAttributeName = (String) attrNamesEnum.nextElement(); if (!"".equals(currentAttributeName)) { bindings.put(currentAttributeName, context.getRequest().getAttribute(currentAttributeName)); } } bindings.put("params", context.getRequest().getParameterMap()); Reader scriptContent = null; try { InputStream scriptInputStream = getViewInputStream(); if (scriptInputStream != null) { scriptContent = new InputStreamReader(scriptInputStream); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); // The following binding is necessary for Javascript, which doesn't offer a console by default. bindings.put("out", new PrintWriter(scriptContext.getWriter())); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptEngine.eval(scriptContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); return writer.toString().trim(); } else { throw new RenderException( "Error while retrieving input stream for the resource " + view.getPath()); } } catch (ScriptException e) { throw new RenderException("Error while executing script " + view.getPath(), e); } catch (IOException e) { throw new RenderException( "Error while retrieving input stream for the resource " + view.getPath(), e); } finally { if (scriptContent != null) { IOUtils.closeQuietly(scriptContent); } } } } catch (ScriptException e) { logger.error(e.getMessage(), e); } finally { Thread.currentThread().setContextClassLoader(tccl); } return null; }