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.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;//from ww w.  j a  v  a  2 s .  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);
            }
        }
    }
}