Example usage for javax.script Bindings putAll

List of usage examples for javax.script Bindings putAll

Introduction

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

Prototype

public void putAll(Map<? extends String, ? extends Object> toMerge);

Source Link

Document

Adds all the mappings in a given Map to this Bindings .

Usage

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  ww. ja va  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");
    }
}

From source file:org.ms123.common.utils.UtilsServiceImpl.java

public Object executeScript(String scriptName, String namespace, String user, Map params) throws Exception {
    System.out.println("UtilsServiceImpl.executeScript:" + params);
    String storeId = (String) params.get("storeId");
    StoreDesc sdesc = StoreDesc.get(storeId);
    namespace = sdesc.getNamespace();//from w w  w  .  jav  a2s.c om
    System.out.println("UtilsServiceImpl.namespace:" + sdesc + "/" + namespace);
    ScriptEngine se = m_scriptEngineService.getEngineByName("groovy");
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    se.getContext().setWriter(pw);
    Bindings b = se.createBindings();
    b.putAll(params);
    b.put("jdo", m_dataLayer);
    b.put("ws", lookupServiceByName("org.ms123.common.workflow.api.WorkflowService"));
    b.put("ss", lookupServiceByName("org.ms123.common.setting.api.SettingService"));
    b.put("et", lookupServiceByName("org.ms123.common.entity.api.EntityService"));
    b.put("storeDesc", sdesc);
    b.put("home", System.getProperty("simpl4.dir"));
    b.put("log", m_logger);
    b.put("user", user);
    b.put("namespace", namespace);
    se.setBindings(b, ScriptContext.ENGINE_SCOPE);
    b.put("se", se);
    Object r = "";
    FileReader fr = getScriptFile(namespace, scriptName);
    r = se.eval(fr);
    System.out.println("r:" + r);
    pw.close();
    m_logger.info("executeScript:" + sw);
    System.out.println("executeScript:" + sw);
    return null;
}

From source file:org.mule.module.scripting.component.Scriptable.java

public void populateDefaultBindings(Bindings bindings) {
    if (properties != null) {
        bindings.putAll((Map) properties);
    }/*from w w w  .ja  v  a2 s.co m*/
    bindings.put("log", logger);
    // A place holder for a returned result if the script doesn't return a result.
    // The script can overwrite this binding
    bindings.put("result", NullPayload.getInstance());
    bindings.put("muleContext", muleContext);
    bindings.put("registry", muleContext.getRegistry());
}

From source file:org.netbeans.jcode.core.util.FileUtil.java

private static void expandTemplate(InputStream template, Map<String, Object> values, Charset targetEncoding,
        Writer w) throws IOException {
    //        Charset sourceEnc = FileEncodingQuery.getEncoding(template);
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    bind.putAll(values);
    bind.put(ENCODING_PROPERTY_NAME, targetEncoding.name());

    Reader is = null;//from   w ww  .j  av  a2s. c om
    try {
        eng.getContext().setWriter(w);
        is = new InputStreamReader(template);
        eng.eval(is);
    } catch (ScriptException ex) {
        throw new IOException(ex);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.netbeans.jcode.core.util.FileUtil.java

public static String expandTemplate(String template, Map<String, Object> values) {
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);
    }/*from  www  . j a v  a2 s .  c  om*/
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    Reader is = new StringReader(template);
    try {
        eng.eval(is);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();

}

From source file:org.nuxeo.ecm.webengine.DefaultWebContext.java

public Bindings createBindings(Map<String, Object> vars) {
    Bindings bindings = new SimpleBindings();
    if (vars != null) {
        bindings.putAll(vars);
    }/* w  w w .j a  v a  2  s  . c  o  m*/
    initDefaultBindings(bindings);
    return bindings;
}

From source file:org.omegat.gui.scripting.ScriptRunner.java

/**
 * Execute a script with a given engine and bindings.
 * /* w w w  .  j a  v a 2 s  .c o  m*/
 * @param script
 *            The script in string form
 * @param engine
 *            The engine
 * @param additionalBindings
 *            A map of bindings that will be included along with other
 *            bindings
 * @return The evaluation result
 * @throws ScriptException
 */
public static Object executeScript(String script, ScriptEngine engine, Map<String, Object> additionalBindings)
        throws ScriptException {
    // logResult(StaticUtils.format(OStrings.getString("SCW_SELECTED_LANGUAGE"),
    // engine.getFactory().getEngineName()));
    Bindings bindings = engine.createBindings();
    bindings.put(VAR_PROJECT, Core.getProject());
    bindings.put(VAR_EDITOR, Core.getEditor());
    bindings.put(VAR_GLOSSARY, Core.getGlossary());
    bindings.put(VAR_MAINWINDOW, Core.getMainWindow());
    bindings.put(VAR_CORE, Core.class);

    if (additionalBindings != null) {
        bindings.putAll(additionalBindings);
    }
    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    Object result = engine.eval(script);
    if (engine instanceof Invocable) {
        invokeGuiScript((Invocable) engine);
    }
    return result;
}

From source file:org.openhab.binding.ebus.internal.parser.EBusTelegramParser.java

/**
 * Evaluates the compiled script of a entry.
 * @param entry The configuration entry to evaluate
 * @param scopeValues All known values for script scope
 * @return The computed value//  www  .  j av a 2  s.c o m
 * @throws ScriptException
 */
private Object evaluateScript(Entry<String, Map<String, Object>> entry, Map<String, Object> scopeValues)
        throws ScriptException {

    Object value = null;

    // executes compiled script
    if (entry.getValue().containsKey("cscript")) {
        CompiledScript cscript = (CompiledScript) entry.getValue().get("cscript");

        // Add global variables thisValue and keyName to JavaScript context
        Bindings bindings = cscript.getEngine().createBindings();
        bindings.putAll(scopeValues);
        value = cscript.eval(bindings);
    }

    // try to convert the returned value to BigDecimal
    value = ObjectUtils.defaultIfNull(NumberUtils.toBigDecimal(value), value);

    // round to two digits, maybe not optimal for any result
    if (value instanceof BigDecimal) {
        ((BigDecimal) value).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    return value;
}

From source file:org.openhab.binding.ebus.parser.EBusTelegramParser.java

/**
 * @param entry//from  www.ja  v a2s .  co  m
 * @param bindings2
 * @return
 * @throws ScriptException
 */
private Object evaluateScript(Entry<String, Map<String, Object>> entry, Map<String, Object> bindings2)
        throws ScriptException {
    Object value = null;
    if (entry.getValue().containsKey("cscript")) {
        CompiledScript cscript = (CompiledScript) entry.getValue().get("cscript");

        // Add global variables thisValue and keyName to JavaScript context
        Bindings bindings = cscript.getEngine().createBindings();
        bindings.putAll(bindings2);
        value = cscript.eval(bindings);
    }

    value = ObjectUtils.defaultIfNull(NumberUtils.toBigDecimal(value), value);

    // round to two digits, maybe not optimal for any result
    if (value instanceof BigDecimal) {
        ((BigDecimal) value).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    return value;
}

From source file:org.opennms.opennms.pris.plugins.script.util.ScriptManager.java

public static Object execute(final InstanceConfiguration config, final Map<String, Object> bindings)
        throws IOException, ScriptException {

    Requisition requisition = null;/* w ww.  j  a  v  a 2 s .  com*/
    // Get the path to the script
    final List<Path> scripts = config.getPaths("file");

    // Get the script engine by language defined in config or by extension if it
    // is not defined in the config
    final ScriptEngineManager SCRIPT_ENGINE_MANAGER = new ScriptEngineManager(
            ScriptManager.class.getClassLoader());

    for (Path script : scripts) {

        final ScriptEngine scriptEngine = config.containsKey("lang")
                ? SCRIPT_ENGINE_MANAGER.getEngineByName(config.getString("lang"))
                : SCRIPT_ENGINE_MANAGER.getEngineByExtension(FilenameUtils.getExtension(script.toString()));

        if (scriptEngine == null) {
            throw new RuntimeException("Script engine implementation not found");
        }

        // Create some bindings for values available in the script
        final Bindings scriptBindings = scriptEngine.createBindings();
        scriptBindings.put("script", script);
        scriptBindings.put("logger", LoggerFactory.getLogger(script.toString()));
        scriptBindings.put("config", config);
        scriptBindings.put("instance", config.getInstanceIdentifier());
        scriptBindings.put("interfaceUtils", new InterfaceUtils(config));
        scriptBindings.putAll(bindings);

        // Overwrite initial requisition with the requisition from the previous script, if there was any.
        if (requisition != null) {
            scriptBindings.put("requisition", requisition);
        }

        // Evaluate the script and return the requisition created in the script
        try (final Reader scriptReader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) {
            LOGGER.debug("Start Script {}", script);
            requisition = (Requisition) scriptEngine.eval(scriptReader, scriptBindings);
            LOGGER.debug("Done  Script {}", script);
        }
    }
    return requisition;
}