List of usage examples for javax.script ScriptEngine createBindings
public Bindings createBindings();
Bindings
. From source file:org.jahia.modules.portal.filter.JCRRestJavaScriptLibFilter.java
@Override public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain) throws Exception { String out = previousOut;//from w w w .j a v a 2 s. com String context = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath()) ? renderContext.getRequest().getContextPath() : ""; // add lib String path = context + "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType() .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JCR_REST_JS_FILE; String encodedPath = URLEncoder.encode(path, "UTF-8"); out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='" + JCR_REST_JS_FILE + "'/>"); // instance JavaScript object String script = getResolvedTemplate(); if (script != null) { String extension = StringUtils.substringAfterLast(JCR_REST_SCRIPT_TEMPLATE, "."); ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension); ScriptContext scriptContext = new JCRRestUtilsScriptContext(); final Bindings bindings = scriptEngine.createBindings(); // bindings bindings.put("options", getBindingMap(renderContext, resource, context)); 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(script, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); final String resultScript = writer.toString(); if (StringUtils.isNotBlank(resultScript)) { out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(resultScript, "UTF-8") + "' insert='false' resource='' title='' key=''/>"); } } return out; }
From source file:org.jahia.services.render.filter.MarkedForDeletionFilter.java
protected String getTemplateOutput(RenderContext renderContext, Resource resource) { String out = StringUtils.EMPTY; try {/*w w w. j a va2 s. co m*/ String template = getTemplateContent(); resolvedTemplate = null; if (StringUtils.isEmpty(template)) { return StringUtils.EMPTY; } ScriptEngine engine = ScriptEngineUtils.getInstance().scriptEngine(templateExtension); ScriptContext ctx = new SimpleScriptContext(); ctx.setWriter(new StringWriter()); Bindings bindings = engine.createBindings(); bindings.put("renderContext", renderContext); bindings.put("resource", resource); final ResourceBundle bundle = ResourceBundles.getInternal(renderContext.getUILocale()); bindings.put("bundle", bundle); bindings.put("i18n", LazyMap.decorate(new HashMap<String, String>(2), new Transformer() { public Object transform(Object input) { String value = null; String key = String.valueOf(input); try { value = bundle.getString(key); } catch (MissingResourceException e) { value = key; } return value; } })); ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE); engine.eval(template, ctx); out = ((StringWriter) ctx.getWriter()).getBuffer().toString(); } catch (Exception e) { logger.error(e.getMessage(), e); } return out; }
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;//from w w w . j a va2s. 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.jahia.services.render.filter.StaticAssetsFilter.java
private void addResources(RenderContext renderContext, org.jahia.services.render.Resource resource, Source source, OutputDocument outputDocument, String targetTag, Map<String, Map<String, Map<String, String>>> assetsByType) throws IOException, ScriptException { renderContext.getRequest().setAttribute(STATIC_ASSETS, assetsByType); Element element = source.getFirstElement(targetTag); String templateContent = getResolvedTemplate(); if (element == null) { logger.warn("Trying to add resources to output but didn't find {} tag", targetTag); return;//from ww w. ja v a 2 s . c o m } if (templateContent != null) { final EndTag headEndTag = element.getEndTag(); ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(templateExtension); ScriptContext scriptContext = new AssetsScriptContext(); final Bindings bindings = scriptEngine.createBindings(); bindings.put("contextJsParameters", getContextJsParameters(assetsByType, renderContext)); if (aggregateAndCompress && resource.getWorkspace().equals("live")) { Map<String, Map<String, String>> cssAssets = assetsByType.get("css"); if (cssAssets != null) { assetsByType.put("css", aggregate(cssAssets, "css")); } Map<String, Map<String, String>> javascriptAssets = assetsByType.get("javascript"); if (javascriptAssets != null) { Map<String, Map<String, String>> scripts = new LinkedHashMap<String, Map<String, String>>( javascriptAssets); Map<String, Map<String, String>> newScripts = aggregate(javascriptAssets, "js"); assetsByType.put("javascript", newScripts); scripts.keySet().removeAll(newScripts.keySet()); assetsByType.put("aggregatedjavascript", scripts); } } else if (addLastModifiedDate) { addLastModified(assetsByType); } bindings.put(TARGET_TAG, targetTag); bindings.put("renderContext", renderContext); bindings.put("resource", resource); bindings.put("contextPath", renderContext.getRequest().getContextPath()); 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)) { outputDocument.replace(headEndTag.getBegin(), headEndTag.getBegin() + 1, "\n" + AggregateCacheFilter.removeCacheTags(staticsAsset) + "\n<"); } } // workaround for ie9 in gxt/gwt // renderContext.isEditMode() means that gwt is loaded, for contribute, edit or studio if (isEnforceIECompatibilityMode(renderContext)) { int idx = element.getBegin() + element.toString().indexOf(">"); String str = ">\n<meta http-equiv=\"X-UA-Compatible\" content=\"" + SettingsBean.getInstance().getInternetExplorerCompatibility() + "\"/>"; outputDocument.replace(idx, idx + 1, str); } if ((renderContext.isPreviewMode()) && !Boolean.valueOf((String) renderContext.getRequest() .getAttribute("org.jahia.StaticAssetFilter.doNotModifyDocumentTitle"))) { for (Element title : element.getAllElements(HTMLElementName.TITLE)) { int idx = title.getBegin() + title.toString().indexOf(">"); String str = Messages.getInternal("label.preview", renderContext.getUILocale()); str = ">" + str + " - "; outputDocument.replace(idx, idx + 1, str); } } }
From source file:org.jahia.tools.patches.GroovyPatcher.java
public static void executeScripts(Resource[] scripts) { long timer = System.currentTimeMillis(); logger.info("Found new patch scripts {}. Executing...", StringUtils.join(scripts)); for (Resource script : scripts) { try {//from w w w. j a va 2s .c o m long timerSingle = System.currentTimeMillis(); String scriptContent = getContent(script); if (StringUtils.isNotEmpty(scriptContent)) { ScriptEngine engine = getEngine(); ScriptContext ctx = new SimpleScriptContext(); ctx.setWriter(new StringWriter()); Bindings bindings = engine.createBindings(); bindings.put("log", new LoggerWrapper(logger, logger.getName(), ctx.getWriter())); ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE); engine.eval(scriptContent, ctx); String result = ((StringWriter) ctx.getWriter()).getBuffer().toString(); logger.info("Execution of script {} took {} ms with result:\n{}", new String[] { script.toString(), String.valueOf(System.currentTimeMillis() - timerSingle), result }); } else { logger.warn("Content of the script {} is either empty or cannot be read. Skipping."); } rename(script, ".installed"); } catch (Exception e) { logger.error("Execution of script " + script + " failed with error: " + e.getMessage(), e); rename(script, ".failed"); } } logger.info("Execution took {} ms", (System.currentTimeMillis() - timer)); }
From source file:org.ms123.common.utils.UtilsServiceImpl.java
public Object executeScript(String scriptName, String namespace, String user, Map params) throws Exception { System.out.println("UtilsServiceImpl.executeScript:" + params); String storeId = (String) params.get("storeId"); StoreDesc sdesc = StoreDesc.get(storeId); namespace = sdesc.getNamespace();// www . ja va 2 s . c o m System.out.println("UtilsServiceImpl.namespace:" + sdesc + "/" + namespace); ScriptEngine se = m_scriptEngineService.getEngineByName("groovy"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); se.getContext().setWriter(pw); Bindings b = se.createBindings(); b.putAll(params); b.put("jdo", m_dataLayer); b.put("ws", lookupServiceByName("org.ms123.common.workflow.api.WorkflowService")); b.put("ss", lookupServiceByName("org.ms123.common.setting.api.SettingService")); b.put("et", lookupServiceByName("org.ms123.common.entity.api.EntityService")); b.put("storeDesc", sdesc); b.put("home", System.getProperty("simpl4.dir")); b.put("log", m_logger); b.put("user", user); b.put("namespace", namespace); se.setBindings(b, ScriptContext.ENGINE_SCOPE); b.put("se", se); Object r = ""; FileReader fr = getScriptFile(namespace, scriptName); r = se.eval(fr); System.out.println("r:" + r); pw.close(); m_logger.info("executeScript:" + sw); System.out.println("executeScript:" + sw); return null; }
From source file:org.omegat.gui.scripting.ScriptRunner.java
/** * Execute a script with a given engine and bindings. * /*from w ww.jav a2 s .co m*/ * @param script * The script in string form * @param engine * The engine * @param additionalBindings * A map of bindings that will be included along with other * bindings * @return The evaluation result * @throws ScriptException */ public static Object executeScript(String script, ScriptEngine engine, Map<String, Object> additionalBindings) throws ScriptException { // logResult(StaticUtils.format(OStrings.getString("SCW_SELECTED_LANGUAGE"), // engine.getFactory().getEngineName())); Bindings bindings = engine.createBindings(); bindings.put(VAR_PROJECT, Core.getProject()); bindings.put(VAR_EDITOR, Core.getEditor()); bindings.put(VAR_GLOSSARY, Core.getGlossary()); bindings.put(VAR_MAINWINDOW, Core.getMainWindow()); bindings.put(VAR_CORE, Core.class); if (additionalBindings != null) { bindings.putAll(additionalBindings); } engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); Object result = engine.eval(script); if (engine instanceof Invocable) { invokeGuiScript((Invocable) engine); } return result; }
From source file:org.opennms.opennms.pris.plugins.script.util.ScriptManager.java
public static Object execute(final InstanceConfiguration config, final Map<String, Object> bindings) throws IOException, ScriptException { Requisition requisition = null;//from w w w.j a v a 2 s .com // Get the path to the script final List<Path> scripts = config.getPaths("file"); // Get the script engine by language defined in config or by extension if it // is not defined in the config final ScriptEngineManager SCRIPT_ENGINE_MANAGER = new ScriptEngineManager( ScriptManager.class.getClassLoader()); for (Path script : scripts) { final ScriptEngine scriptEngine = config.containsKey("lang") ? SCRIPT_ENGINE_MANAGER.getEngineByName(config.getString("lang")) : SCRIPT_ENGINE_MANAGER.getEngineByExtension(FilenameUtils.getExtension(script.toString())); if (scriptEngine == null) { throw new RuntimeException("Script engine implementation not found"); } // Create some bindings for values available in the script final Bindings scriptBindings = scriptEngine.createBindings(); scriptBindings.put("script", script); scriptBindings.put("logger", LoggerFactory.getLogger(script.toString())); scriptBindings.put("config", config); scriptBindings.put("instance", config.getInstanceIdentifier()); scriptBindings.put("interfaceUtils", new InterfaceUtils(config)); scriptBindings.putAll(bindings); // Overwrite initial requisition with the requisition from the previous script, if there was any. if (requisition != null) { scriptBindings.put("requisition", requisition); } // Evaluate the script and return the requisition created in the script try (final Reader scriptReader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) { LOGGER.debug("Start Script {}", script); requisition = (Requisition) scriptEngine.eval(scriptReader, scriptBindings); LOGGER.debug("Done Script {}", script); } } return requisition; }
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 ww . j a va 2s.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.trafodion.rest.script.ScriptManager.java
public void runScript(ScriptContext ctx) { String scriptName;// www. j a v a 2 s .co m if (ctx.getScriptName().length() == 0) scriptName = DEFAULT_SCRIPT_NAME; else if (!ctx.getScriptName().endsWith(".py")) scriptName = ctx.getScriptName() + PYTHON_SUFFIX; else scriptName = ctx.getScriptName(); try { ScriptEngine engine = manager.getEngineByName("python"); Bindings bindings = engine.createBindings(); bindings.put("scriptcontext", ctx); if (engine instanceof Compilable) { CompiledScript script = m.get(scriptName); if (script == null) { LOG.info("Compiling script " + scriptName); Compilable compilingEngine = (Compilable) engine; try { script = compilingEngine.compile(new FileReader(restHome + "/bin/scripts/" + scriptName)); } catch (Exception e) { LOG.warn(e.getMessage()); } m.put(scriptName, script); } script.eval(bindings); } else { try { engine.eval(new FileReader(restHome + "/bin/scripts/" + scriptName), bindings); } catch (Exception e) { LOG.warn(e.getMessage()); } } } catch (javax.script.ScriptException se) { LOG.warn(se.getMessage()); } }