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:org.nuxeo.runtime.scripting.ScriptingComponent.java

@Override
public Object eval(String path, ScriptContext ctx) throws ScriptException {
    ScriptEngine engine = getEngineByFileName(path);
    if (engine != null) {
        try {//  w  w w  .  j  a  v  a  2 s .c  o  m
            Reader reader = new FileReader(getScriptFile(path));
            try {
                return engine.eval(reader, ctx);
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    } else {
        throw new ScriptException("No script engine was found for the file: " + path);
    }
}

From source file:com.intuit.tank.tools.script.ScriptRunner.java

/**
 * /*from  w  w  w . jav a 2s.c  o  m*/
 * @param scriptName
 * @param script
 * @param engine
 * @param inputs
 * @param output
 * @return
 * @throws ScriptException
 */
public ScriptIOBean runScript(@Nullable String scriptName, @Nonnull String script, @Nonnull ScriptEngine engine,
        @Nonnull Map<String, Object> inputs, OutputLogger output) throws ScriptException {
    Reader reader = null;
    ScriptIOBean ioBean = null;
    try {
        reader = new StringReader(script);
        ioBean = new ScriptIOBean(inputs, output);
        engine.put("ioBean", ioBean);
        ioBean.println("Starting test...");
        engine.eval(reader, engine.getContext());
        ioBean.println("Finished test...");
    } catch (ScriptException e) {
        throw new ScriptException(e.getMessage(), scriptName, e.getLineNumber(), e.getColumnNumber());
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return ioBean;
}

From source file:org.tomitribe.tribestream.registryng.bootstrap.Provisioning.java

@PostConstruct
public void init() {
    loginContext.setUsername("system");

    ofNullable(script).ifPresent(s -> {
        final ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
        final Bindings bindings = engine.createBindings();
        bindings.put("props", System.getProperties());

        final File file = new File(s);
        if (file.isFile()) {
            try (final Reader reader = new FileReader(file)) {
                engine.eval(reader, bindings);
            } catch (final IOException | ScriptException e) {
                throw new IllegalArgumentException(e);
            }/*from w  w  w.jav a2 s  .  com*/
        } else {
            try {
                engine.eval(s, bindings);
            } catch (final ScriptException e) {
                throw new IllegalArgumentException(e);
            }
        }
    });
    restore();
}

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

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    if (StringUtils.isEmpty(previousOut)) {
        return previousOut;
    }// ww w.  j  a  v a  2 s.  c om
    long timer = System.currentTimeMillis();
    boolean evaluated = false;

    Matcher matcher = macrosPattern.matcher(previousOut);
    while (matcher.find()) {
        evaluated = true;
        String macroName = matcher.group(1);
        String[] macro = getMacro(macroName);
        if (macro != null) {
            try {
                // execute macro
                ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(macro[1]);
                ScriptContext scriptContext = scriptEngine.getContext();
                scriptContext.setWriter(new StringWriter());
                scriptContext.setErrorWriter(new StringWriter());
                scriptEngine.eval(macro[0], getBindings(renderContext, resource, scriptContext, matcher));
                String scriptResult = scriptContext.getWriter().toString().trim();
                previousOut = matcher.replaceFirst(scriptResult);
            } catch (ScriptException e) {
                logger.warn("Error during execution of macro " + macroName + " with message " + e.getMessage(),
                        e);
                previousOut = matcher.replaceFirst(macroName);
            }
            matcher = macrosPattern.matcher(previousOut);
        } else if (replaceByErrorMessageOnMissingMacros) {
            previousOut = matcher.replaceFirst("macro " + macroName + " not found");
            logger.warn("Unknown macro '{}'", macroName);
            matcher = macrosPattern.matcher(previousOut);
        }
    }

    if (evaluated && logger.isDebugEnabled()) {
        logger.debug("Evaluation of macros took {} ms", (System.currentTimeMillis() - timer));
    }
    return previousOut;
}

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;//  ww  w.  j  a  v  a 2  s  . co  m
    // 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;
}

From source file:org.apache.felix.webconsole.plugins.scriptconsole.internal.ScriptConsolePlugin.java

private void eval(String script, String lang, ScriptContext ctx) throws ScriptException, IOException {
    ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension(lang);
    if (scriptEngine == null) {
        throw new IllegalArgumentException("No ScriptEngineFactory found for extension " + lang);
    }//from   w w w.  ja  v a 2 s. c  o m

    // evaluate the script
    //Currently we do not make use of returned object
    final Object result = scriptEngine.eval(script, ctx);

    // allways flush the error channel
    ctx.getErrorWriter().flush();

}

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

private String evaluate(String subject, JCRNodeWrapper document) {
    if (subject.contains("${")) {
        try {/*from   w w  w  .  j ava  2  s .c o 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.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);//ww  w  .j av a 2 s  .c  o m
    engine.eval("g.V(marko).out().fill(temp)", bindings);
    assertEquals(list.size(), 3);
}

From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java

private void executeScript(Map<String, Object> beans, URL script) throws ScriptException, IOException {
    if (log.isInfoEnabled()) {
        log.info("Executing script " + script);
    }/*  w w w.  j  a va  2  s.co m*/

    if (script.getPath().endsWith(".js")) {
        ScriptContext context = new SimpleScriptContext();
        ScriptEngine engine = buildEngine(beans, script, context);
        InputStream openStream = script.openStream();
        if (openStream == null) {
            throw new FileNotFoundException("Could not locate resource " + script);
        }
        Reader in = new InputStreamReader(openStream);
        try {
            engine.eval(in, context);
        } finally {
            in.close();
        }
    } else if (script.getPath().endsWith(".class")) {
        String path = script.getPath();
        int idx = path.indexOf("upgrade/");
        path = path.substring(idx);
        idx = path.lastIndexOf(".");
        path = path.substring(0, idx).replace("/", ".");
        try {
            @SuppressWarnings("unchecked")
            Class<? extends Runnable> clazz = (Class<? extends Runnable>) getClass().getClassLoader()
                    .loadClass(path);
            Runnable r = clazz.newInstance();
            springContext.getAutowireCapableBeanFactory().autowireBean(r);
            r.run();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {

        BufferedReader r = new BufferedReader(new InputStreamReader(script.openStream()));
        try {
            String statement = "";
            String line;
            boolean ignoreErrors = false;
            while ((line = r.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("EXIT IF FRESH")) {
                    if (isFreshInstall()) {
                        break;
                    }
                    continue;
                }

                if (!line.startsWith("/*") && !line.startsWith("//")) {
                    if (line.endsWith(";")) {
                        line = line.substring(0, line.length() - 1);
                        statement += line;
                        sessionFactory.getCurrentSession().createSQLQuery(statement).executeUpdate();
                        statement = "";
                    } else {
                        statement += line + "\n";
                    }
                }
            }

            if (StringUtils.isNotBlank(statement)) {
                try {
                    sessionFactory.getCurrentSession().createSQLQuery(statement).executeUpdate();
                } catch (Throwable e) {
                    if (!ignoreErrors) {
                        throw e;
                    }
                }
            }
        } finally {
            r.close();
        }
    }

}

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 a2  s . 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;
}