Example usage for javax.script ScriptContext setBindings

List of usage examples for javax.script ScriptContext setBindings

Introduction

In this page you can find the example usage for javax.script ScriptContext setBindings.

Prototype

public void setBindings(Bindings bindings, int scope);

Source Link

Document

Associates a Bindings instance with a particular scope in this ScriptContext.

Usage

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;//  w  w w  . j a v a  2s.co  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;/*ww  w  .j  a v a2 s. c  om*/
    }

    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.services.render.scripting.JSR223Script.java

/**
 * Execute the script and return the result as a string
 *
 * @param resource resource to display/*from   w w  w  .  j  a v  a 2 s.c om*/
 * @param context
 * @return the rendered resource
 * @throws org.jahia.services.render.RenderException
 */
public String execute(Resource resource, RenderContext context) throws RenderException {
    ScriptEngine scriptEngine = null;

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(view.getModule().getChainedClassLoader());

    try {
        scriptEngine = ScriptEngineUtils.getInstance().scriptEngine(view.getFileExtension());

        if (scriptEngine != null) {
            ScriptContext scriptContext = new SimpleScriptContext();
            final Bindings bindings = new SimpleBindings();
            Enumeration<?> attrNamesEnum = context.getRequest().getAttributeNames();
            while (attrNamesEnum.hasMoreElements()) {
                String currentAttributeName = (String) attrNamesEnum.nextElement();
                if (!"".equals(currentAttributeName)) {
                    bindings.put(currentAttributeName, context.getRequest().getAttribute(currentAttributeName));
                }
            }
            bindings.put("params", context.getRequest().getParameterMap());
            Reader scriptContent = null;
            try {
                InputStream scriptInputStream = getViewInputStream();
                if (scriptInputStream != null) {
                    scriptContent = new InputStreamReader(scriptInputStream);
                    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);
                    scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                            ScriptContext.GLOBAL_SCOPE);

                    scriptEngine.eval(scriptContent, scriptContext);

                    StringWriter writer = (StringWriter) scriptContext.getWriter();
                    return writer.toString().trim();
                } else {
                    throw new RenderException(
                            "Error while retrieving input stream for the resource " + view.getPath());
                }
            } catch (ScriptException e) {
                throw new RenderException("Error while executing script " + view.getPath(), e);
            } catch (IOException e) {
                throw new RenderException(
                        "Error while retrieving input stream for the resource " + view.getPath(), e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }

    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    return null;
}

From source file:org.jahia.services.scheduler.JSR223ScriptJob.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    final JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    String jobScriptPath;//from   w w  w  . j  av  a  2 s . com
    boolean isAbsolutePath = false;
    if (map.containsKey(JOB_SCRIPT_ABSOLUTE_PATH)) {
        isAbsolutePath = true;
        jobScriptPath = map.getString(JOB_SCRIPT_ABSOLUTE_PATH);
    } else {
        jobScriptPath = map.getString(JOB_SCRIPT_PATH);
    }
    logger.info("Start executing JSR223 script job {}", jobScriptPath);

    ScriptEngine scriptEngine = ScriptEngineUtils.getInstance()
            .scriptEngine(FilenameUtils.getExtension(jobScriptPath));
    if (scriptEngine != null) {
        ScriptContext scriptContext = new SimpleScriptContext();
        final Bindings bindings = new SimpleBindings();
        bindings.put("jobDataMap", map);

        InputStream scriptInputStream;
        if (!isAbsolutePath) {
            scriptInputStream = JahiaContextLoaderListener.getServletContext()
                    .getResourceAsStream(jobScriptPath);
        } else {
            scriptInputStream = FileUtils.openInputStream(new File(jobScriptPath));
        }
        if (scriptInputStream != null) {
            Reader scriptContent = null;
            try {
                scriptContent = new InputStreamReader(scriptInputStream);
                StringWriter out = new StringWriter();
                scriptContext.setWriter(out);
                // 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);
                map.put(JOB_SCRIPT_OUTPUT, out.toString());
                logger.info("...JSR-223 script job {} execution finished", jobScriptPath);
            } catch (ScriptException e) {
                logger.error("Error during execution of the JSR-223 script job " + jobScriptPath
                        + " execution failed with error " + e.getMessage(), e);
                throw new Exception("Error during execution of script " + jobScriptPath, e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }
    }
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected String evaluateExpression(WorkItem workItem, String scriptToExecute, JCRSessionWrapper session)
        throws RepositoryException, ScriptException {
    ScriptContext scriptContext = new SimpleScriptContext();
    if (bindings == null) {
        bindings = getBindings(workItem, session);
    }//from   w  w  w  .  ja v a  2s  . c o m
    scriptContext.setWriter(new StringWriter());
    scriptContext.setErrorWriter(new StringWriter());
    scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    scriptContext.setBindings(scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE),
            ScriptContext.GLOBAL_SCOPE);
    scriptEngine.eval(scriptToExecute, scriptContext);
    String error = scriptContext.getErrorWriter().toString();
    if (error.length() > 0) {
        logger.error("Scripting error : " + error);
    }
    return scriptContext.getWriter().toString().trim();
}

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  ava 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.nuxeo.ecm.webengine.scripting.Scripting.java

protected Object _runScript(ScriptFile script, Map<String, Object> args) throws Exception {
    SimpleBindings bindings = new SimpleBindings();
    if (args != null) {
        bindings.putAll(args);//from   w  w  w. j a v  a 2 s . c  o m
    }
    String ext = script.getExtension();
    // check for a script engine
    ScriptEngine engine = getEngineManager().getEngineByExtension(ext);
    if (engine != null) {
        ScriptContext ctx = new SimpleScriptContext();
        ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        CompiledScript comp = getCompiledScript(engine, script.getFile()); // use cache for compiled scripts
        if (comp != null) {
            return comp.eval(ctx);
        } // compilation not supported - eval it on the fly
        try {
            Reader reader = new FileReader(script.getFile());
            try { // TODO use __result__ to pass return value for engine that doesn't returns like jython
                Object result = engine.eval(reader, ctx);
                if (result == null) {
                    result = bindings.get("__result__");
                }
                return result;
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    }
    return null;
}

From source file:org.opennms.features.topology.plugins.topo.graphml.GraphMLEdgeStatusProvider.java

private GraphMLEdgeStatus computeEdgeStatus(final List<StatusScript> scripts, final GraphMLEdge edge) {
    return scripts.stream().flatMap(script -> {
        final SimpleBindings bindings = createBindings(edge);
        final StringWriter writer = new StringWriter();
        final ScriptContext context = new SimpleScriptContext();
        context.setWriter(writer);//w  w  w.  j  ava  2s.  co  m
        context.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
        try {
            LOG.debug("Executing script: {}", script);
            final GraphMLEdgeStatus status = script.eval(context);
            if (status != null) {
                return Stream.of(status);
            } else {
                return Stream.empty();
            }
        } catch (final ScriptException e) {
            LOG.error("Failed to execute script: {}", e);
            return Stream.empty();
        } finally {
            LOG.info(writer.toString());
        }
    }).reduce(GraphMLEdgeStatus::merge).orElse(null);
}

From source file:org.wso2.carbon.business.rules.core.util.TemplateManagerHelper.java

/**
 * Runs the script that is given as a string, and gives all the variables specified in the script
 *
 * @param script//  w  w  w .  j  a  v  a  2  s . com
 * @return Map of Strings
 * @throws TemplateManagerHelperException
 */
public static Map<String, String> getScriptGeneratedVariables(String script)
        throws RuleTemplateScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    ScriptContext scriptContext = new SimpleScriptContext();
    scriptContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

    try {
        // Run script
        engine.eval(script);
        Map<String, Object> returnedScriptContextBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);

        // Variable names and their values as strings, from the script context binding
        Map<String, String> scriptVariables = new HashMap<>();
        for (Map.Entry scriptVariable : returnedScriptContextBindings.entrySet()) {
            if (scriptVariable.getValue() == null) {
                scriptVariables.put(scriptVariable.getKey().toString(), null);
            } else {
                scriptVariables.put(scriptVariable.getKey().toString(), scriptVariable.getValue().toString());
            }
        }
        return scriptVariables;
    } catch (ScriptException e) {
        throw new RuleTemplateScriptException(e.getCause().getMessage(), e);
    }
}