Example usage for javax.script ScriptEngine eval

List of usage examples for javax.script ScriptEngine eval

Introduction

In this page you can find the example usage for javax.script ScriptEngine eval.

Prototype

public Object eval(Reader reader, Bindings n) throws ScriptException;

Source Link

Document

Same as eval(String, Bindings) except that the source of the script is provided as a Reader.

Usage

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 w w w  .j a  v a  2  s .  c  o  m*/
    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.jahia.services.render.filter.MarkedForDeletionFilter.java

protected String getTemplateOutput(RenderContext renderContext, Resource resource) {
    String out = StringUtils.EMPTY;
    try {//ww w .  j  a  va2s. 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.content.nodetypes.initializers.ScriptChoiceListInitializerImpl.java

public List<ChoiceListValue> getChoiceListValues(ExtendedPropertyDefinition epd, String param,
        List<ChoiceListValue> values, Locale locale, Map<String, Object> context) {
    if (param != null) {
        final String extension = Patterns.DOT.split(param)[1];
        ScriptEngine byName;
        try {//from   ww  w.j  ava 2  s  .  c  o  m
            byName = scriptEngineUtils.scriptEngine(extension);
        } catch (ScriptException e) {
            logger.error(e.getMessage(), e);
            byName = null;
        }
        if (byName != null) {
            final Set<JahiaTemplatesPackage> forModule = ServicesRegistry.getInstance()
                    .getJahiaTemplateManagerService().getModulesWithViewsForComponent(
                            JCRContentUtils.replaceColon(epd.getDeclaringNodeType().getName()));
            final Bindings bindings = byName.getBindings(ScriptContext.ENGINE_SCOPE);
            bindings.put("values", values);
            for (JahiaTemplatesPackage template : forModule) {
                final Resource scriptPath = template
                        .getResource(File.separator + "scripts" + File.separator + param);
                if (scriptPath != null && scriptPath.exists()) {
                    Reader scriptContent = null;
                    try {
                        scriptContent = new InputStreamReader(scriptPath.getInputStream());
                        return (List<ChoiceListValue>) byName.eval(scriptContent, bindings);
                    } catch (ScriptException e) {
                        logger.error("Error while executing script " + scriptPath, e);
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (scriptContent != null) {
                            IOUtils.closeQuietly(scriptContent);
                        }
                    }
                }
            }
        }
    }
    return Collections.emptyList();
}

From source file:org.jahia.osgi.FrameworkService.java

private void updateFileReferencesIfNeeded() {
    File script = new File(
            SettingsBean.getInstance().getJahiaVarDiskPath() + "/scripts/groovy/updateFileReferences.groovy");
    if (!script.isFile()) {
        return;/*from   w  w w.  j  ava 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:com.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

private ConsoleOutputBean eval(ScriptEngine engine, String evalScript, Map<String, ?> bindings,
        final ConsoleOutputBean consoleOutputBean) throws ScriptException {
    updateBindings(engine, ScriptContext.ENGINE_SCOPE, new HashMap<String, Object>() {
        {//from   w ww  .j  a v  a 2  s.c om
            put("out", new PrintWriter(consoleOutputBean.getOut(), true));
            put("err", new PrintWriter(consoleOutputBean.getErr(), true));
        }
    });

    if (bindings != null && !bindings.isEmpty()) {
        updateBindings(engine, ScriptContext.ENGINE_SCOPE, bindings);
    }

    engine.getContext().setWriter(consoleOutputBean.getOut());
    engine.getContext().setErrorWriter(consoleOutputBean.getErr());
    engine.getContext().setReader(new NullReader(0));

    consoleOutputBean.setEvalResult(engine.eval(evalScript, engine.getContext()));

    return consoleOutputBean;
}

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  ww  . j  a  v  a2  s. co  m*/
    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:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

private static void checkAndLoadJSFile(ScriptEngine actualContext, Bindings eval_scope, String fileName) {
    Reader inStream = null;/*from ww  w  . j a  va2 s .  c o m*/
    try {
        inStream = new InputStreamReader(KettleVFS.getInputStream(fileName));
        actualContext.eval(inStream, eval_scope);
    } /*
      //TODO AKRETION: see if we can find better catches compatibles with JSR223
      catch (FileNotFoundException Signal) {
       new RuntimeException("Unable to open file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")");
      } catch (WrappedException Signal) {
       new RuntimeException("WrappedException while evaluating file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")");
      } catch (EvaluatorException Signal) {
       new RuntimeException("EvaluatorException while evaluating file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")");
      } catch (JavaScriptException Signal) {
       new RuntimeException("JavaScriptException while evaluating file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")");
      } catch (IOException Signal) {
       new RuntimeException("Error while reading file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")"         );
      } */
    catch (KettleFileException Signal) {
        new RuntimeException(
                "Error while reading file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")");
    } catch (ScriptException Signal) {
        new RuntimeException(
                "Error while reading file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")");
    } finally {
        try {
            if (inStream != null)
                inStream.close();
        } catch (Exception Signal) {
            /* nop */
        }
        ;
    }
    ;
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

private static void checkAndLoadJSFile(ScriptEngine actualContext, Bindings eval_scope, String fileName) {
    Reader inStream = null;/*from  w  ww.ja va2 s . c  o m*/
    try {
        inStream = new InputStreamReader(KettleVFS.getInputStream(fileName));
        actualContext.eval(inStream, eval_scope);
    } catch (KettleFileException Signal) {
        /*
         * //TODO AKRETION: see if we can find better catches compatibles with JSR223 catch (FileNotFoundException Signal)
         * { new RuntimeException("Unable to open file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")"); }
         * catch (WrappedException Signal) { new RuntimeException("WrappedException while evaluating file \"" + fileName +
         * "\" (reason: \"" + Signal.getMessage() + "\")"); } catch (EvaluatorException Signal) { new
         * RuntimeException("EvaluatorException while evaluating file \"" + fileName + "\" (reason: \"" +
         * Signal.getMessage() + "\")"); } catch (JavaScriptException Signal) { new
         * RuntimeException("JavaScriptException while evaluating file \"" + fileName + "\" (reason: \"" +
         * Signal.getMessage() + "\")"); } catch (IOException Signal) { new RuntimeException("Error while reading file \""
         * + fileName + "\" (reason: \"" + Signal.getMessage() + "\")" ); }
         */
        new RuntimeException(
                "Error while reading file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")");
    } catch (ScriptException Signal) {
        new RuntimeException(
                "Error while reading file \"" + fileName + "\" (reason: \"" + Signal.getMessage() + "\")");
    } finally {
        try {
            if (inStream != null) {
                inStream.close();
            }
        } catch (Exception Signal) {
            // Ignore
        }
    }
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void LoadScriptFromTab(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    try {/*  w w w . j a  va  2  s.co  m*/
        for (int i = 0; i < ArgList.length; i++) { // don't worry about "undefined" arguments
            String strToLoad = (String) ArgList[i];
            String strScript = actualObject.get(strToLoad).toString();
            actualContext.eval(strScript, actualObject);
        }
    } catch (Exception e) {
        //System.out.println(e.toString());
    }
}

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  av  a2  s . c om
    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();
}