Example usage for javax.script ScriptContext GLOBAL_SCOPE

List of usage examples for javax.script ScriptContext GLOBAL_SCOPE

Introduction

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

Prototype

int GLOBAL_SCOPE

To view the source code for javax.script ScriptContext GLOBAL_SCOPE.

Click Source Link

Document

GlobalScope attributes are visible to all engines created by same ScriptEngineFactory.

Usage

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 ww. ja va2s.  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.jaffa.rules.util.ScriptEnginePool.java

/**
 * Clears the script engine of all previous state except, if it is a BeanShell interpreter,
 * the engine is left/*from w w w.j  a va  2  s  . c  o  m*/
 *
 * @param scriptEngine ScriptEngine to clear
 */
private void clearEngine(String language, ScriptEngine scriptEngine) {
    // Clear everything except the BeanShell engine ("bsh" in the binding)
    // This will clear all imported class, methods, and variables
    List<String> itemsToRemove = new ArrayList<String>();
    for (Map.Entry<String, Object> bindingEntry : scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE)
            .entrySet()) {
        if (language.equalsIgnoreCase(BEANSHELL)
                && bindingEntry.getKey().equalsIgnoreCase(BEANSHELL_ENGINE_NAME)) {
            continue;
        }
        itemsToRemove.add(bindingEntry.getKey());
    }
    for (String value : itemsToRemove) {
        scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove(value);
    }

    // Clear entire global scope
    scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE).clear();
}

From source file:org.jahia.utils.ScriptEngineUtils.java

private void initEngine(ScriptEngine engine) {
    if (engine.getFactory().getNames().contains("velocity")) {
        final Properties velocityProperties = new Properties();
        final String key = "runtime.log.logsystem.log4j.logger";
        final String log4jLoggerProp = System.getProperty(key);
        if (log4jLoggerProp != null) {
            velocityProperties.setProperty(key, log4jLoggerProp);
        } else {/*  w  ww.  jav a  2 s. co m*/
            velocityProperties.setProperty(key, "root");
        }
        engine.getContext().setAttribute("com.sun.script.velocity.properties", velocityProperties,
                ScriptContext.GLOBAL_SCOPE);
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java

public GremlinGroovyScriptEngine(final Customizer... customizers) {
    // initialize the global scope in case this scriptengine was instantiated outside of the ScriptEngineManager
    setBindings(new ConcurrentBindings(), ScriptContext.GLOBAL_SCOPE);

    final List<Customizer> listOfCustomizers = new ArrayList<>(Arrays.asList(customizers));

    // always need this plugin for a scriptengine to be "Gremlin-enabled"
    CoreGremlinPlugin.instance().getCustomizers("gremlin-groovy")
            .ifPresent(c -> listOfCustomizers.addAll(Arrays.asList(c)));

    GremlinLoader.load();//from  w ww .ja  va 2s .c o m

    final List<ImportCustomizer> importCustomizers = listOfCustomizers.stream()
            .filter(p -> p instanceof ImportCustomizer).map(p -> (ImportCustomizer) p)
            .collect(Collectors.toList());
    final ImportCustomizer[] importCustomizerArray = new ImportCustomizer[importCustomizers.size()];
    importGroovyCustomizer = new ImportGroovyCustomizer(importCustomizers.toArray(importCustomizerArray));

    groovyCustomizers = listOfCustomizers.stream().filter(p -> p instanceof GroovyCustomizer)
            .map(p -> ((GroovyCustomizer) p)).collect(Collectors.toList());

    final Optional<CompilationOptionsCustomizer> compilationOptionsCustomizerProvider = listOfCustomizers
            .stream().filter(p -> p instanceof CompilationOptionsCustomizer)
            .map(p -> (CompilationOptionsCustomizer) p).findFirst();
    expectedCompilationTime = compilationOptionsCustomizerProvider.isPresent()
            ? compilationOptionsCustomizerProvider.get().getExpectedCompilationTime()
            : 5000;

    typeCheckingEnabled = listOfCustomizers.stream().anyMatch(
            p -> p instanceof TypeCheckedGroovyCustomizer || p instanceof CompileStaticGroovyCustomizer);

    // determine if interpreter mode should be enabled
    interpreterModeEnabled = groovyCustomizers.stream()
            .anyMatch(p -> p.getClass().equals(InterpreterModeGroovyCustomizer.class));

    createClassLoader();
}

From source file:org.labkey.nashorn.NashornController.java

private Pair<ScriptEngine, ScriptContext> getNashorn(boolean useSession) throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine;//from  w ww .j  a  v  a 2  s  .c  o m
    ScriptContext context;

    Callable<ScriptEngine> createContext = new Callable<ScriptEngine>() {
        @Override
        @NotNull
        public ScriptEngine call() throws Exception {
            NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
            ScriptEngine engine = factory.getScriptEngine(new String[] { "--global-per-engine" });
            return engine;
        }
    };

    if (useSession) {
        HttpServletRequest req = getViewContext().getRequest();
        engine = SessionHelper.getAttribute(req, this.getClass().getName() + "#scriptEngine", createContext);
    } else {
        engine = createContext.call();
    }

    Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    engineScope.put("LABKEY", new org.labkey.nashorn.env.LABKEY(getViewContext()));

    Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
    // null==engine.getBindings(ScriptContext.GLOBAL_SCOPE), because of --global-per-engine
    // some docs mention enginScope.get("nashorn.global"), but that is also null
    if (null == globalScope)
        globalScope = (Bindings) engineScope.get("nashorn.global");
    if (null == globalScope)
        globalScope = engineScope;
    globalScope.put("console", new Console());

    return new Pair<>(engine, engine.getContext());
}

From source file:de.axelfaust.alfresco.nashorn.repo.processor.NashornScriptProcessor.java

protected void initScriptContext() throws ScriptException {
    final Bindings oldEngineBindings = this.engine.getBindings(ScriptContext.ENGINE_SCOPE);
    final AMDModulePreloader oldPreloader = this.amdPreloader;
    final AMDScriptRunner oldAMDRunner = this.amdRunner;

    LOGGER.debug("Initializing new script context");

    inEngineContextInitialization.set(Boolean.TRUE);
    try (NashornScriptModel model = NashornScriptModel.openModel()) {
        // create new (unpolluted) engine bindings
        final Bindings engineBindings = this.engine.createBindings();
        this.engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);

        final Bindings globalBindings = new SimpleBindings();
        this.engine.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);

        // only available during initialisation
        globalBindings.put("applicationContext", this.applicationContext);

        LOGGER.debug("Executing bootstrap scripts");
        URL resource;//  w  ww .  ja  v a  2s  . c om

        // 1) simple logger facade for SLF4J
        LOGGER.debug("Bootstrapping simple logger");
        resource = NashornScriptProcessor.class.getResource(SCRIPT_SIMPLE_LOGGER);
        this.executeScriptFromResource(resource);

        // 2) AMD loader and noSuchProperty to be used for all scripts apart from bootstrap
        LOGGER.debug("Setting up AMD");
        resource = NashornScriptProcessor.class.getResource(SCRIPT_AMD);
        this.executeScriptFromResource(resource);

        resource = NashornScriptProcessor.class.getResource(SCRIPT_NO_SUCH_PROPERTY);
        this.executeScriptFromResource(resource);

        final Object define = this.engine.get("define");
        this.amdPreloader = ((Invocable) this.engine).getInterface(define, AMDModulePreloader.class);

        // 3) the nashorn loader plugin so we can control access to globals
        LOGGER.debug("Setting up nashorn AMD loader");
        this.preloadAMDModule("loaderMetaLoader", "nashorn", "nashorn");

        // 4) remove Nashorn globals
        LOGGER.debug("Removing disallowed Nashorn globals \"{}\" and \"{}\"",
                NASHORN_GLOBAL_PROPERTIES_TO_ALWAYS_REMOVE, this.nashornGlobalPropertiesToRemove);
        for (final String property : NASHORN_GLOBAL_PROPERTIES_TO_ALWAYS_REMOVE) {
            engineBindings.remove(property);
        }

        if (this.nashornGlobalPropertiesToRemove != null) {
            for (final String property : this.nashornGlobalPropertiesToRemove.split(",")) {
                engineBindings.remove(property.trim());
            }
        }

        // 5) Java extensions (must be picked up by modules before #9)
        globalBindings.put("processorExtensions", this.processorExtensions);

        // 6) AMD config
        LOGGER.debug("Applying AMD config \"{}\"", this.amdConfig);
        resource = this.amdConfig.getURL();
        this.executeScriptFromResource(resource);

        // 7) configured JavaScript base modules
        LOGGER.debug("Bootstrapping base modules");
        this.initScriptContextBaseModules(this.amdPreloader);

        // 8) configured JavaScript extension modules
        LOGGER.debug("Bootstrapping extension modules");
        this.initScriptContextExtensions(this.amdPreloader);

        // 9) remove any init data that shouldn't be publicly available
        globalBindings.clear();

        // 10) obtain the runner interface
        LOGGER.debug("Preparing AMD script runner");
        resource = NashornScriptProcessor.class.getResource(SCRIPE_AMD_SCRIPT_RUNNER);
        final Object scriptRunnerObj = this.executeScriptFromResource(resource);
        this.amdRunner = ((Invocable) this.engine).getInterface(scriptRunnerObj, AMDScriptRunner.class);

        LOGGER.info("New script context initialized");
    } catch (final Throwable t) {
        LOGGER.warn("Initialization of script context failed", t);

        // reset
        this.engine.setBindings(oldEngineBindings, ScriptContext.ENGINE_SCOPE);
        this.engine.getBindings(ScriptContext.GLOBAL_SCOPE).clear();
        this.amdPreloader = oldPreloader;
        this.amdRunner = oldAMDRunner;

        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof ScriptException) {
            throw (ScriptException) t;
        } else {
            throw new org.alfresco.scripts.ScriptException(
                    "Unknown error initializing script context - reset to previous state", t);
        }
    } finally {
        inEngineContextInitialization.remove();
    }
}

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;//  www. j  a v a  2 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();
}

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 w  w  w  .j av 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);
            }
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java

/**
 * Creates the {@code ScriptContext} using a {@link GremlinScriptContext} which avoids a significant amount of
 * additional object creation on script evaluation.
 *///from ww  w. j  a v  a2 s .c  o m
@Override
protected ScriptContext getScriptContext(final Bindings nn) {
    final GremlinScriptContext ctxt = new GremlinScriptContext(context.getReader(), context.getWriter(),
            context.getErrorWriter());
    final Bindings gs = getBindings(ScriptContext.GLOBAL_SCOPE);

    if (gs != null)
        ctxt.setBindings(gs, ScriptContext.GLOBAL_SCOPE);

    if (nn != null) {
        ctxt.setBindings(nn, ScriptContext.ENGINE_SCOPE);
    } else {
        throw new NullPointerException("Engine scope Bindings may not be null.");
    }

    return ctxt;
}

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);
    }//from   w  w  w  . jav a 2  s .  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");
    }
}