List of usage examples for javax.script Bindings put
public Object put(String name, Object value);
From source file:org.jahia.services.render.filter.StaticAssetsFilter.java
@Override public String execute(String previousOut, RenderContext renderContext, org.jahia.services.render.Resource resource, RenderChain chain) throws Exception { String out = previousOut;/* ww w. j a v a2 s. c o m*/ Source source = new Source(previousOut); Map<String, Map<String, Map<String, Map<String, String>>>> assetsByTarget = new LinkedHashMap<>(); List<Element> esiResourceElements = source.getAllElements("jahia:resource"); Set<String> keys = new HashSet<>(); for (Element esiResourceElement : esiResourceElements) { StartTag esiResourceStartTag = esiResourceElement.getStartTag(); Map<String, Map<String, Map<String, String>>> assets; String targetTag = esiResourceStartTag.getAttributeValue(TARGET_TAG); if (targetTag == null) { targetTag = "HEAD"; } else { targetTag = targetTag.toUpperCase(); } if (!assetsByTarget.containsKey(targetTag)) { assets = LazySortedMap.decorate(TransformedSortedMap.decorate( new TreeMap<String, Map<String, Map<String, String>>>(ASSET_COMPARATOR), LOW_CASE_TRANSFORMER, NOPTransformer.INSTANCE), new AssetsMapFactory()); assetsByTarget.put(targetTag, assets); } else { assets = assetsByTarget.get(targetTag); } String type = esiResourceStartTag.getAttributeValue("type"); String path = StringUtils.equals(type, "inline") ? StringUtils.substring(out, esiResourceStartTag.getEnd(), esiResourceElement.getEndTag().getBegin()) : URLDecoder.decode(esiResourceStartTag.getAttributeValue("path"), "UTF-8"); Boolean insert = Boolean.parseBoolean(esiResourceStartTag.getAttributeValue("insert")); String key = esiResourceStartTag.getAttributeValue("key"); // get options Map<String, String> optionsMap = getOptionMaps(esiResourceStartTag); Map<String, Map<String, String>> stringMap = assets.get(type); if (stringMap == null) { Map<String, Map<String, String>> assetMap = new LinkedHashMap<>(); stringMap = assets.put(type, assetMap); } if (insert) { Map<String, Map<String, String>> my = new LinkedHashMap<>(); my.put(path, optionsMap); my.putAll(stringMap); stringMap = my; } else { if ("".equals(key) || !keys.contains(key)) { Map<String, Map<String, String>> my = new LinkedHashMap<>(); my.put(path, optionsMap); stringMap.putAll(my); keys.add(key); } } assets.put(type, stringMap); } OutputDocument outputDocument = new OutputDocument(source); if (renderContext.isAjaxRequest()) { String templateContent = getAjaxResolvedTemplate(); if (templateContent != null) { for (Map.Entry<String, Map<String, Map<String, Map<String, String>>>> entry : assetsByTarget .entrySet()) { renderContext.getRequest().setAttribute(STATIC_ASSETS, entry.getValue()); Element element = source.getFirstElement(TARGET_TAG); final EndTag tag = element != null ? element.getEndTag() : null; ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(ajaxTemplateExtension); ScriptContext scriptContext = new AssetsScriptContext(); final Bindings bindings = scriptEngine.createBindings(); bindings.put(TARGET_TAG, entry.getKey()); bindings.put("renderContext", renderContext); bindings.put("resource", resource); scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE); // The following binding is necessary for Javascript, which doesn't offer a console by default. bindings.put("out", new PrintWriter(scriptContext.getWriter())); scriptEngine.eval(templateContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); final String staticsAsset = writer.toString(); if (StringUtils.isNotBlank(staticsAsset)) { if (tag != null) { outputDocument.replace(tag.getBegin(), tag.getBegin() + 1, "\n" + staticsAsset + "\n<"); out = outputDocument.toString(); } else { out = staticsAsset + "\n" + previousOut; } } } } } else if (resource.getContextConfiguration().equals("page")) { if (renderContext.isEditMode()) { if (renderContext.getServletPath().endsWith("frame")) { boolean doParse = true; if (renderContext.getEditModeConfig().getSkipMainModuleTypesDomParsing() != null) { for (String nt : renderContext.getEditModeConfig().getSkipMainModuleTypesDomParsing()) { doParse = !resource.getNode().isNodeType(nt); if (!doParse) { break; } } } List<Element> bodyElementList = source.getAllElements(HTMLElementName.BODY); if (bodyElementList.size() > 0) { Element bodyElement = bodyElementList.get(bodyElementList.size() - 1); EndTag bodyEndTag = bodyElement.getEndTag(); outputDocument.replace(bodyEndTag.getBegin(), bodyEndTag.getBegin() + 1, "</div><"); bodyElement = bodyElementList.get(0); StartTag bodyStartTag = bodyElement.getStartTag(); outputDocument.replace(bodyStartTag.getEnd(), bodyStartTag.getEnd(), "\n" + "<div jahiatype=\"mainmodule\"" + " path=\"" + resource.getNode().getPath() + "\" locale=\"" + resource.getLocale() + "\"" + " template=\"" + (resource.getTemplate() != null && !resource.getTemplate().equals("default") ? resource.getTemplate() : "") + "\"" + " nodetypes=\"" + ConstraintsHelper.getConstraints(renderContext.getMainResource().getNode()) + "\"" + ">"); if (doParse) { outputDocument.replace(bodyStartTag.getEnd() - 1, bodyStartTag.getEnd(), " jahia-parse-html=\"true\">"); } } } } if (!assetsByTarget.containsKey("HEAD")) { addResources(renderContext, resource, source, outputDocument, "HEAD", new HashMap<String, Map<String, Map<String, String>>>()); } for (Map.Entry<String, Map<String, Map<String, Map<String, String>>>> entry : assetsByTarget .entrySet()) { String targetTag = entry.getKey(); Map<String, Map<String, Map<String, String>>> assets = entry.getValue(); addResources(renderContext, resource, source, outputDocument, targetTag, assets); } out = outputDocument.toString(); } // Clean all jahia:resource tags source = new Source(out); outputDocument = new OutputDocument(source); for (Element el : source.getAllElements("jahia:resource")) { outputDocument.replace(el, ""); } String s = outputDocument.toString(); s = removeTempTags(s); return s.trim(); }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java
private ScriptEngines createScriptEngines() { // plugins already on the path - ones static to the classpath final List<GremlinPlugin> globalPlugins = new ArrayList<>(); ServiceLoader.load(GremlinPlugin.class).forEach(globalPlugins::add); return new ScriptEngines(se -> { // this first part initializes the scriptengines Map for (Map.Entry<String, EngineSettings> config : settings.entrySet()) { final String language = config.getKey(); se.reload(language, new HashSet<>(config.getValue().getImports()), new HashSet<>(config.getValue().getStaticImports()), config.getValue().getConfig()); }/*from ww w .ja va2 s .c o m*/ // use grabs dependencies and returns plugins to load final List<GremlinPlugin> pluginsToLoad = new ArrayList<>(globalPlugins); use.forEach(u -> { if (u.size() != 3) logger.warn( "Could not resolve dependencies for [{}]. Each entry for the 'use' configuration must include [groupId, artifactId, version]", u); else { logger.info("Getting dependencies for [{}]", u); pluginsToLoad.addAll(se.use(u.get(0), u.get(1), u.get(2))); } }); // now that all dependencies are in place, the imports can't get messed up if a plugin tries to execute // a script (as the script engine appends the import list to the top of all scripts passed to the engine). // only enable those plugins that are configured to be enabled. se.loadPlugins(pluginsToLoad.stream().filter(plugin -> enabledPlugins.contains(plugin.getName())) .collect(Collectors.toList())); // initialization script eval can now be performed now that dependencies are present with "use" for (Map.Entry<String, EngineSettings> config : settings.entrySet()) { final String language = config.getKey(); // script engine initialization files that fail will only log warnings - not fail server initialization final AtomicBoolean hasErrors = new AtomicBoolean(false); config.getValue().getScripts().stream().map(File::new).filter(f -> { if (!f.exists()) { logger.warn("Could not initialize {} ScriptEngine with {} as file does not exist", language, f); hasErrors.set(true); } return f.exists(); }).map(f -> { try { return Pair.with(f, Optional.of(new FileReader(f))); } catch (IOException ioe) { logger.warn("Could not initialize {} ScriptEngine with {} as file could not be read - {}", language, f, ioe.getMessage()); hasErrors.set(true); return Pair.with(f, Optional.<FileReader>empty()); } }).filter(p -> p.getValue1().isPresent()).map(p -> Pair.with(p.getValue0(), p.getValue1().get())) .forEachOrdered(p -> { try { final Bindings bindings = new SimpleBindings(); bindings.putAll(globalBindings); // evaluate init scripts with hard reference so as to ensure it doesn't get garbage collected bindings.put(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE, GremlinGroovyScriptEngine.REFERENCE_TYPE_HARD); // the returned object should be a Map of initialized global bindings final Object initializedBindings = se.eval(p.getValue1(), bindings, language); if (initializedBindings != null && initializedBindings instanceof Map) globalBindings.putAll((Map) initializedBindings); else logger.warn( "Initialization script {} did not return a Map - no global bindings specified", p.getValue0()); logger.info("Initialized {} ScriptEngine with {}", language, p.getValue0()); } catch (ScriptException sx) { hasErrors.set(true); logger.warn( "Could not initialize {} ScriptEngine with {} as script could not be evaluated - {}", language, p.getValue0(), sx.getMessage()); } }); } }); }
From source file:org.ow2.parserve.PARServeEngine.java
private Object retrieveResultVariable(ScriptContext ctx, Bindings bindings, REXP rexp) { Object resultValue = null;//from w w w. j ava2 s . c o m // If the 'result' variable is explicitly defined in the global // environment it is considered as the task result instead of the // result exp REXP resultRexp = null; if (!serverEval) { resultRexp = engine.engineGet(TaskScript.RESULT_VARIABLE, ctx); if (resultRexp != null) { resultValue = engine.engineCast(resultRexp, null, ctx); } else { resultValue = engine.engineCast(rexp, null, ctx); } } if (resultValue == null) { resultValue = true; // TaskResult.getResult() returns true by default } bindings.put(TaskScript.RESULT_VARIABLE, resultValue); return resultValue; }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingAction.java
/** * Default execute method.../* ww w.j a v a2s .c om*/ */ @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.lsc.utils.JScriptEvaluator.java
/** * Local instance evaluation.// ww w. j a va 2s. c o m * * @param expression * the expression to eval * @param params * the keys are the name used in the * @return the evaluation result * @throws LscServiceException */ private Object instanceEval(final Task task, final String expression, final Map<String, Object> params) throws LscServiceException { // Script script = null; Bindings bindings = engine.createBindings(); /* Allow to have shorter names for function in the package org.lsc.utils.directory */ String expressionImport = "var version = java.lang.System.getProperty(\"java.version\");\n" + "if (version.startsWith(\"1.8.0\")) { load(\"nashorn:mozilla_compat.js\"); }\n" + "importPackage(org.lsc.utils.directory);\n" + "importPackage(org.lsc.utils);\n" + expression; // if (cache.containsKey(expressionImport)) { // script = cache.get(expressionImport); // } else { // script = cx.compileString(expressionImport, "<cmd>", 1, null); // cache.put(expressionImport, script); // } // add LDAP interface for destination if (!bindings.containsKey("ldap") && task.getDestinationService() instanceof AbstractSimpleJndiService) { ScriptableJndiServices dstSjs = new ScriptableJndiServices(); dstSjs.setJndiServices(((AbstractSimpleJndiService) task.getDestinationService()).getJndiServices()); bindings.put("ldap", dstSjs); } // add LDAP interface for source if (!bindings.containsKey("srcLdap") && task.getSourceService() instanceof AbstractSimpleJndiService) { ScriptableJndiServices srcSjs = new ScriptableJndiServices(); srcSjs.setJndiServices(((AbstractSimpleJndiService) task.getSourceService()).getJndiServices()); bindings.put("srcLdap", srcSjs); } if (params != null) { for (String paramName : params.keySet()) { bindings.put(paramName, params.get(paramName)); } } Object ret = null; try { if (task.getScriptIncludes() != null) { for (File scriptInclude : task.getScriptIncludes()) { if ("js".equals(FilenameUtils.getExtension(scriptInclude.getAbsolutePath()))) { FileReader reader = new FileReader(scriptInclude); try { engine.eval(reader, bindings); } finally { reader.close(); } } } } ret = engine.eval(expressionImport, bindings); } catch (ScriptException e) { LOGGER.error("Fail to compute expression: " + expression + " on " + (params.containsKey("srcBean") && ((IBean) params.get("srcBean")).getMainIdentifier() != null ? "id=" + ((IBean) params.get("srcBean")).getMainIdentifier() : (params.containsKey("dstBean") && ((IBean) params.get("dstBean")).getMainIdentifier() != null ? "id=" + ((IBean) params.get("dstBean")).getMainIdentifier() : "unknown id !")) + "\nReason: " + e.toString()); LOGGER.debug(e.toString(), e); throw new LscServiceException(e); } catch (RuntimeException e) { throw new LscServiceException(e); } catch (Exception e) { LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); return null; } return ret; }
From source file:io.github.jeddict.jcode.parser.ejs.EJSParser.java
private ScriptEngine createEngine() { CompiledScript cscript;//from w w w . ja v a 2s.c o m Bindings bindings; ScriptEngine scriptEngine = new NashornScriptEngineFactory().getScriptEngine("--language=es6");//engine = new ScriptEngineManager().getEngineByName("nashorn"); try { try { if (base == null) { base = IOUtils.toString(EJSParser.class.getClassLoader() .getResourceAsStream("io/github/jeddict/jcode/parser/ejs/resources/base.js"), "UTF-8"); } if (ejs == null) { ejs = IOUtils.toString(EJSParser.class.getClassLoader() .getResourceAsStream("io/github/jeddict/jcode/parser/ejs/resources/ejs.js"), "UTF-8"); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } scriptEngine.eval(base); Compilable compilingEngine = (Compilable) scriptEngine; cscript = compilingEngine.compile(ejs); bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE); cscript.eval(bindings); scriptEngine.eval(scripts.toString()); for (Map<String, Object> context : contexts) { context.keySet().stream().forEach((key) -> { try { bindings.put(key, context.get(key)); if (context.get(key) instanceof Collection) { scriptEngine.eval(String.format("%s = Java.from(%s);", key, key)); } } catch (ScriptException ex) { Exceptions.printStackTrace(ex); } }); } } catch (ScriptException ex) { Exceptions.printStackTrace(ex); } return scriptEngine; }
From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java
@Override public boolean execute(TestData data, TestResult result, final boolean debug) { // Interpret the file testData = data;//from w w w. j ava 2 s.co m testResult = result; if (debug) { testScriptBreakPointEventHandler.addTestScriptBreakpointListener(scriptBreakpoint); } try { Bindings bindings = engine.createBindings(); engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); engine.eval("import sys as __sys"); engine.eval("if not globals().has_key('__initModules'):\n" + " __initModules = __sys.modules.keys()\n" + "else:\n" + " for m in __sys.modules.keys():\n" + " if m not in __initModules:\n" + " del __sys.modules[m]", globalBindings); // add all global bindinds bindings.putAll(globalBindings); if (testSuite != null) { // add pythonlib subdirectories of test script directory up to test suites directory, to python path List<String> additionalPythonPath = getAdditionalPythonPath(); String pythonPathScript = ""; for (String pythonlib : additionalPythonPath) { pythonPathScript += "__sys.path.append(r'" + pythonlib + "')\n"; } engine.eval(pythonPathScript); } // reset doStep count / step id / step name stacks engine.eval("doStep.countStack = [0]\n" + "doStep.stepIdStack = []\n" + "doStep.stepNameStack = []\n"); // add testAPI, testData and scriptBreakpoint to bindings bindings.put("this", this); engine.eval("testAPI = __TestAPIWrapper(this)"); bindings.remove("__TestAPIWrapper"); bindings.remove("this"); bindings.put("testData", scriptTestData); bindings.put("DoubleWithPrecision", DoubleWithPrecision.class); bindings.put("QTasteException", QTasteException.class); bindings.put("QTasteDataException", QTasteDataException.class); bindings.put("QTasteTestFailException", QTasteTestFailException.class); bindings.put("__scriptBreakpoint", scriptBreakpoint); globalBindings.put("testScript", this); // create QTaste module with testAPI, testData, DoubleWithPrecision, doStep, doSteps, doSubStep, logger and Status engine.eval("class __QTaste_Module:\n" + " def __init__(self):\n" + " self.importTestScript= importTestScript\n" + " self.isInTestScriptImport= isInTestScriptImport\n" + " self.testAPI= testAPI\n" + " self.testData = testData\n" + " self.DoubleWithPrecision = DoubleWithPrecision\n" + " self.doStep = doStep\n" + " self.doSteps = doSteps\n" + " self.doSubStep = doStep\n" + " self.doSubSteps = doSteps\n" + " self.logger = logger\n" + " self.Status = Status\n" + " self.QTasteException = QTasteException\n" + " self.QTasteDataException = QTasteDataException\n" + " self.QTasteTestFailException = QTasteTestFailException\n" + "__sys.modules['qtaste'] = __QTaste_Module()"); // remove testAPI, testData, DoubleWithPrecision, doStep, doSteps, logger and Status from bindinds bindings.remove("__QTaste_Module"); bindings.remove("importTestScript"); bindings.remove("isCalledFromMainTestScript"); bindings.remove("testAPI"); bindings.remove("testData"); bindings.remove("DoubleWithPrecision"); bindings.remove("doStep"); bindings.remove("doSteps"); bindings.remove("logger"); bindings.remove("Status"); bindings.remove("QTasteException"); bindings.remove("QTasteDataException"); bindings.remove("QTasteTestFailException"); // Check if test was aborted by user before execute testscript.py if (TestEngine.isAbortedByUser()) { return false; } if (!debug) { engine.eval("execfile(r'" + fileName + "', globals())"); } else { // execute in debugger engine.eval(scriptDebuggerClassCode); engine.eval("__debugger = __ScriptDebugger()"); bindings.remove("__bdb"); bindings.remove("__ScriptDebugger"); for (Breakpoint b : breakPointEventHandler.getBreakpoints()) { engine.eval("__debugger.set_break(r'" + b.getFileName() + "', " + b.getLineIndex() + ")"); } engine.eval("__debugger.runcall(execfile, r'" + fileName + "', globals())"); } } catch (ScriptException e) { handleScriptException(e, result); } finally { if (debug) { testScriptBreakPointEventHandler.removeTestScriptBreakpointListener(scriptBreakpoint); } } return true; }