Example usage for javax.script ScriptContext getWriter

List of usage examples for javax.script ScriptContext getWriter

Introduction

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

Prototype

public Writer getWriter();

Source Link

Document

Returns the Writer for scripts to use when displaying output.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptContext ctx = new SimpleScriptContext();

    // Get the reader and writers from the script context
    Reader inputReader = ctx.getReader();
    Writer outputWriter = ctx.getWriter();
    Writer errWriter = ctx.getErrorWriter();

    // Write all script outputs to an out.txt file
    Writer fileWriter = new FileWriter("out.txt");
    ctx.setWriter(fileWriter);/*from  w ww .j  a  v  a 2 s.  c  om*/
}

From source file:org.jahia.modules.irclogs.filters.IRCLogPageTitleFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;/*from   w w w .  java  2  s  .c  o  m*/
    String script = getResolvedTemplate();
    if (script != null) {
        Source source = new Source(previousOut);
        OutputDocument outputDocument = new OutputDocument(source);
        List<Element> headElementList = source.getAllElements(HTMLElementName.TITLE);
        for (Element element : headElementList) {
            final EndTag bodyEndTag = element.getEndTag();
            final StartTag bodyStartTag = element.getStartTag();
            String extension = StringUtils.substringAfterLast(template, ".");
            ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
            ScriptContext scriptContext = new irclogsScriptContext();
            final Bindings bindings = scriptEngine.createBindings();
            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()));

            // Parameters needed for title replacing
            bindings.put("orgTitle",
                    outputDocument.toString().substring(bodyStartTag.getEnd(), bodyEndTag.getBegin()));
            bindings.put("dateFormatter", dateFormatter);
            bindings.put("title", getTitle());
            bindings.put("renderContext", renderContext);

            scriptEngine.eval(script, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            final String irclogsScript = writer.toString();
            if (StringUtils.isNotBlank(irclogsScript)) {
                outputDocument.replace(bodyStartTag.getEnd(), bodyEndTag.getBegin() + 1,
                        AggregateCacheFilter.removeEsiTags(irclogsScript) + "<");
            }
            break; // avoid to loop if for any reasons multiple body in the page
        }
        out = outputDocument.toString().trim();
    }

    return out;
}

From source file:org.jahia.modules.portal.filter.PortalLibFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;//from  w w w  .j av  a 2 s  .  co  m

    // add portal API lib
    String path = "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType()
            .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JS_API_FILE;
    path = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath())
            ? renderContext.getRequest().getContextPath() + path
            : path;
    String encodedPath = URLEncoder.encode(path, "UTF-8");
    out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='"
            + JS_API_FILE + "'/>");

    // add portal instance
    String script = getResolvedTemplate();
    if (script != null) {
        String extension = StringUtils.substringAfterLast(template, ".");
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
        ScriptContext scriptContext = new PortalScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        // bindings
        bindings.put("portalContext", serializePortal(renderContext));
        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 portalScript = writer.toString();
        if (StringUtils.isNotBlank(portalScript)) {
            out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(portalScript, "UTF-8")
                    + "' insert='false' resource='' title='' key=''/>");
        }
    }

    return out;
}

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  ww . j  ava  2s  .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.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java

Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException {
    final Binding binding = new Binding(context.getBindings(ScriptContext.ENGINE_SCOPE)) {
        @Override/*w w w. j a v  a  2  s.  com*/
        public Object getVariable(String name) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope != -1) {
                    return context.getAttribute(name, scope);
                }
                // Redirect script output to context writer, if out var is not already provided
                if ("out".equals(name)) {
                    final Writer writer = context.getWriter();
                    if (writer != null) {
                        return (writer instanceof PrintWriter) ? (PrintWriter) writer
                                : new PrintWriter(writer, true);
                    }
                }
                // Provide access to engine context, if context var is not already provided
                if ("context".equals(name)) {
                    return context;
                }
            }
            throw new MissingPropertyException(name, getClass());
        }

        @Override
        public void setVariable(String name, Object value) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope == -1) {
                    scope = ScriptContext.ENGINE_SCOPE;
                }
                context.setAttribute(name, value, scope);
            }
        }
    };

    try {
        // if this class is not an instance of Script, it's a full-blown class then simply return that class
        if (!Script.class.isAssignableFrom(scriptClass)) {
            return scriptClass;
        } else {
            final Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
            for (Method m : scriptClass.getMethods()) {
                final String name = m.getName();
                globalClosures.put(name, new MethodClosure(scriptObject, name));
            }

            final MetaClass oldMetaClass = scriptObject.getMetaClass();
            scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {
                @Override
                public Object invokeMethod(final Object object, final String name, final Object args) {
                    if (args == null) {
                        return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                    } else if (args instanceof Tuple) {
                        return invokeMethod(object, name, ((Tuple) args).toArray());
                    } else if (args instanceof Object[]) {
                        return invokeMethod(object, name, (Object[]) args);
                    } else {
                        return invokeMethod(object, name, new Object[] { args });
                    }
                }

                @Override
                public Object invokeMethod(final Object object, final String name, final Object args[]) {
                    try {
                        return super.invokeMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, context);
                    }
                }

                @Override
                public Object invokeStaticMethod(final Object object, final String name, final Object args[]) {
                    try {
                        return super.invokeStaticMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, context);
                    }
                }
            });

            final Object o = scriptObject.run();

            // if interpreter mode is enable then local vars of the script are promoted to engine scope bindings.
            if (interpreterModeEnabled) {
                final Map<String, Object> localVars = (Map<String, Object>) context
                        .getAttribute(COLLECTED_BOUND_VARS_MAP_VARNAME);
                if (localVars != null) {
                    localVars.entrySet().forEach(e -> {
                        // closures need to be cached for later use
                        if (e.getValue() instanceof Closure)
                            globalClosures.put(e.getKey(), (Closure) e.getValue());

                        context.setAttribute(e.getKey(), e.getValue(), ScriptContext.ENGINE_SCOPE);
                    });

                    // get rid of the temporary collected vars
                    context.removeAttribute(COLLECTED_BOUND_VARS_MAP_VARNAME, ScriptContext.ENGINE_SCOPE);
                    localVars.clear();
                }
            }

            return o;
        }
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:org.jahia.ajax.gwt.helper.UIConfigHelper.java

/**
 * Get resources/*from  w ww  .  ja 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.docrules.EmailDocumentRule.java

private String evaluate(String subject, JCRNodeWrapper document) {
    if (subject.contains("${")) {
        try {//  w ww  . j a v a2s . c  o m
            ScriptEngine byName = ScriptEngineUtils.getInstance().getEngineByName("velocity");
            ScriptContext scriptContext = byName.getContext();
            final Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
            bindings.put("document", document);
            scriptContext.setWriter(new StringWriter());
            scriptContext.setErrorWriter(new StringWriter());
            byName.eval(subject, bindings);
            return scriptContext.getWriter().toString().trim();
        } catch (ScriptException e) {
            logger.error("Error while evaluating value [" + subject + "]", e);
        }
    }

    return null;
}

From source file:org.jahia.modules.macros.filter.MacrosFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    if (StringUtils.isEmpty(previousOut)) {
        return previousOut;
    }//from   w ww .  ja va 2  s  . c o m
    long timer = System.currentTimeMillis();
    boolean evaluated = false;

    Matcher matcher = macrosPattern.matcher(previousOut);
    while (matcher.find()) {
        evaluated = true;
        String macroName = matcher.group(1);
        String[] macro = getMacro(macroName);
        if (macro != null) {
            try {
                // execute macro
                ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(macro[1]);
                ScriptContext scriptContext = scriptEngine.getContext();
                scriptContext.setWriter(new StringWriter());
                scriptContext.setErrorWriter(new StringWriter());
                scriptEngine.eval(macro[0], getBindings(renderContext, resource, scriptContext, matcher));
                String scriptResult = scriptContext.getWriter().toString().trim();
                previousOut = matcher.replaceFirst(scriptResult);
            } catch (ScriptException e) {
                logger.warn("Error during execution of macro " + macroName + " with message " + e.getMessage(),
                        e);
                previousOut = matcher.replaceFirst(macroName);
            }
            matcher = macrosPattern.matcher(previousOut);
        } else if (replaceByErrorMessageOnMissingMacros) {
            previousOut = matcher.replaceFirst("macro " + macroName + " not found");
            logger.warn("Unknown macro '{}'", macroName);
            matcher = macrosPattern.matcher(previousOut);
        }
    }

    if (evaluated && logger.isDebugEnabled()) {
        logger.debug("Evaluation of macros took {} ms", (System.currentTimeMillis() - timer));
    }
    return previousOut;
}

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;// www .  j  ava2s.  c  o  m
    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;
}