List of usage examples for javax.script ScriptEngine getBindings
public Bindings getBindings(int scope);
From source file:be.solidx.hot.JSR223ScriptExecutor.java
@Override public Object execute(Script<CompiledScript> script) throws ScriptException { try {/*w ww .ja va 2s. co m*/ 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:tk.elevenk.restfulrobot.testcase.TestCase.java
/** * Runs all actions in the test case/*from w w w . j av a2s . c om*/ * * @return * @throws Exception */ public void runTest(ScriptEngine _engine) { // check that the test is not already running if (!running) { // prepare bindings before running test this.bindings = _engine.getBindings(ScriptContext.ENGINE_SCOPE); // create empty response and request for bindings this.buildRequest(null); this.bindings.put("Response", this.response); // run the script runtime = System.nanoTime(); this.runScript(scriptFileName); runtime = System.nanoTime() - runtime; } }
From source file:org.apache.nifi.processors.script.ExecuteScript.java
/** * Evaluates the given script body (or file) using the current session, context, and flowfile. The script * evaluation expects a FlowFile to be returned, in which case it will route the FlowFile to success. If a script * error occurs, the original FlowFile will be routed to failure. If the script succeeds but does not return a * FlowFile, the original FlowFile will be routed to no-flowfile * * @param context the current process context * @param sessionFactory provides access to a {@link ProcessSessionFactory}, which * can be used for accessing FlowFiles, etc. * @throws ProcessException if the scripted processor's onTrigger() method throws an exception *//*from w ww. j ava2 s . c o m*/ @Override public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException { synchronized (scriptingComponentHelper.isInitialized) { if (!scriptingComponentHelper.isInitialized.get()) { scriptingComponentHelper.createResources(); } } ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll(); ComponentLog log = getLogger(); if (scriptEngine == null) { // No engine available so nothing more to do here return; } ProcessSession session = sessionFactory.createSession(); try { try { Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (bindings == null) { bindings = new SimpleBindings(); } bindings.put("session", session); bindings.put("context", context); bindings.put("log", log); bindings.put("REL_SUCCESS", REL_SUCCESS); bindings.put("REL_FAILURE", REL_FAILURE); // Find the user-added properties and set them on the script for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) { if (property.getKey().isDynamic()) { // Add the dynamic property bound to its full PropertyValue to the script engine if (property.getValue() != null) { bindings.put(property.getKey().getName(), context.getProperty(property.getKey())); } } } scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); // Execute any engine-specific configuration before the script is evaluated ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap .get(scriptingComponentHelper.getScriptEngineName().toLowerCase()); // Evaluate the script with the configurator (if it exists) or the engine if (configurator != null) { configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules()); } else { scriptEngine.eval(scriptToRun); } // Commit this session for the user. This plus the outermost catch statement mimics the behavior // of AbstractProcessor. This class doesn't extend AbstractProcessor in order to share a base // class with InvokeScriptedProcessor session.commit(); } catch (ScriptException e) { throw new ProcessException(e); } } catch (final Throwable t) { // Mimic AbstractProcessor behavior here getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t }); session.rollback(true); throw t; } finally { scriptingComponentHelper.engineQ.offer(scriptEngine); } }
From source file:be.solidx.hot.JSR223ScriptExecutor.java
@Override public Object execute(Script<CompiledScript> script, Writer writer) throws ScriptException { try {/*www . j a v a 2s . c o m*/ ScriptEngine scriptEngine = getEngine(); CompiledScript compiledScript = getCachedScript(script); SimpleScriptContext simpleScriptContext = new SimpleScriptContext(); executePreExecuteScripts(simpleScriptContext); simpleScriptContext.setWriter(writer); Object object = compiledScript.eval(simpleScriptContext); writer.flush(); if (object == null) return scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE); return object; } catch (Exception e) { throw new ScriptException(e); } }
From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java
/** * Execute the Sass Compilation Ruby Script. * * @param sassScript//from w w w . j ava 2 s .c om * the sass script * @throws MojoExecutionException * the mojo execution exception * @throws MojoFailureException * the mojo failure exception */ protected void executeSassScript(final String sassScript) throws MojoExecutionException, MojoFailureException { if (this.skip) { return; } final Log log = this.getLog(); System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe"); log.debug("Execute Sass Ruby script:\n\n" + sassScript + "\n\n"); final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby"); try { final CompilerCallback compilerCallback = new CompilerCallback(log); jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback); jruby.eval(sassScript); if (this.failOnError && compilerCallback.hadError()) { throw new MojoFailureException("Sass compilation encountered errors (see above for details)."); } } catch (final ScriptException e) { throw new MojoExecutionException("Failed to execute Sass ruby script:\n" + sassScript, e); } log.debug("\n"); }
From source file:org.jahia.services.content.nodetypes.initializers.ScriptChoiceListInitializerImpl.java
public List<ChoiceListValue> getChoiceListValues(ExtendedPropertyDefinition epd, String param, List<ChoiceListValue> values, Locale locale, Map<String, Object> context) { if (param != null) { final String extension = Patterns.DOT.split(param)[1]; ScriptEngine byName; try {//ww w . j a v a 2s.c o m byName = scriptEngineUtils.scriptEngine(extension); } catch (ScriptException e) { logger.error(e.getMessage(), e); byName = null; } if (byName != null) { final Set<JahiaTemplatesPackage> forModule = ServicesRegistry.getInstance() .getJahiaTemplateManagerService().getModulesWithViewsForComponent( JCRContentUtils.replaceColon(epd.getDeclaringNodeType().getName())); final Bindings bindings = byName.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("values", values); for (JahiaTemplatesPackage template : forModule) { final Resource scriptPath = template .getResource(File.separator + "scripts" + File.separator + param); if (scriptPath != null && scriptPath.exists()) { Reader scriptContent = null; try { scriptContent = new InputStreamReader(scriptPath.getInputStream()); return (List<ChoiceListValue>) byName.eval(scriptContent, bindings); } catch (ScriptException e) { logger.error("Error while executing script " + scriptPath, e); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { if (scriptContent != null) { IOUtils.closeQuietly(scriptContent); } } } } } } return Collections.emptyList(); }
From source file:nz.net.orcon.kanban.automation.plugin.ScriptPlugin.java
@Override public Map<String, Object> process(Action action, Map<String, Object> context) throws Exception { ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); for (Entry<String, Object> entry : context.entrySet()) { if (StringUtils.isNotBlank(entry.getKey())) { engine.put(entry.getKey(), entry.getValue()); }// w ww.j a v a 2 s. com } if (action.getProperties() != null) { for (Entry<String, String> entry : action.getProperties().entrySet()) { if (StringUtils.isNotBlank(entry.getKey())) { engine.put(entry.getKey(), entry.getValue()); } } } engine.put("lists", listController); engine.put("log", log); String script = null; if (StringUtils.isNotBlank(action.getResource())) { script = resourceController.getResource((String) context.get("boardid"), action.getResource()); } else { script = action.getMethod(); } engine.eval(script); Bindings resultBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); for (Entry<String, Object> entry : resultBindings.entrySet()) { if (entry.getKey().equals("context") || entry.getKey().equals("print") || entry.getKey().equals("println")) { continue; } context.put(entry.getKey(), entry.getValue()); } return context; }
From source file:org.labkey.nashorn.NashornController.java
private Pair<ScriptEngine, ScriptContext> getNashorn(boolean useSession) throws Exception { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine; ScriptContext context;/*from ww w. ja v a 2s .c o m*/ Callable<ScriptEngine> createContext = new Callable<ScriptEngine>() { @Override @NotNull public ScriptEngine call() throws Exception { NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); ScriptEngine engine = factory.getScriptEngine(new String[] { "--global-per-engine" }); return engine; } }; if (useSession) { HttpServletRequest req = getViewContext().getRequest(); engine = SessionHelper.getAttribute(req, this.getClass().getName() + "#scriptEngine", createContext); } else { engine = createContext.call(); } Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE); engineScope.put("LABKEY", new org.labkey.nashorn.env.LABKEY(getViewContext())); Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE); // null==engine.getBindings(ScriptContext.GLOBAL_SCOPE), because of --global-per-engine // some docs mention enginScope.get("nashorn.global"), but that is also null if (null == globalScope) globalScope = (Bindings) engineScope.get("nashorn.global"); if (null == globalScope) globalScope = engineScope; globalScope.put("console", new Console()); return new Pair<>(engine, engine.getContext()); }
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()); }// w w w . ja 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.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 ww w. j ava 2 s . co 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; }