Example usage for javax.script ScriptEngine eval

List of usage examples for javax.script ScriptEngine eval

Introduction

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

Prototype

public Object eval(Reader reader, Bindings n) throws ScriptException;

Source Link

Document

Same as eval(String, Bindings) except that the source of the script is provided as a Reader.

Usage

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java

public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException {
    if (engine instanceof Compilable && ATTEMPT_COMPILATION) {
        Compilable eng = (Compilable) engine;
        CompiledScript cs = eng.compile(script);
        return context != null ? cs.eval(context) : cs.eval();
    }//from  www . jav  a  2s . c  o  m

    return context != null ? engine.eval(script, context) : engine.eval(script);
}

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;// w  ww  .j a va  2  s .  co  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.jtotus.network.NordnetConnect.java

public String fetchEncryptedPassword(String encryptJS, String pass, String pubKey, String sessionId) {
    String password = null;/*w w w.ja  v  a  2 s .c o  m*/

    StartUpLoader loader = StartUpLoader.getInstance();

    //ScriptEngineManager mgr = loader.getLoadedScriptManager();
    //         Bindings bindings = mgr.getBindings();

    ScriptEngine engine = loader.getLoadedEngine();
    Bindings bindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE);

    try {
        StringBuilder strBuild = new StringBuilder();
        strBuild.append(encryptJS);

        strBuild.append(" \n var keyObj = RSA.getPublicKey(\'" + pubKey + "\');\n"
                + "  var encryptedPass = RSA.encrypt(\'" + pass + "\', keyObj, \'" + sessionId + "\');\n");

        engine.eval(strBuild.toString(), bindings);

        password = (String) bindings.get("encryptedPass");

    } catch (ScriptException ex) {
        Logger.getLogger(NordnetConnector.class.getName()).log(Level.SEVERE, null, ex);
    }

    log.info("JavaScript engine loaded:" + engine.NAME);

    return password;
}

From source file:org.nuxeo.ecm.webengine.scripting.Scripting.java

protected Object _runScript(ScriptFile script, Map<String, Object> args) throws Exception {
    SimpleBindings bindings = new SimpleBindings();
    if (args != null) {
        bindings.putAll(args);/*from   w w w . ja  v a 2  s.  c om*/
    }
    String ext = script.getExtension();
    // check for a script engine
    ScriptEngine engine = getEngineManager().getEngineByExtension(ext);
    if (engine != null) {
        ScriptContext ctx = new SimpleScriptContext();
        ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        CompiledScript comp = getCompiledScript(engine, script.getFile()); // use cache for compiled scripts
        if (comp != null) {
            return comp.eval(ctx);
        } // compilation not supported - eval it on the fly
        try {
            Reader reader = new FileReader(script.getFile());
            try { // TODO use __result__ to pass return value for engine that doesn't returns like jython
                Object result = engine.eval(reader, ctx);
                if (result == null) {
                    result = bindings.get("__result__");
                }
                return result;
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    }
    return null;
}

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

/**
 * Initialize the instance./* ww w. jav  a 2s. c o  m*/
 * 
 * @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:org.archive.crawler.framework.ActionDirectory.java

/**
 * Try the actionFile as a script, deducing the proper scripting
 * language from its file extension. Return true if evaluation was
 * tried with a known script engine. /* w ww  . j  a v  a  2s  .  c om*/
 * 
 * Provides 'appCtx' and 'rawOut' to script for accessing crawl
 * and outputting text to a '.out' file paired with the 'done/' 
 * action file. If an exception occurs, it will be logged to an
 * '.ex' file alongside the script file in 'done/'. 
 * 
 * @param actionFile file to try
 * @param timestamp timestamp correlating out/ex files with done script
 * @return true if engine evaluation began (even if an error occurred)
 */
protected boolean tryAsScript(File actionFile, String timestamp) {
    int i = actionFile.getName().lastIndexOf(".");
    if (i < 0) {
        return false;
    }

    // deduce language/engine from extension
    String extension = actionFile.getName().substring(i + 1);
    ScriptEngine engine = MANAGER.getEngineByExtension(extension);
    if (engine == null) {
        return false;
    }

    // prepare engine
    StringWriter rawString = new StringWriter();
    PrintWriter rawOut = new PrintWriter(rawString);
    Exception ex = null;
    Bindings bindings = new BeanLookupBindings(appCtx);
    bindings.put("rawOut", rawOut);
    bindings.put("appCtx", appCtx);

    // evaluate and record any exception
    try {
        String script = FileUtils.readFileToString(actionFile);
        engine.eval(script, bindings);
    } catch (IOException e) {
        ex = e;
    } catch (ScriptException e) {
        ex = e;
    } catch (RuntimeException e) {
        ex = e;
    } finally {
        // the script could create an object that persists and retains a reference to the Bindings
        bindings.put("rawOut", null);
        bindings.put("appCtx", null);
    }

    // report output/exception to files paired with script in done dir
    rawOut.flush();
    String allOut = rawString.toString();
    if (StringUtils.isNotBlank(allOut)) {
        File outFile = new File(doneDir.getFile(), timestamp + "." + actionFile.getName() + ".out");
        try {
            FileUtils.writeStringToFile(outFile, rawString.toString());
        } catch (IOException ioe) {
            LOGGER.log(Level.SEVERE, "problem during action file: " + actionFile, ioe);
        }
    }
    if (ex != null) {
        File exFile = new File(doneDir.getFile(), timestamp + "." + actionFile.getName() + ".exception");
        try {
            FileUtils.writeStringToFile(exFile, ex.toString());
        } catch (IOException ioe) {
            LOGGER.log(Level.SEVERE, "problem during action file: " + actionFile, ioe);
        }
    }

    return true;
}

From source file:org.trafodion.rest.script.ScriptManager.java

public void runScript(ScriptContext ctx) {
    String scriptName;//from   w ww.j  ava 2s.c om

    if (ctx.getScriptName().length() == 0)
        scriptName = DEFAULT_SCRIPT_NAME;
    else if (!ctx.getScriptName().endsWith(".py"))
        scriptName = ctx.getScriptName() + PYTHON_SUFFIX;
    else
        scriptName = ctx.getScriptName();

    try {
        ScriptEngine engine = manager.getEngineByName("python");
        Bindings bindings = engine.createBindings();
        bindings.put("scriptcontext", ctx);
        if (engine instanceof Compilable) {
            CompiledScript script = m.get(scriptName);
            if (script == null) {
                LOG.info("Compiling script " + scriptName);
                Compilable compilingEngine = (Compilable) engine;
                try {
                    script = compilingEngine.compile(new FileReader(restHome + "/bin/scripts/" + scriptName));
                } catch (Exception e) {
                    LOG.warn(e.getMessage());
                }
                m.put(scriptName, script);
            }
            script.eval(bindings);
        } else {
            try {
                engine.eval(new FileReader(restHome + "/bin/scripts/" + scriptName), bindings);
            } catch (Exception e) {
                LOG.warn(e.getMessage());
            }
        }
    } catch (javax.script.ScriptException se) {
        LOG.warn(se.getMessage());
    }
}

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 ww  w. j  av a  2 s. co  m*/
                } finally {
                    if (graph.features().graph().supportsTransactions())
                        g.tx().rollback();
                }
                latch.countDown();
            }
        }.start();
    }
    latch.await();
}

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 ww w  .  ja  v  a 2 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;
}