List of usage examples for javax.script ScriptContext ENGINE_SCOPE
int ENGINE_SCOPE
To view the source code for javax.script ScriptContext ENGINE_SCOPE.
Click Source Link
ScriptEngine
and a set of attributes is maintained for each engine. From source file:org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngine.java
public Object eval(Reader scriptReader, ScriptContext scriptContext) throws ScriptException { String scriptName = getScriptName(scriptReader); Reader reader = wrapReaderIfEspScript(scriptReader, scriptName); if (!(scriptReader instanceof ScriptNameAware)) { if (NO_SCRIPT_NAME.equals(scriptName)) { String script = (String) scriptContext.getBindings(ScriptContext.ENGINE_SCOPE) .get(ScriptEngine.FILENAME); if (script != null) { for (String extension : getFactory().getExtensions()) { if (script.endsWith(extension)) { scriptName = script; reader = new ScriptNameAwareReader(reader, scriptName); break; }//from w w w . ja v a 2 s . c om } } } } return compile(reader).eval(scriptContext); }
From source file:com.lucidtechnics.blackboard.util.Jsr223ScriptingUtil.java
public Object executeScript(String _scriptResource) { ScriptContext scriptContext = getScriptEngine().getContext(); Object result = null;//from ww w .j a v a 2s. c o m try { for (String key : getBindingsMap().keySet()) { scriptContext.setAttribute(key, getBindingsMap().get(key), ScriptContext.ENGINE_SCOPE); } CompiledScript script = compileScript(_scriptResource); if (script != null) { result = script.eval(scriptContext); } else { result = getScriptEngine().eval(new InputStreamReader(findScript(_scriptResource)), scriptContext); } } catch (Throwable t) { throw new RuntimeException( "Unable to execute script: " + _scriptResource + " for this reason: " + t.toString(), t); } return result; }
From source file:org.rhq.bindings.ScriptEngineFactory.java
/** * Injects the values provided in the bindings into the {@link ScriptContext#ENGINE_SCOPE engine scope} * of the provided script engine./*from w w w . j av a2s .c o m*/ * * @param engine the engine * @param bindings the bindings * @param deleteExistingBindings true if the existing bindings should be replaced by the provided ones, false * if the provided bindings should be added to the existing ones (possibly overwriting bindings with the same name). */ public static void injectStandardBindings(ScriptEngine engine, StandardBindings bindings, boolean deleteExistingBindings) { bindings.preInject(engine); Bindings engineBindings = deleteExistingBindings ? engine.createBindings() : engine.getBindings(ScriptContext.ENGINE_SCOPE); for (Map.Entry<String, Object> entry : bindings.entrySet()) { engineBindings.put(entry.getKey(), entry.getValue()); } engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE); bindings.postInject(engine); }
From source file:org.xwiki.eventstream.internal.UntypedEventListener.java
/** * Evaluate the given velocity template and return a boolean. * * @param event the event that should be bound to the script context * @param source the source object of the event that should be bound to the template * @param userReference a user reference used to build context * @param templateContent the velocity template that should be evaluated * @return true if the template evaluation returned true or if the template is empty *///from w ww. j av a 2s . com private boolean evaluateVelocityTemplate(Event event, Object source, DocumentReference userReference, String templateContent) { try { // We dont need to evaluate the template if its empty if (StringUtils.isBlank(templateContent)) { return true; } scriptContextManager.getCurrentScriptContext().setAttribute(EVENT_BINDING_NAME, event, ScriptContext.ENGINE_SCOPE); scriptContextManager.getCurrentScriptContext().setAttribute(SOURCE_BINDING_NAME, source, ScriptContext.ENGINE_SCOPE); Template customTemplate = templateManager.createStringTemplate(templateContent, userReference); XDOM templateXDOM = templateManager.execute(customTemplate); WikiPrinter printer = new DefaultWikiPrinter(); renderer.render(templateXDOM, printer); scriptContextManager.getCurrentScriptContext().removeAttribute(EVENT_BINDING_NAME, ScriptContext.ENGINE_SCOPE); scriptContextManager.getCurrentScriptContext().removeAttribute(SOURCE_BINDING_NAME, ScriptContext.ENGINE_SCOPE); return printer.toString().trim().equals("true"); } catch (Exception e) { logger.warn(String.format("Unable to render a notification validation template. Error : %s", e.getMessage())); scriptContextManager.getCurrentScriptContext().removeAttribute(EVENT_BINDING_NAME, ScriptContext.ENGINE_SCOPE); scriptContextManager.getCurrentScriptContext().removeAttribute(SOURCE_BINDING_NAME, ScriptContext.ENGINE_SCOPE); return false; } }
From source file:org.netbeans.jcode.core.util.FileUtil.java
private static void expandTemplate(InputStream template, Map<String, Object> values, Charset targetEncoding, Writer w) throws IOException { // Charset sourceEnc = FileEncodingQuery.getEncoding(template); ScriptEngine eng = getScriptEngine(); Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE); bind.putAll(values);//from w w w. j a v a2 s. co m bind.put(ENCODING_PROPERTY_NAME, targetEncoding.name()); Reader is = null; try { eng.getContext().setWriter(w); is = new InputStreamReader(template); eng.eval(is); } catch (ScriptException ex) { throw new IOException(ex); } finally { if (is != null) { is.close(); } } }
From source file:org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilder.java
/** * Creates the graph with the given Script and step map. * * @param script the Dynamic authentication script. *///from w ww .j a v a 2 s.co m public JsGraphBuilder createWith(String script) { try { currentBuilder.set(this); Bindings globalBindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE); Bindings engineBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_EXECUTE_STEP, (StepExecutor) this::executeStep); globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SEND_ERROR, (BiConsumer<String, Map>) this::sendError); globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SHOW_PROMPT, (PromptExecutor) this::addShowPrompt); engineBindings.put("exit", (RestrictedFunction) this::exitFunction); engineBindings.put("quit", (RestrictedFunction) this::quitFunction); JsFunctionRegistry jsFunctionRegistrar = FrameworkServiceDataHolder.getInstance() .getJsFunctionRegistry(); if (jsFunctionRegistrar != null) { Map<String, Object> functionMap = jsFunctionRegistrar .getSubsystemFunctionsMap(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER); functionMap.forEach(globalBindings::put); } Invocable invocable = (Invocable) engine; engine.eval(script); invocable.invokeFunction(FrameworkConstants.JSAttributes.JS_FUNC_ON_LOGIN_REQUEST, new JsAuthenticationContext(authenticationContext)); JsGraphBuilderFactory.persistCurrentContext(authenticationContext, engine); } catch (ScriptException e) { result.setBuildSuccessful(false); result.setErrorReason("Error in executing the Javascript. Nested exception is: " + e.getMessage()); if (log.isDebugEnabled()) { log.debug("Error in executing the Javascript.", e); } } catch (NoSuchMethodException e) { result.setBuildSuccessful(false); result.setErrorReason("Error in executing the Javascript. " + FrameworkConstants.JSAttributes.JS_FUNC_ON_LOGIN_REQUEST + " function is not defined."); if (log.isDebugEnabled()) { log.debug("Error in executing the Javascript.", e); } } finally { clearCurrentBuilder(); } return this; }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingAction.java
/** * Default execute method.../*from ww w.ja v a 2 s . c o m*/ */ @SuppressWarnings("unchecked") public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException { try { listenerForwarder.started(); // // // data flow configuration and dataStore name must not be null. // // if (configuration == null) { throw new ActionException(this, "Configuration is null."); } final String scriptName = it.geosolutions.tools.commons.file.Path .findLocation(configuration.getScriptFile(), getConfigDir().getAbsolutePath()); if (scriptName == null) throw new ActionException(this, "Unable to locate the script file name: " + configuration.getScriptFile()); final File script = new File(scriptName); /** * Dynamic class-loading ... */ listenerForwarder.setTask("dynamic class loading ..."); final String moduleFolder = new File(script.getParentFile(), "jars").getAbsolutePath(); if (LOGGER.isInfoEnabled()) { LOGGER.info("Runtime class-loading from moduleFolder -> " + moduleFolder); } final File moduleDirectory = new File(moduleFolder); try { addFile(moduleDirectory.getParentFile()); addFile(moduleDirectory); } catch (IOException e) { throw new ActionException(this, e.getLocalizedMessage(), e); } final String classpath = System.getProperty("java.class.path"); final File[] moduleFiles = moduleDirectory.listFiles(); if (moduleFiles != null) { for (File moduleFile : moduleFiles) { final String name = moduleFile.getName(); if (name.endsWith(".jar")) { if (classpath.indexOf(name) == -1) { try { if (LOGGER.isInfoEnabled()) LOGGER.info("Adding: " + name); addFile(moduleFile); } catch (IOException e) { throw new ActionException(this, e.getLocalizedMessage(), e); } } } } } /** * Evaluating script ... */ listenerForwarder.setTask("evaluating script ..."); // Now, pass a different script context final ScriptContext newContext = new SimpleScriptContext(); final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE); // add variables to the new engineScope // engineScope.put("eventList", events); // engineScope.put("runningContext", getRunningContext()); // add properties as free vars in script final Map<String, Object> props = configuration.getProperties(); if (props != null) { final Set<Entry<String, Object>> set = props.entrySet(); final Iterator<Entry<String, Object>> it = set.iterator(); while (it.hasNext()) { final Entry<String, ?> prop = it.next(); if (prop == null) { continue; } if (LOGGER.isInfoEnabled()) LOGGER.info(" Adding script property: " + prop.getKey() + " : " + prop.getValue()); engineScope.put(prop.getKey(), prop.getValue()); } } // read the script FileReader reader = null; try { reader = new FileReader(script); engine.eval(reader, engineScope); } catch (FileNotFoundException e) { throw new ActionException(this, e.getLocalizedMessage(), e); } finally { IOUtils.closeQuietly(reader); } final Invocable inv = (Invocable) engine; listenerForwarder.setTask("Executing script: " + script.getName()); // check for incoming event list if (events == null) { throw new ActionException(this, "Unable to start the script using a null incoming list of events"); } // call the script final Map<String, Object> argsMap = new HashedMap(); argsMap.put(ScriptingAction.CONFIG_KEY, configuration); argsMap.put(ScriptingAction.TEMPDIR_KEY, getTempDir()); argsMap.put(ScriptingAction.CONFIGDIR_KEY, getConfigDir()); argsMap.put(ScriptingAction.EVENTS_KEY, events); argsMap.put(ScriptingAction.LISTENER_KEY, listenerForwarder); final Map<String, Object> mapOut = (Map<String, Object>) inv.invokeFunction("execute", new Object[] { argsMap }); // checking output final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>(); if (mapOut == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Caution returned map from script " + configuration.getScriptFile() + " is null.\nSimulating an empty return list."); } return ret; } final Object obj = mapOut.get(ScriptingAction.RETURN_KEY); if (obj == null) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Caution returned object from script " + configuration.getScriptFile() + " is null.\nPassing an empty list to the next action!"); } return ret; } if (obj instanceof List) { final List<Object> list = (List<Object>) obj; for (final Object out : list) { if (out == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Caution returned object from script " + configuration.getScriptFile() + " is null.\nContinue with the next one."); } continue; } if (out instanceof FileSystemEvent) { FileSystemEvent ev = (FileSystemEvent) out; ret.add(ev); } else if (out instanceof File) { ret.add(new FileSystemEvent((File) out, FileSystemEventType.FILE_ADDED)); } else { final File file = new File(out.toString()); if (!file.exists() && LOGGER.isWarnEnabled()) { LOGGER.warn("Caution returned object from script " + configuration.getScriptFile() + " do not points to an existent file!"); } ret.add(new FileSystemEvent(file, FileSystemEventType.FILE_ADDED)); } } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Caution returned object from script " + configuration.getScriptFile() + " is not a valid List.\nPassing an empty list to the next action!"); } return ret; } listenerForwarder.setTask("Completed"); listenerForwarder.completed(); return ret; } catch (Exception t) { listenerForwarder.setTask("Completed with errors"); listenerForwarder.failed(t); throw new ActionException(this, t.getMessage(), t); } finally { engine = null; factory = null; } }
From source file:io.github.jeddict.jcode.util.FileUtil.java
public static void expandTemplate(Reader reader, Writer writer, Map<String, Object> values, Charset targetEncoding) throws IOException { ScriptEngine eng = getScriptEngine(); Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE); bind.putAll(values);/*from ww w . j av a 2s .c om*/ bind.put(ENCODING_PROPERTY_NAME, targetEncoding.name()); try { eng.getContext().setWriter(writer); eng.eval(reader); } catch (ScriptException ex) { throw new IOException(ex); } finally { if (reader != null) { reader.close(); } } }
From source file:org.jasig.maven.plugin.sass.AbstractSassMojo.java
/** * Execute the SASS Compilation Ruby Script *//*w w w . j a va2 s. c o m*/ protected void executeSassScript(String sassScript) throws MojoExecutionException, MojoFailureException { final Log log = this.getLog(); System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe"); log.debug("Execute SASS Ruby Script:\n" + sassScript); final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby"); try { CompilerCallback compilerCallback = new CompilerCallback(log); jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback); jruby.eval(sassScript); if (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); } }
From source file:org.jumpmind.metl.core.runtime.component.ContentRouter.java
protected void handleControlMessages(ControlMessage inputMessage, ISendMessageCallback callback, boolean unitOfWorkBoundaryReached) { Bindings bindings = scriptEngine.createBindings(); bindHeadersAndFlowParameters(bindings, inputMessage); scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); if (routes != null) { for (Route route : routes) { try { if (Boolean.TRUE.equals(scriptEngine.eval(route.getMatchExpression()))) { callback.sendControlMessage(inputMessage.getHeader(), route.getTargetStepId()); targetStepsThatNeedControlMessages.remove(route.getTargetStepId()); if (onlyRouteFirstMatch) { break; }/*from w ww .j a v a 2 s. co m*/ } } catch (ScriptException e) { throw new RuntimeException(e); } } } }