Example usage for javax.script ScriptContext setErrorWriter

List of usage examples for javax.script ScriptContext setErrorWriter

Introduction

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

Prototype

public void setErrorWriter(Writer writer);

Source Link

Document

Sets the Writer used to display error output.

Usage

From source file:jp.toastkid.script.runner.JavaScriptRunner.java

@Override
public Optional<String> run(final String script) {

    if (StringUtils.isEmpty(script)) {
        return Optional.empty();
    }/*from  w ww.  j  a  va2  s  .c o  m*/
    final StringBuilder result = new StringBuilder();

    try (final StringWriter writer = new StringWriter();) {
        final ScriptContext context = engine.getContext();
        context.setWriter(writer);
        context.setErrorWriter(writer);

        final java.lang.Object run = engine.eval(script);
        result.append(writer.toString()).append(LINE_SEPARATOR);
        if (run != null) {
            result.append("return = ").append(run.toString());
        }
        writer.close();
    } catch (final CompilationFailedException | IOException | ScriptException e) {
        e.printStackTrace();
        result.append("Occurred Exception.").append(LINE_SEPARATOR).append(e.getMessage());
    }
    return Optional.of(result.toString());
}

From source file:jp.toastkid.script.runner.GroovyRunner.java

@Override
public Optional<String> run(final String script) {
    if (StringUtils.isEmpty(script)) {
        return Optional.empty();
    }/*  ww w  .ja  v  a  2 s  . c  o m*/
    if (engine == null) {
        System.out.println("groovy null");
    }

    final StringBuilder result = new StringBuilder();

    try (final StringWriter writer = new StringWriter();) {
        if (engine != null) {
            final ScriptContext context = engine.getContext();
            context.setWriter(new PrintWriter(writer));
            context.setErrorWriter(new PrintWriter(writer));
        }
        final java.lang.Object run = engine.eval(script);
        result.append(writer.toString()).append(LINE_SEPARATOR);
        if (run != null) {
            result.append("return = ").append(run.toString());
        }
        writer.close();
    } catch (final CompilationFailedException | IOException | javax.script.ScriptException e) {
        e.printStackTrace();
        result.append("Occurred Exception.").append(LINE_SEPARATOR).append(e.getMessage());
    }
    return Optional.of(result.toString());
}

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

/**
 * Get resources//from   w w w . j  a  va2 s  .  co 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 {/*from   www .j a  va  2 s  .co  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.j a v a  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.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);
    }//w w w. jav  a 2s .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.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.  co m*/
 * @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.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 . j  a v a 2s  . c om
    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.services.workflow.jbpm.JBPMMailProducer.java

private String evaluateExpression(Execution execution, String scriptToExecute, JCRSessionWrapper session)
        throws RepositoryException, ScriptException {
    ScriptContext scriptContext = scriptEngine.getContext();
    if (bindings == null) {
        bindings = getBindings(execution, session);
    }//  w  ww. j a  v a 2  s .c o m
    scriptContext.setWriter(new StringWriter());
    scriptContext.setErrorWriter(new StringWriter());
    scriptEngine.eval(scriptToExecute, bindings);
    String error = scriptContext.getErrorWriter().toString();
    if (error.length() > 0) {
        logger.error("Scripting error : " + error);
    }
    return scriptContext.getWriter().toString().trim();
}