Example usage for javax.script SimpleBindings SimpleBindings

List of usage examples for javax.script SimpleBindings SimpleBindings

Introduction

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

Prototype

public SimpleBindings() 

Source Link

Document

Default constructor uses a HashMap .

Usage

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

/**
 * Get resources/*from w  w w  .  ja v a  2 s .  c  om*/
 *
 * @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;
}