Example usage for javax.script ScriptEngine createBindings

List of usage examples for javax.script ScriptEngine createBindings

Introduction

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

Prototype

public Bindings createBindings();

Source Link

Document

Returns an uninitialized Bindings.

Usage

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;//w w w  . j a v a2s.  c o m

    // 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.jahia.modules.irclogs.filters.IRCLogPageTitleFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;//from  www  .  j a  v a2 s.  com
    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:it.greenvulcano.script.impl.ScriptExecutorImpl.java

/**
 * Initialize the instance.//from ww w . j  a  v a2  s.  c om
 * 
 * @param lang
 *        script engine language
 * @param script
 *        the script to configure; if null the script must be passes in the execute method; overridden by 'file'
 * @param file
 *        if not null, defines the script file to read
 * @param bcName
 *        defines the BaseContext to be used to enrich the script;
 *        if null is used the default context for the given language, if defined
 * @throws GVScriptException
 */
public void init(String lang, String script, String file, String bcName) throws GVScriptException {
    try {
        this.lang = lang;
        if ((file != null) && !"".equals(file)) {
            this.script = cache.getScript(file);
        } else {
            this.script = script;
            if ((this.script == null) || "".equals(this.script)) {
                externalScript = true;
            }
        }

        if (!externalScript && ((this.script == null) || "".equals(this.script))) {
            throw new GVScriptException("Empty configured script!");
        }

        ScriptEngine engine = getScriptEngine(lang);
        if (engine == null) {
            throw new GVScriptException("ScriptEngine[" + this.lang + "] not found!");
        }
        bindings = engine.createBindings();

        String baseContext = BaseContextManager.instance().getBaseContextScript(lang, bcName);
        if (baseContext != null) {
            this.script = baseContext + "\n\n" + (this.script != null ? this.script : "");
            if (externalScript) {
                engine.eval(this.script, bindings);
            }
        } else if (bcName != null) {
            throw new GVScriptException("BaseContext[" + this.lang + "/" + bcName + "] not found!");
        }

        if (engine instanceof Compilable && PropertiesHandler.isExpanded(script)) {
            String scriptKey = DigestUtils.sha256Hex(script);
            Optional<CompiledScript> cachedCompiledScript = cache.getCompiledScript(scriptKey);

            if (cachedCompiledScript.isPresent()) {
                compScript = cachedCompiledScript.get();
            } else {
                logger.debug("Static script[" + lang + "], can be compiled for performance");
                compScript = ((Compilable) engine).compile(script);
                cache.putCompiledScript(scriptKey, compScript);
            }
        }

        initialized = true;
    } catch (GVScriptException exc) {
        logger.error("Error initializing ScriptExecutorImpl", exc);
        throw exc;
    } catch (Exception exc) {
        logger.error("Error initializing ScriptExecutorImpl", exc);
        throw new GVScriptException("Error initializing ScriptExecutorImpl", exc);
    }
}

From source file:com.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

@SuppressWarnings({ "SameParameterValue" })
private void updateBindings(ScriptEngine engine, int scope, Map<String, ?> mergeValues) {
    Bindings bindings = engine.getContext().getBindings(scope);
    if (bindings == null) {
        bindings = engine.createBindings();
        engine.getContext().setBindings(bindings, scope);
    }//from w w w  .  j  a  v a2s . c  o  m
    bindings.putAll(mergeValues);
}

From source file:it.greenvulcano.script.impl.ScriptExecutorImpl.java

/**
 * Initialize the instance.//from  w w w.ja va 2  s .c  o  m
 * 
 * @param node
 *        the configuration node
 * @throws GVScriptException
 */
public void init(Node node) throws GVScriptException {
    try {
        name = XMLConfig.get(node.getParentNode(), "@name");
        logger.debug("init script node " + name);
        lang = XMLConfig.get(node, "@lang", "js");
        String file = XMLConfig.get(node, "@file", "");
        if (!"".equals(file)) {
            scriptName = file;
            script = cache.getScript(file);
        } else {
            scriptName = ScriptCache.INTERNAL_SCRIPT;
            script = XMLConfig.get(node, ".", null);
        }

        if ((script == null) || "".equals(script)) {
            throw new GVScriptException("Empty configured script!");
        }

        ScriptEngine engine = getScriptEngine(lang);
        if (engine == null) {
            throw new GVScriptException("ScriptEngine[" + lang + "] not found!");
        }

        String bcName = XMLConfig.get(node, "@base-context", null);
        String baseContext = BaseContextManager.instance().getBaseContextScript(lang, bcName);
        if (baseContext != null) {
            script = baseContext + "\n\n" + (script != null ? script : "");
        } else if (bcName != null) {
            throw new GVScriptException("BaseContext[" + lang + "/" + bcName + "] not found!");
        }

        if (engine instanceof Compilable && PropertiesHandler.isExpanded(script)) {
            String scriptKey = DigestUtils.sha256Hex(script);

            Optional<CompiledScript> cachedCompiledScript = cache.getCompiledScript(scriptKey);

            if (cachedCompiledScript.isPresent()) {
                compScript = cachedCompiledScript.get();
            } else {
                logger.debug("Static script[" + lang + "], can be compiled for performance");
                compScript = ((Compilable) engine).compile(script);
                cache.putCompiledScript(scriptKey, compScript);
            }
        }
        bindings = engine.createBindings();

        initialized = true;
    } catch (GVScriptException exc) {
        logger.error("Error initializing ScriptExecutorImpl", exc);
        throw exc;
    } catch (Exception exc) {
        logger.error("Error initializing ScriptExecutorImpl", exc);
        throw new GVScriptException("Error initializing ScriptExecutorImpl", exc);
    }
}

From source file:org.apache.jmeter.util.JSR223TestElement.java

/**
 * This method will run inline script or file script with special behaviour for file script:
 * - If ScriptEngine implements Compilable script will be compiled and cached
 * - If not if will be run//ww w .ja  va2  s . c o m
 * @param scriptEngine ScriptEngine
 * @param bindings {@link Bindings} might be null
 * @return Object returned by script
 * @throws IOException when reading the script fails
 * @throws ScriptException when compiling or evaluation of the script fails
 */
protected Object processFileOrScript(ScriptEngine scriptEngine, Bindings bindings)
        throws IOException, ScriptException {
    if (bindings == null) {
        bindings = scriptEngine.createBindings();
    }
    populateBindings(bindings);
    File scriptFile = new File(getFilename());
    // Hack: bsh-2.0b5.jar BshScriptEngine implements Compilable but throws "java.lang.Error: unimplemented"
    boolean supportsCompilable = scriptEngine instanceof Compilable
            && !(scriptEngine.getClass().getName().equals("bsh.engine.BshScriptEngine")); // $NON-NLS-1$
    if (!StringUtils.isEmpty(getFilename())) {
        if (scriptFile.exists() && scriptFile.canRead()) {
            BufferedReader fileReader = null;
            try {
                if (supportsCompilable) {
                    String cacheKey = getScriptLanguage() + "#" + // $NON-NLS-1$
                            scriptFile.getAbsolutePath() + "#" + // $NON-NLS-1$
                            scriptFile.lastModified();
                    CompiledScript compiledScript = compiledScriptsCache.get(cacheKey);
                    if (compiledScript == null) {
                        synchronized (compiledScriptsCache) {
                            compiledScript = compiledScriptsCache.get(cacheKey);
                            if (compiledScript == null) {
                                // TODO Charset ?
                                fileReader = new BufferedReader(new FileReader(scriptFile),
                                        (int) scriptFile.length());
                                compiledScript = ((Compilable) scriptEngine).compile(fileReader);
                                compiledScriptsCache.put(cacheKey, compiledScript);
                            }
                        }
                    }
                    return compiledScript.eval(bindings);
                } else {
                    // TODO Charset ?
                    fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length());
                    return scriptEngine.eval(fileReader, bindings);
                }
            } finally {
                IOUtils.closeQuietly(fileReader);
            }
        } else {
            throw new ScriptException("Script file '" + scriptFile.getAbsolutePath()
                    + "' does not exist or is unreadable for element:" + getName());
        }
    } else if (!StringUtils.isEmpty(getScript())) {
        if (supportsCompilable && !StringUtils.isEmpty(cacheKey)) {
            computeScriptMD5();
            CompiledScript compiledScript = compiledScriptsCache.get(this.scriptMd5);
            if (compiledScript == null) {
                synchronized (compiledScriptsCache) {
                    compiledScript = compiledScriptsCache.get(this.scriptMd5);
                    if (compiledScript == null) {
                        compiledScript = ((Compilable) scriptEngine).compile(getScript());
                        compiledScriptsCache.put(this.scriptMd5, compiledScript);
                    }
                }
            }

            return compiledScript.eval(bindings);
        } else {
            return scriptEngine.eval(getScript(), bindings);
        }
    } else {
        throw new ScriptException("Both script file and script text are empty for element:" + getName());
    }
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldDoSomeGremlin() throws Exception {
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    final List list = new ArrayList();
    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId("marko"));
    bindings.put("temp", list);
    assertEquals(list.size(), 0);/*from w  w w .j av  a2  s.c  o  m*/
    engine.eval("g.V(marko).out().fill(temp)", bindings);
    assertEquals(list.size(), 3);
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.CLASSIC)
public void shouldProperlyHandleBindings() throws Exception {
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.put("g", g);
    engine.put("marko", convertToVertexId("marko"));
    Assert.assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()"));

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("s", "marko");
    bindings.put("f", 0.5f);
    bindings.put("i", 1);
    bindings.put("b", true);
    bindings.put("l", 100l);
    bindings.put("d", 1.55555d);

    assertEquals(engine.eval("g.E().has('weight',f).next()", bindings),
            g.E(convertToEdgeId("marko", "knows", "vadas")).next());
    assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next());
    assertEquals(engine.eval(/*from   www.j a v a  2 s . c  om*/
            "g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()",
            bindings), g.V(convertToVertexId("marko")).next());
    assertEquals(engine.eval(
            "g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()",
            bindings), g.V(convertToVertexId("marko")).next());
    assertEquals(engine.eval(
            "g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()",
            bindings), g.V(convertToVertexId("marko")).next());
    assertEquals(engine.eval(
            "g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()",
            bindings), g.V(convertToVertexId("marko")).next());
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldClearBindingsBetweenEvals() throws Exception {
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.put("g", g);
    engine.put("marko", convertToVertexId("marko"));
    assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()"));

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("s", "marko");

    assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next());

    try {// ww  w .j  a v a  2s  .c o  m
        engine.eval("g.V().has('name',s).next()");
        fail("This should have failed because s is no longer bound");
    } catch (Exception ex) {
        final Throwable t = ExceptionUtils.getRootCause(ex);
        assertEquals(MissingPropertyException.class, t.getClass());
        assertTrue(t.getMessage().startsWith("No such property: s for class"));
    }

}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldBeThreadSafe() throws Exception {
    final ScriptEngine engine = new GremlinGroovyScriptEngine();

    int runs = 500;
    final CountDownLatch latch = new CountDownLatch(runs);
    final List<String> names = Arrays.asList("marko", "peter", "josh", "vadas", "stephen", "pavel", "matthias");
    final Random random = new Random();

    for (int i = 0; i < runs; i++) {
        new Thread("test-thread-safe-" + i) {
            public void run() {
                String name = names.get(random.nextInt(names.size() - 1));
                try {
                    final Bindings bindings = engine.createBindings();
                    bindings.put("g", g);
                    bindings.put("name", name);
                    final Object result = engine
                            .eval("t = g.V().has('name',name); if(t.hasNext()) { t } else { null }", bindings);
                    if (name.equals("stephen") || name.equals("pavel") || name.equals("matthias"))
                        assertNull(result);
                    else
                        assertNotNull(result);
                } catch (ScriptException e) {
                    assertFalse(true);//from  www  .  ja  v a 2  s . c om
                } finally {
                    if (graph.features().graph().supportsTransactions())
                        g.tx().rollback();
                }
                latch.countDown();
            }
        }.start();
    }
    latch.await();
}