List of usage examples for javax.script ScriptContext getBindings
public Bindings getBindings(int scope);
Bindings
associated with the given scope in this ScriptContext
. From source file:Main.java
public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval("var msg = 'Hello globals'"); engine.eval("print(this.msg);"); ScriptContext ctx = new SimpleScriptContext(); ScriptContext defaultCtx = engine.getContext(); Bindings engineBindings = defaultCtx.getBindings(ENGINE_SCOPE); ctx.setBindings(engineBindings, ENGINE_SCOPE); engine.eval("print(this.msg);", ctx); }
From source file:io.lavagna.service.ApiHooksService.java
private static void executeScript(String name, CompiledScript script, Map<String, Object> scope) { try {/*from w w w.j a v a2s . c om*/ 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:com.googlecode.starflow.core.script.spel.SpelScriptEngine.java
private Map<String, Object> getVariables(ScriptContext scriptContext) { Map<String, Object> variables = new HashMap<String, Object>(); if (scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE) != null) { variables.putAll(scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE)); }/*w w w . j a v a 2s . c o m*/ if (scriptContext.getBindings(ScriptContext.ENGINE_SCOPE) != null) { variables.putAll(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE)); } return variables; }
From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java
private ScriptEngine buildEngine(Map<String, Object> beans, URL script, ScriptContext context) throws ScriptException, IOException { // Create a new scope for the beans Bindings engineScope = context.getBindings(ScriptContext.ENGINE_SCOPE); for (String key : beans.keySet()) { engineScope.put(key, beans.get(key)); }/*from w w w. j a v a 2 s . c om*/ engineScope.put("ctx", springContext); // Execute the script String name = script.getPath(); int idx; if ((idx = name.indexOf("/")) > -1) { name = name.substring(idx + 1); } if ((idx = name.lastIndexOf(".")) > -1) { name = name.substring(idx + 1); } ScriptEngine engine = manager.getEngineByExtension(name); if (engine == null) { throw new IOException("No scripting engine found for " + name); } return engine; }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingAction.java
/** * Default execute method.../* w w w.j a v a 2s . co 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: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 ww w .j a v a2 s . co m } } } } return compile(reader).eval(scriptContext); }
From source file:org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngine.java
private String getScriptName(ScriptContext scriptContext) { Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); String scriptName = (String) bindings.get(ScriptEngine.FILENAME); if (scriptName != null && !"".equals(scriptName)) { return scriptName; }/*from w w w .java2s . co m*/ SlingScriptHelper sling = (SlingScriptHelper) bindings.get(SlingBindings.SLING); if (sling != null) { return sling.getScript().getScriptResource().getPath(); } return NO_SCRIPT_NAME; }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException { final Binding binding = new Binding(context.getBindings(ScriptContext.ENGINE_SCOPE)) { @Override//ww w . j av a2 s . c o m public Object getVariable(String name) { synchronized (context) { int scope = context.getAttributesScope(name); if (scope != -1) { return context.getAttribute(name, scope); } // Redirect script output to context writer, if out var is not already provided if ("out".equals(name)) { final Writer writer = context.getWriter(); if (writer != null) { return (writer instanceof PrintWriter) ? (PrintWriter) writer : new PrintWriter(writer, true); } } // Provide access to engine context, if context var is not already provided if ("context".equals(name)) { return context; } } throw new MissingPropertyException(name, getClass()); } @Override public void setVariable(String name, Object value) { synchronized (context) { int scope = context.getAttributesScope(name); if (scope == -1) { scope = ScriptContext.ENGINE_SCOPE; } context.setAttribute(name, value, scope); } } }; try { // if this class is not an instance of Script, it's a full-blown class then simply return that class if (!Script.class.isAssignableFrom(scriptClass)) { return scriptClass; } else { final Script scriptObject = InvokerHelper.createScript(scriptClass, binding); for (Method m : scriptClass.getMethods()) { final String name = m.getName(); globalClosures.put(name, new MethodClosure(scriptObject, name)); } final MetaClass oldMetaClass = scriptObject.getMetaClass(); scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) { @Override public Object invokeMethod(final Object object, final String name, final Object args) { if (args == null) { return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY); } else if (args instanceof Tuple) { return invokeMethod(object, name, ((Tuple) args).toArray()); } else if (args instanceof Object[]) { return invokeMethod(object, name, (Object[]) args); } else { return invokeMethod(object, name, new Object[] { args }); } } @Override public Object invokeMethod(final Object object, final String name, final Object args[]) { try { return super.invokeMethod(object, name, args); } catch (MissingMethodException mme) { return callGlobal(name, args, context); } } @Override public Object invokeStaticMethod(final Object object, final String name, final Object args[]) { try { return super.invokeStaticMethod(object, name, args); } catch (MissingMethodException mme) { return callGlobal(name, args, context); } } }); final Object o = scriptObject.run(); // if interpreter mode is enable then local vars of the script are promoted to engine scope bindings. if (interpreterModeEnabled) { final Map<String, Object> localVars = (Map<String, Object>) context .getAttribute(COLLECTED_BOUND_VARS_MAP_VARNAME); if (localVars != null) { localVars.entrySet().forEach(e -> { // closures need to be cached for later use if (e.getValue() instanceof Closure) globalClosures.put(e.getKey(), (Closure) e.getValue()); context.setAttribute(e.getKey(), e.getValue(), ScriptContext.ENGINE_SCOPE); }); // get rid of the temporary collected vars context.removeAttribute(COLLECTED_BOUND_VARS_MAP_VARNAME, ScriptContext.ENGINE_SCOPE); localVars.clear(); } } return o; } } catch (Exception e) { throw new ScriptException(e); } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
private void registerBindingTypes(final ScriptContext context) { if (typeCheckingEnabled) { final Map<String, ClassNode> variableTypes = new HashMap<>(); clearVarTypes();//ww w.j av a 2 s . com // 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); } }
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);/*from w w w.ja v a2s .co m*/ try { Object result = scriptEngine.eval(fireflowExpression.getBody(), scriptContext); return result; } catch (ScriptException e) { throw new RuntimeException("Can NOT evaluate the expression. ", e); } }