List of usage examples for javax.script ScriptContext setBindings
public void setBindings(Bindings bindings, int scope);
Bindings
instance with a particular scope in this ScriptContext
. From source file:org.jahia.modules.googleAnalytics.GoogleAnalyticsFilter.java
@Override public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain) throws Exception { String out = previousOut;//from ww w. j a v a 2 s . c om String webPropertyID = renderContext.getSite().hasProperty("webPropertyID") ? renderContext.getSite().getProperty("webPropertyID").getString() : null; if (StringUtils.isNotEmpty(webPropertyID)) { String script = getResolvedTemplate(); if (script != null) { Source source = new Source(previousOut); OutputDocument outputDocument = new OutputDocument(source); List<Element> headElementList = source.getAllElements(HTMLElementName.HEAD); for (Element element : headElementList) { final EndTag headEndTag = element.getEndTag(); String extension = StringUtils.substringAfterLast(template, "."); ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension); ScriptContext scriptContext = new GoogleScriptContext(); final Bindings bindings = scriptEngine.createBindings(); bindings.put("webPropertyID", webPropertyID); String url = resource.getNode().getUrl(); if (renderContext.getRequest().getAttribute("analytics-path") != null) { url = (String) renderContext.getRequest().getAttribute("analytics-path"); } bindings.put("resourceUrl", url); bindings.put("resource", resource); bindings.put("gaMap", renderContext.getRequest().getAttribute("gaMap")); 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 googleAnalyticsScript = writer.toString(); if (StringUtils.isNotBlank(googleAnalyticsScript)) { outputDocument.replace(headEndTag.getBegin(), headEndTag.getBegin() + 1, "\n" + AggregateCacheFilter.removeEsiTags(googleAnalyticsScript) + "\n<"); } break; // avoid to loop if for any reasons multiple body in the page } out = outputDocument.toString().trim(); } } return out; }
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()); }/* w ww .ja va 2 s . c om*/ 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.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 www . j av 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.apache.sling.scripting.sightly.js.impl.JsEnvironment.java
public void runResource(Resource scriptResource, Bindings globalBindings, Bindings arguments, UnaryCallback callback) {// www . j a v a 2s. co m ScriptContext scriptContext = new SimpleScriptContext(); CommonJsModule module = new CommonJsModule(); Bindings scriptBindings = buildBindings(scriptResource, globalBindings, arguments, module); scriptContext.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE); scriptContext.setAttribute(ScriptEngine.FILENAME, scriptResource.getPath(), ScriptContext.ENGINE_SCOPE); runScript(scriptResource, scriptContext, callback, module); }
From source file:org.jahia.ajax.gwt.helper.UIConfigHelper.java
/** * Get resources//from www. j a v a 2 s. c o m * * @param key * @param locale * @param site * @param jahiaUser * @return */ private String getResources(String key, Locale locale, JCRSiteNode site, JahiaUser jahiaUser) { if (key == null || key.length() == 0) { return key; } if (logger.isDebugEnabled()) { logger.debug("Resources key: " + key); } String baseName = null; String value = null; if (key.contains("@")) { baseName = StringUtils.substringAfter(key, "@"); key = StringUtils.substringBefore(key, "@"); } value = Messages.get(baseName, site != null ? site.getTemplatePackage() : null, key, locale, null); if (value == null || value.length() == 0) { value = Messages.getInternal(key, locale); } if (logger.isDebugEnabled()) { logger.debug("Resources value: " + value); } if (value.contains("${")) { try { ScriptEngine scriptEngine = scriptEngineUtils.getEngineByName("velocity"); ScriptContext scriptContext = new SimpleScriptContext(); final Bindings bindings = new SimpleBindings(); bindings.put("currentSite", site); bindings.put("currentUser", jahiaUser); bindings.put("currentLocale", locale); bindings.put("PrincipalViewHelper", PrincipalViewHelper.class); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); scriptEngine.eval(value, scriptContext); //String error = scriptContext.getErrorWriter().toString(); return scriptContext.getWriter().toString().trim(); } catch (ScriptException e) { logger.error("Error while executing script [" + value + "]", e); } } return value; }
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;// w w w . j a va 2 s. c om 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.osgi.FrameworkService.java
private void updateFileReferencesIfNeeded() { File script = new File( SettingsBean.getInstance().getJahiaVarDiskPath() + "/scripts/groovy/updateFileReferences.groovy"); if (!script.isFile()) { return;/* w w w . java 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.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;//w ww .java 2s .c o m } 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:org.jahia.services.mail.MailServiceImpl.java
@Override public void sendMessageWithTemplate(String template, Map<String, Object> boundObjects, String toMail, String fromMail, String ccList, String bcclist, Locale locale, String templatePackageName) throws RepositoryException, ScriptException { // Resolve template : ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(StringUtils.substringAfterLast(template, ".")); ScriptContext scriptContext = new SimpleScriptContext(); //try if it is multilingual String suffix = StringUtils.substringAfterLast(template, "."); String languageMailConfTemplate = template.substring(0, template.length() - (suffix.length() + 1)) + "_" + locale.toString() + "." + suffix; JahiaTemplatesPackage templatePackage = templateManagerService.getTemplatePackage(templatePackageName); Resource templateRealPath = templatePackage.getResource(languageMailConfTemplate); if (templateRealPath == null) { templateRealPath = templatePackage.getResource(template); }// www . j a v a 2 s . c o m InputStream scriptInputStream = null; try { scriptInputStream = templateRealPath.getInputStream(); } catch (IOException e) { logger.error(e.getMessage(), e); } if (scriptInputStream != null) { ResourceBundle resourceBundle; if (templatePackageName == null) { String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/")) .replaceAll("."), "."); resourceBundle = ResourceBundles.get(resourceBundleName, locale); } else { resourceBundle = ResourceBundles.get(ServicesRegistry.getInstance().getJahiaTemplateManagerService() .getTemplatePackage(templatePackageName), locale); } final Bindings bindings = new SimpleBindings(); bindings.put("bundle", resourceBundle); bindings.putAll(boundObjects); Reader scriptContent = null; // Subject String subject; try { String subjectTemplatePath = StringUtils.substringBeforeLast(template, ".") + ".subject." + StringUtils.substringAfterLast(template, "."); InputStream stream = templatePackage.getResource(subjectTemplatePath).getInputStream(); scriptContent = templateCharset != null ? new InputStreamReader(stream, templateCharset) : new InputStreamReader(stream); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptContext.setWriter(new StringWriter()); scriptEngine.eval(scriptContent, scriptContext); subject = scriptContext.getWriter().toString().trim(); } catch (Exception e) { logger.warn("Not able to render mail subject using " + StringUtils.substringBeforeLast(template, ".") + ".subject." + StringUtils.substringAfterLast(template, ".") + " template file - set org.jahia.services.mail.MailService in debug for more information"); if (logger.isDebugEnabled()) { logger.debug("generating the mail subject throw an exception : ", e); } subject = resourceBundle.getString( StringUtils.substringBeforeLast(StringUtils.substringAfterLast(template, "/"), ".") + ".subject"); } finally { IOUtils.closeQuietly(scriptContent); } try { try { scriptContent = templateCharset != null ? new InputStreamReader(scriptInputStream, templateCharset) : new InputStreamReader(scriptInputStream); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(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); scriptEngine.eval(scriptContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); String body = writer.toString(); sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body); } finally { IOUtils.closeQuietly(scriptContent); } } else { logger.warn("Cannot send mail, template [" + template + "] from module [" + templatePackageName + "] not found"); } }
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 v a 2s . com 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; }