List of usage examples for javax.script Bindings put
public Object put(String name, Object value);
From source file:org.apache.nifi.reporting.script.ScriptedReportingTask.java
@Override public void onTrigger(final ReportingContext context) { synchronized (scriptingComponentHelper.isInitialized) { if (!scriptingComponentHelper.isInitialized.get()) { scriptingComponentHelper.createResources(); }// w w w . j a v a 2s . com } ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll(); ComponentLog log = getLogger(); if (scriptEngine == null) { // No engine available so nothing more to do here return; } try { try { Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (bindings == null) { bindings = new SimpleBindings(); } bindings.put("context", context); bindings.put("log", log); bindings.put("vmMetrics", vmMetrics); // 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); } } 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 }); throw t; } finally { scriptingComponentHelper.engineQ.offer(scriptEngine); } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldDoSomeGremlin() throws Exception { final ScriptEngine engine = new GremlinGroovyScriptEngine(); final List list = new ArrayList(); final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("marko", convertToVertexId("marko")); bindings.put("temp", list); assertEquals(list.size(), 0);/*from w w w. j a va 2 s . c om*/ engine.eval("g.V(marko).out().fill(temp)", bindings); assertEquals(list.size(), 3); }
From source file:org.jahia.services.content.rules.RulesNotificationService.java
private void sendMail(String template, Object user, String toMail, String fromMail, String ccList, String bcclist, Locale locale, KnowledgeHelper drools) throws RepositoryException, ScriptException, IOException { if (!notificationService.isEnabled()) { return;/*from w w w . j av a 2 s . com*/ } if (StringUtils.isEmpty(toMail)) { logger.warn("A mail couldn't be sent because to: has no recipient"); return; } // Resolve template : String extension = StringUtils.substringAfterLast(template, "."); ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension); ScriptContext scriptContext = new SimpleScriptContext(); final Bindings bindings = new SimpleBindings(); bindings.put("currentUser", user); bindings.put("contextPath", Jahia.getContextPath()); bindings.put("currentLocale", locale); final Object object = drools.getMatch().getTuple().getHandle().getObject(); JCRNodeWrapper node = null; if (object instanceof AbstractNodeFact) { node = ((AbstractNodeFact) object).getNode(); bindings.put("currentNode", node); final int siteURLPortOverride = SettingsBean.getInstance().getSiteURLPortOverride(); bindings.put("servername", "http" + (siteURLPortOverride == 443 ? "s" : "") + "://" + node.getResolveSite().getServerName() + ((siteURLPortOverride != 0 && siteURLPortOverride != 80 && siteURLPortOverride != 443) ? ":" + siteURLPortOverride : "")); } InputStream scriptInputStream = JahiaContextLoaderListener.getServletContext() .getResourceAsStream(template); if (scriptInputStream == null && node != null) { RulesListener rulesListener = RulesListener.getInstance(node.getSession().getWorkspace().getName()); String packageName = drools.getRule().getPackageName(); JahiaTemplateManagerService jahiaTemplateManagerService = ServicesRegistry.getInstance() .getJahiaTemplateManagerService(); for (Map.Entry<String, String> entry : rulesListener.getModulePackageNameMap().entrySet()) { if (packageName.equals(entry.getValue())) { JahiaTemplatesPackage templatePackage = jahiaTemplateManagerService .getTemplatePackage(entry.getKey()); Resource resource = templatePackage.getResource(template); if (resource != null) { scriptInputStream = resource.getInputStream(); break; } } } } if (scriptInputStream != null) { String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/")) .replaceAll("."), "."); String subject = ""; try { ResourceBundle resourceBundle = ResourceBundles.get(resourceBundleName, locale); bindings.put("bundle", resourceBundle); subject = resourceBundle.getString("subject"); } catch (MissingResourceException e) { if (node != null) { final Value[] values = node.getResolveSite().getProperty("j:installedModules").getValues(); for (Value value : values) { try { ResourceBundle resourceBundle = ResourceBundles .get(ServicesRegistry.getInstance().getJahiaTemplateManagerService() .getTemplatePackageById(value.getString()).getName(), locale); subject = resourceBundle.getString( drools.getRule().getName().toLowerCase().replaceAll(" ", ".") + ".subject"); bindings.put("bundle", resourceBundle); } catch (MissingResourceException ee) { // Do nothing } } } } Reader scriptContent = null; try { scriptContent = new InputStreamReader(scriptInputStream); scriptContext.setWriter(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(); String body = writer.toString(); notificationService.sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body); } finally { if (scriptContent != null) { IOUtils.closeQuietly(scriptContent); } } } }
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)); }/* www. jav a 2 s. co m*/ 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:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldClearBindingsBetweenEvals() throws Exception { final ScriptEngine engine = new GremlinGroovyScriptEngine(); engine.put("g", g); engine.put("marko", convertToVertexId("marko")); assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()")); final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("s", "marko"); assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next()); try {//w w w . j a v a2s .c o m engine.eval("g.V().has('name',s).next()"); fail("This should have failed because s is no longer bound"); } catch (Exception ex) { final Throwable t = ExceptionUtils.getRootCause(ex); assertEquals(MissingPropertyException.class, t.getClass()); assertTrue(t.getMessage().startsWith("No such property: s for class")); } }
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 ww w .j a v a 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.jahia.osgi.FrameworkService.java
private void updateFileReferencesIfNeeded() { File script = new File( SettingsBean.getInstance().getJahiaVarDiskPath() + "/scripts/groovy/updateFileReferences.groovy"); if (!script.isFile()) { return;/*from w w w . j a va 2 s . c om*/ } ScriptEngine scriptEngine; try { scriptEngine = ScriptEngineUtils.getInstance() .scriptEngine(FilenameUtils.getExtension(script.getName())); } catch (ScriptException e) { throw new JahiaRuntimeException(e); } if (scriptEngine == null) { throw new IllegalStateException("No script engine available"); } ScriptContext scriptContext = new SimpleScriptContext(); Bindings bindings = new SimpleBindings(); bindings.put("log", logger); bindings.put("logger", logger); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); try (FileInputStream scriptInputStream = new FileInputStream(script); InputStreamReader scriptReader = new InputStreamReader(scriptInputStream, Charsets.UTF_8); StringWriter out = new StringWriter()) { scriptContext.setWriter(out); scriptEngine.eval(scriptReader, scriptContext); } catch (ScriptException | IOException e) { throw new JahiaRuntimeException(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 ww w .j a va 2 s. com*/ 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.mule.module.scripting.component.Scriptable.java
public void populateBindings(Bindings bindings, Object payload) { populateDefaultBindings(bindings);//from w w w . j a v a 2s. c o m bindings.put("payload", payload); // For backward compatability. Usually used by the script transformer since // src maps with the argument passed into the transformer bindings.put("src", payload); }
From source file:org.archive.crawler.framework.ActionDirectory.java
/** * Try the actionFile as a script, deducing the proper scripting * language from its file extension. Return true if evaluation was * tried with a known script engine. /*w w w .ja va 2 s. c om*/ * * Provides 'appCtx' and 'rawOut' to script for accessing crawl * and outputting text to a '.out' file paired with the 'done/' * action file. If an exception occurs, it will be logged to an * '.ex' file alongside the script file in 'done/'. * * @param actionFile file to try * @param timestamp timestamp correlating out/ex files with done script * @return true if engine evaluation began (even if an error occurred) */ protected boolean tryAsScript(File actionFile, String timestamp) { int i = actionFile.getName().lastIndexOf("."); if (i < 0) { return false; } // deduce language/engine from extension String extension = actionFile.getName().substring(i + 1); ScriptEngine engine = MANAGER.getEngineByExtension(extension); if (engine == null) { return false; } // prepare engine StringWriter rawString = new StringWriter(); PrintWriter rawOut = new PrintWriter(rawString); Exception ex = null; Bindings bindings = new BeanLookupBindings(appCtx); bindings.put("rawOut", rawOut); bindings.put("appCtx", appCtx); // evaluate and record any exception try { String script = FileUtils.readFileToString(actionFile); engine.eval(script, bindings); } catch (IOException e) { ex = e; } catch (ScriptException e) { ex = e; } catch (RuntimeException e) { ex = e; } finally { // the script could create an object that persists and retains a reference to the Bindings bindings.put("rawOut", null); bindings.put("appCtx", null); } // report output/exception to files paired with script in done dir rawOut.flush(); String allOut = rawString.toString(); if (StringUtils.isNotBlank(allOut)) { File outFile = new File(doneDir.getFile(), timestamp + "." + actionFile.getName() + ".out"); try { FileUtils.writeStringToFile(outFile, rawString.toString()); } catch (IOException ioe) { LOGGER.log(Level.SEVERE, "problem during action file: " + actionFile, ioe); } } if (ex != null) { File exFile = new File(doneDir.getFile(), timestamp + "." + actionFile.getName() + ".exception"); try { FileUtils.writeStringToFile(exFile, ex.toString()); } catch (IOException ioe) { LOGGER.log(Level.SEVERE, "problem during action file: " + actionFile, ioe); } } return true; }