Example usage for javax.script Bindings put

List of usage examples for javax.script Bindings put

Introduction

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

Prototype

public Object put(String name, Object value);

Source Link

Document

Set a named value.

Usage

From source file:org.jahia.modules.macros.filter.MacrosFilter.java

private Bindings getBindings(RenderContext renderContext, Resource resource, ScriptContext scriptContext,
        Matcher matcher) {// ww  w  .j a  va2 s.  c  om
    Bindings bindings = new SimpleBindings();
    bindings.put("currentUser", renderContext.getUser());
    bindings.put("currentNode", resource.getNode());
    bindings.put("currentResource", resource);
    bindings.put("renderContext", renderContext);
    bindings.put("url", new URLGenerator(renderContext, resource));
    String group = matcher.group(3);
    if (group != null) {
        int i = 1;
        for (String s : StringUtils.split(group, ",")) {
            bindings.put("param" + (i++), s);
        }
    }
    try {
        bindings.put("currentAliasUser",
                renderContext.getMainResource().getNode().getSession().getAliasedUser());
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }
    return bindings;
}

From source file:org.jahia.modules.docrules.EmailDocumentRule.java

private String evaluate(String subject, JCRNodeWrapper document) {
    if (subject.contains("${")) {
        try {//  w  w  w  .jav a 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.apache.tinkerpop.gremlin.groovy.engine.ScriptEnginesTest.java

@Test
public void shouldMergeBindingsFromLocalAndGlobalWithMultiplePlugins() throws Exception {
    final ScriptEngines engines = new ScriptEngines(se -> {
    });//from   w ww  . j a  v  a 2 s. c om
    engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(),
            Collections.emptyMap());

    engines.loadPlugins(Arrays.asList(new GremlinPlugin() {
        @Override
        public String getName() {
            return "mock1";
        }

        @Override
        public void pluginTo(final PluginAcceptor pluginAcceptor)
                throws IllegalEnvironmentException, PluginInitializationException {
            pluginAcceptor.addBinding("y", "here");
        }
    }));

    final Bindings localBindings = new SimpleBindings();
    localBindings.put("x", "there");

    assertEquals("herethere", engines.eval("y+x", localBindings, "gremlin-groovy"));

    engines.loadPlugins(Arrays.asList(new GremlinPlugin() {
        @Override
        public String getName() {
            return "mock2";
        }

        @Override
        public void pluginTo(final PluginAcceptor pluginAcceptor)
                throws IllegalEnvironmentException, PluginInitializationException {
            pluginAcceptor.addBinding("z", "where");
            pluginAcceptor.addImports(new HashSet<>(Arrays.asList("import java.awt.Color")));
        }
    }));

    assertEquals("heretherewhere", engines.eval("y+x+z", localBindings, "gremlin-groovy"));
    assertEquals(Color.RED, engines.eval("Color.RED", localBindings, "gremlin-groovy"));

}

From source file:org.wicketstuff.nashorn.resource.NashornResource.java

/**
 * Ensure that the given script is going to be safe. Safe because of endless loops for example.
 * /*w  ww  . j  a v a2s .  c o m*/
 * @param script
 *            the script to be make safe
 * @param attributes
 *            the attributes
 * @return the safe script
 * @throws Exception
 *             if an error occured while making the script safe
 */
private String ensureSafetyScript(String script, Attributes attributes) throws Exception {
    ClassFilter classFilter = new ClassFilter() {
        @Override
        public boolean exposeToScripts(String arg0) {
            return true;
        }
    };
    NashornScriptCallable nashornScriptCallable = new NashornScriptCallable(
            getScriptByName(NashornResource.class.getSimpleName() + ".js"), attributes, classFilter,
            getWriter(), getErrorWriter()) {
        @Override
        protected void setup(Attributes attributes, Bindings bindings) {
            bindings.put("script", script);
            bindings.put("debug", isDebug());
            bindings.put("debug_log_prefix", NashornResource.class.getSimpleName() + " - ");
        }
    };
    return executeScript(nashornScriptCallable, false).toString();
}

From source file:org.jahia.modules.irclogs.filters.IRCLogPageTitleFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;//from  w w  w  .  ja  v  a 2s . c om
    String script = getResolvedTemplate();
    if (script != null) {
        Source source = new Source(previousOut);
        OutputDocument outputDocument = new OutputDocument(source);
        List<Element> headElementList = source.getAllElements(HTMLElementName.TITLE);
        for (Element element : headElementList) {
            final EndTag bodyEndTag = element.getEndTag();
            final StartTag bodyStartTag = element.getStartTag();
            String extension = StringUtils.substringAfterLast(template, ".");
            ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
            ScriptContext scriptContext = new irclogsScriptContext();
            final Bindings bindings = scriptEngine.createBindings();
            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()));

            // Parameters needed for title replacing
            bindings.put("orgTitle",
                    outputDocument.toString().substring(bodyStartTag.getEnd(), bodyEndTag.getBegin()));
            bindings.put("dateFormatter", dateFormatter);
            bindings.put("title", getTitle());
            bindings.put("renderContext", renderContext);

            scriptEngine.eval(script, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            final String irclogsScript = writer.toString();
            if (StringUtils.isNotBlank(irclogsScript)) {
                outputDocument.replace(bodyStartTag.getEnd(), bodyEndTag.getBegin() + 1,
                        AggregateCacheFilter.removeEsiTags(irclogsScript) + "<");
            }
            break; // avoid to loop if for any reasons multiple body in the page
        }
        out = outputDocument.toString().trim();
    }

    return out;
}

From source file:org.jahia.modules.portal.filter.PortalLibFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;/*from w  w w  .  j av  a2s.  c  om*/

    // add portal API lib
    String path = "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType()
            .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JS_API_FILE;
    path = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath())
            ? renderContext.getRequest().getContextPath() + path
            : path;
    String encodedPath = URLEncoder.encode(path, "UTF-8");
    out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='"
            + JS_API_FILE + "'/>");

    // add portal instance
    String script = getResolvedTemplate();
    if (script != null) {
        String extension = StringUtils.substringAfterLast(template, ".");
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
        ScriptContext scriptContext = new PortalScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        // bindings
        bindings.put("portalContext", serializePortal(renderContext));
        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(script, scriptContext);
        StringWriter writer = (StringWriter) scriptContext.getWriter();
        final String portalScript = writer.toString();
        if (StringUtils.isNotBlank(portalScript)) {
            out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(portalScript, "UTF-8")
                    + "' insert='false' resource='' title='' key=''/>");
        }
    }

    return out;
}

From source file:org.onesec.raven.ivr.queue.actions.RegisterOperatorActionNode.java

@Override
public void formExpressionBindings(Bindings bindings) {
    super.formExpressionBindings(bindings);
    ConversationScenarioState state = getConversationState(bindings);
    if (state != null && state.getBindings().containsKey(OPERATOR_BINDING))
        bindings.put(OPERATOR_BINDING, state.getBindings().get(OPERATOR_BINDING));
}

From source file:org.jahia.modules.portal.filter.JCRRestJavaScriptLibFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;/*from ww w  .  ja v  a  2 s.c o  m*/
    String context = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath())
            ? renderContext.getRequest().getContextPath()
            : "";

    // add lib
    String path = context + "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType()
            .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JCR_REST_JS_FILE;
    String encodedPath = URLEncoder.encode(path, "UTF-8");
    out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='"
            + JCR_REST_JS_FILE + "'/>");

    // instance JavaScript object
    String script = getResolvedTemplate();
    if (script != null) {
        String extension = StringUtils.substringAfterLast(JCR_REST_SCRIPT_TEMPLATE, ".");
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
        ScriptContext scriptContext = new JCRRestUtilsScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        // bindings
        bindings.put("options", getBindingMap(renderContext, resource, context));
        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(script, scriptContext);
        StringWriter writer = (StringWriter) scriptContext.getWriter();
        final String resultScript = writer.toString();
        if (StringUtils.isNotBlank(resultScript)) {
            out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(resultScript, "UTF-8")
                    + "' insert='false' resource='' title='' key=''/>");
        }
    }

    return out;
}

From source file:org.fit.cssbox.scriptbox.demo.tester.ConsoleInjector.java

@Override
public boolean inject(ScriptContext context) {
    Console console = new Console(textPane);
    Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("console", console);

    return true;//from  w w  w  .  j a va 2  s  .c  om
}

From source file:org.freeplane.plugin.script.GenericScript.java

private Bindings createBinding(final NodeModel node) {
    final Bindings binding = engine.createBindings();
    binding.put("c", ProxyFactory.createController(scriptContext));
    binding.put("node", ProxyFactory.createNode(node, scriptContext));
    binding.putAll(ScriptingConfiguration.getStaticProperties());
    return binding;
}