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) throws ScriptException;

Source Link

Document

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

Usage

From source file:org.wso2.carbon.event.template.manager.core.internal.util.TemplateManagerHelper.java

/**
 * This method searches for expressions matching {@link TemplateManagerConstants#TEMPLATE_SCRIPT_REGEX}, evaluate them and
 * replace them by the result of those expressions. If user make any syntax errors in expression and if it does
 * not match with REGEX pattern, they will not be considered as an expression to evaluate.
 * For example, ${toID('My Temperature')} will execute the 'toID' method and replace the value.
 * ${toID('My Temperature)} will not be considered as an expression since the closing single quote is missing.
 *
 * @param content      actual template content to be checked
 * @param scriptEngine JavaScript engine with pre-loaded scripts
 * @return updated content/*from  ww  w. j  av a 2  s .  c o  m*/
 * @throws TemplateDeploymentException if there are any errors in JavaScript function evaluation
 */
private static String replaceScriptExpressions(String content, ScriptEngine scriptEngine)
        throws TemplateDeploymentException {
    StringBuffer buffer = new StringBuffer();
    Pattern pattern = Pattern.compile(TemplateManagerConstants.TEMPLATE_SCRIPT_REGEX);
    Matcher matcher = pattern.matcher(content);
    final int scriptEvaluatorPrefixLength = TemplateManagerConstants.SCRIPT_EVALUATOR_PREFIX.length();
    final int scriptEvaluatorSuffixLength = TemplateManagerConstants.SCRIPT_EVALUATOR_SUFFIX.length();
    if (scriptEngine == null && matcher.find()) { // Do not alter the order of conditions
        // If script engine is not available and at lest one function call is used, throw the exception
        throw new TemplateDeploymentException(
                "JavaScript engine is not available in the current JRE to evaluate the function calls given in the template.");
    }
    while (matcher.find()) {
        String expression = matcher.group();
        int expressionLength = expression.length();
        String scriptToEvaluate = expression.substring(scriptEvaluatorPrefixLength,
                expressionLength - scriptEvaluatorSuffixLength);
        String result = ""; // Empty string, if there is no output
        try {
            Object output = scriptEngine.eval(scriptToEvaluate);
            if (output != null) {
                result = output.toString();
            }
        } catch (ScriptException e) {
            throw new TemplateDeploymentException("Error in evaluating JavaScript expression: " + expression,
                    e);
        }
        matcher.appendReplacement(buffer, result);
    }
    matcher.appendTail(buffer); // Append the remaining text

    return buffer.toString();
}

From source file:io.stallion.tools.ScriptExecBase.java

public void executeJavascript(String source, URL url, String scriptPath, String folder, List<String> args,
        String plugin) throws Exception {
    ScriptEngine scriptEngine = null;
    if (plugin.equals("js") || plugin.equals("stallion")) {
        JsPluginEngine pluginEngine = PluginRegistry.instance().getEngine("main.js");
        if (pluginEngine != null) {
            scriptEngine = pluginEngine.getScriptEngine();
        }/*from   w w  w. j  a v a2  s .c  o m*/
    } else if (!empty(plugin)) {
        JsPluginEngine pluginEngine = PluginRegistry.instance().getEngine(plugin);
        if (pluginEngine != null) {
            scriptEngine = pluginEngine.getScriptEngine();
        }
    }
    if (scriptEngine == null) {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        scriptEngine = scriptEngineManager.getEngineByName("nashorn");
        scriptEngine.eval(IOUtils.toString(getClass().getResource("/jslib/jvm-npm.js"), UTF8));
        scriptEngine.eval(IOUtils.toString(getClass().getResource("/jslib/stallion_shared.js"), UTF8));
        String nodePath = folder + "/node_modules";
        scriptEngine.eval("require.NODE_PATH = \"" + nodePath + "\"");
        scriptEngine.put("myContext",
                new SandboxedContext(plugin, Sandbox.allPermissions(), new JsPluginSettings()));
    }
    if (true || newCommandOptions().isDevMode()) {
        Scanner in = new Scanner(System.in);
        while (true) {
            source = IOUtils.toString(url, UTF8);
            try {
                scriptEngine.eval("load("
                        + JSON.stringify(map(val("script", source), val("name", url.toString()))) + ");");
                //scriptEngine.eval(IOUtils.)
            } catch (Exception e) {
                ExceptionUtils.printRootCauseStackTrace(e);
            } finally {

            }
            System.out.println("Hit enter to re-run the script. Type quit and hit enter to stop.");
            String line = in.nextLine().trim();
            if (empty(line)) {
                continue;
            } else {
                break;
            }
        }
    } else {
        scriptEngine.eval(source);
    }

}

From source file:com.mgmtp.jfunk.core.scripting.ScriptExecutor.java

/**
 * Executes the specified Groovy script.
 *
 * @param script/*www .  j  a va2  s  . c  o  m*/
 *            the script file
 * @param scriptProperties
 *            properties that are set to the script engine's binding and thus will be available
 *            as variables in the Groovy script
 * @return the execution result, {@code true} if successful, {@code false} code
 */
public boolean executeScript(final File script, final Properties scriptProperties) {
    checkState(script.exists(), "Script file does not exist: %s", script);
    checkState(script.canRead(), "Script file is not readable: %s", script);

    Reader reader = null;
    boolean success = false;
    Throwable throwable = null;

    scriptScope.enterScope();
    ScriptContext ctx = scriptContextProvider.get();
    try {
        reader = Files.newReader(script, charset);

        ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("groovy");
        ctx.setScript(script);
        ctx.load(JFunkConstants.SCRIPT_PROPERTIES, false);
        ctx.registerReporter(new SimpleReporter());
        initGroovyCommands(scriptEngine, ctx);
        initScriptProperties(scriptEngine, scriptProperties);
        ScriptMetaData scriptMetaData = scriptMetaDataProvider.get();
        scriptMetaData.setScriptName(script.getPath());

        Date startDate = new Date();
        scriptMetaData.setStartDate(startDate);
        ctx.set(JFunkConstants.SCRIPT_START_MILLIS, String.valueOf(startDate.getTime()));

        eventBus.post(scriptEngine);
        eventBus.post(new BeforeScriptEvent(script.getAbsolutePath()));
        scriptEngine.eval(reader);
        success = true;
    } catch (IOException ex) {
        throwable = ex;
        log.error("Error loading script: " + script, ex);
    } catch (ScriptException ex) {
        throwable = ex;

        // Look up the cause hierarchy if we find a ModuleExecutionException.
        // We only need to log exceptions other than ModuleExecutionException because they
        // have already been logged and we don't want to pollute the log file any further.
        // In fact, other exception cannot normally happen.
        Throwable th = ex;
        while (!(th instanceof ModuleExecutionException)) {
            if (th == null) {
                // log original exception
                log.error("Error executing script: " + script, ex);
                success = false;
                break;
            }
            th = th.getCause();
        }
    } finally {
        try {
            ScriptMetaData scriptMetaData = scriptMetaDataProvider.get();

            Date endDate = new Date();
            scriptMetaData.setEndDate(endDate);
            ctx.set(JFunkConstants.SCRIPT_END_MILLIS, String.valueOf(endDate.getTime()));

            scriptMetaData.setThrowable(throwable);
            eventBus.post(new AfterScriptEvent(script.getAbsolutePath(), success));
        } finally {
            scriptScope.exitScope();
            closeQuietly(reader);
        }
    }

    return success;
}

From source file:nz.net.orcon.kanban.automation.plugin.ScriptPlugin.java

@Override
public Map<String, Object> process(Action action, Map<String, Object> context) throws Exception {

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");

    for (Entry<String, Object> entry : context.entrySet()) {
        if (StringUtils.isNotBlank(entry.getKey())) {
            engine.put(entry.getKey(), entry.getValue());
        }//from w w  w.  j av a2  s  .c o m
    }

    if (action.getProperties() != null) {
        for (Entry<String, String> entry : action.getProperties().entrySet()) {
            if (StringUtils.isNotBlank(entry.getKey())) {
                engine.put(entry.getKey(), entry.getValue());
            }
        }
    }

    engine.put("lists", listController);
    engine.put("log", log);

    String script = null;
    if (StringUtils.isNotBlank(action.getResource())) {
        script = resourceController.getResource((String) context.get("boardid"), action.getResource());
    } else {
        script = action.getMethod();
    }

    engine.eval(script);
    Bindings resultBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    for (Entry<String, Object> entry : resultBindings.entrySet()) {
        if (entry.getKey().equals("context") || entry.getKey().equals("print")
                || entry.getKey().equals("println")) {
            continue;
        }
        context.put(entry.getKey(), entry.getValue());
    }
    return context;
}

From source file:org.pentaho.js.require.RequireJsGenerator.java

private void requirejsFromJs(String moduleName, String moduleVersion, String jsScript)
        throws IOException, ScriptException, NoSuchMethodException, ParseException {
    moduleInfo = new ModuleInfo(moduleName, moduleVersion);

    Pattern pat = Pattern.compile("webjars!(.*).js");
    Matcher m = pat.matcher(jsScript);

    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, m.group(1));
    }//from  w w w  . j  ava 2s  . c  o  m
    m.appendTail(sb);

    jsScript = sb.toString();

    pat = Pattern.compile("webjars\\.path\\(['\"]{1}(.*)['\"]{1}, (['\"]{0,1}[^\\)]+['\"]{0,1})\\)");
    m = pat.matcher(jsScript);
    while (m.find()) {
        m.appendReplacement(sb, m.group(2));
    }
    m.appendTail(sb);

    jsScript = sb.toString();

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    String script = IOUtils
            .toString(getClass().getResourceAsStream("/org/pentaho/js/require/require-js-aggregator.js"));
    script = script.replace("{{EXTERNAL_CONFIG}}", jsScript);

    engine.eval(script);

    requireConfig = (Map<String, Object>) parser
            .parse(((Invocable) engine).invokeFunction("processConfig", "").toString());
}

From source file:com.willwinder.universalgcodesender.model.GUIBackend.java

@Override
public void setWorkPositionUsingExpression(final Axis axis, final String expression) throws Exception {
    String expr = StringUtils.trimToEmpty(expression);
    expr = expr.replaceAll("#", String.valueOf(getWorkPosition().get(axis)));

    // If the expression starts with a mathimatical operation add the original position
    if (StringUtils.startsWithAny(expr, "/", "*")) {
        double value = getWorkPosition().get(axis);
        expr = value + " " + expr;
    }//  w  w w  .  j  av  a2s .c o  m

    // Start a script engine and evaluate the expression
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    try {
        double position = Double.valueOf(engine.eval(expr).toString());
        setWorkPosition(axis, position);
    } catch (ScriptException e) {
        throw new Exception("Invalid expression", e);
    }
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSParser.java

private ScriptEngine createEngine() {
    CompiledScript cscript;/*from ww  w  .  ja  va 2  s .c  o  m*/
    Bindings bindings;
    ScriptEngine scriptEngine = new NashornScriptEngineFactory().getScriptEngine("--language=es6");//engine = new ScriptEngineManager().getEngineByName("nashorn");
    try {
        try {
            if (base == null) {
                base = IOUtils.toString(EJSParser.class.getClassLoader()
                        .getResourceAsStream("io/github/jeddict/jcode/parser/ejs/resources/base.js"), "UTF-8");
            }
            if (ejs == null) {
                ejs = IOUtils.toString(EJSParser.class.getClassLoader()
                        .getResourceAsStream("io/github/jeddict/jcode/parser/ejs/resources/ejs.js"), "UTF-8");
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }

        scriptEngine.eval(base);
        Compilable compilingEngine = (Compilable) scriptEngine;
        cscript = compilingEngine.compile(ejs);
        bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        cscript.eval(bindings);
        scriptEngine.eval(scripts.toString());

        for (Map<String, Object> context : contexts) {
            context.keySet().stream().forEach((key) -> {
                try {
                    bindings.put(key, context.get(key));
                    if (context.get(key) instanceof Collection) {
                        scriptEngine.eval(String.format("%s = Java.from(%s);", key, key));
                    }
                } catch (ScriptException ex) {
                    Exceptions.printStackTrace(ex);
                }
            });
        }

    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }
    return scriptEngine;
}

From source file:org.elasticsearch.river.jolokia.strategy.simple.SimpleRiverSource.java

public void fetch(String hostname) {
    String url = "?";
    String objectName = "?";
    String[] attributeNames = new String[] {};
    try {//from   w ww.  j av a2 s .  c o  m
        String catalogue = getCatalogue(hostname);
        String host = getHost(hostname);
        String port = getPort(hostname);
        String userName = getUser(hostname);
        String password = getPassword(hostname);
        url = getUrl((null == port ? host : (host + ":" + port)) + catalogue);
        objectName = setting.getObjectName();
        Map<String, String> transforms = getAttributeTransforms();

        attributeNames = getAttributeNames();

        J4pClient j4pClient = useBasicAuth(userName, password)
                ? J4pClient.url(url).user(userName).password(password).build()
                : J4pClient.url(url).build();

        J4pReadRequest req = new J4pReadRequest(objectName, attributeNames);

        logger.info("Executing {}, {}, {}", url, objectName, attributeNames);
        J4pReadResponse resp = j4pClient.execute(req);

        if (setting.getOnlyUpdates() && null != resp.asJSONObject().get("value")) {
            Integer oldValue = setting.getLastValueAsHash();
            setting.setLastValueAsHash(resp.asJSONObject().get("value").toString().hashCode());
            if (null != oldValue && oldValue.equals(setting.getLastValueAsHash())) {
                logger.info("Skipping " + objectName + " since no values has changed");
                return;
            }
        }

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("rhino");

        for (ObjectName object : resp.getObjectNames()) {
            StructuredObject reading = createReading(host, catalogue, getObjectName(object));
            for (String attrib : attributeNames) {
                try {
                    Object v = resp.getValue(object, attrib);

                    // Transform
                    if (transforms.containsKey(attrib)) {
                        String function = transforms.get(attrib)
                                .replaceFirst("^\\s*function\\s+([^\\s\\(]+)\\s*\\(.*$", "$1");
                        engine.eval(transforms.get(attrib));
                        v = convert(engine.eval(function + "(" + JSONValue.toJSONString(v) + ")"));
                    }

                    reading.source(setting.getPrefix() + attrib, v);
                } catch (Exception e) {
                    reading.source(ERROR_PREFIX + setting.getPrefix() + attrib, e.getMessage());
                }
            }
            createReading(reading);
        }
    } catch (Exception e) {
        try {
            logger.info("Failed to execute request {} {} {}", url, objectName, attributeNames, e);
            StructuredObject reading = createReading(getHost(hostname), getCatalogue(hostname),
                    setting.getObjectName());
            reading.source(ERROR_TYPE, e.getClass().getName());
            reading.source(ERROR, e.getMessage());
            int rc = HttpStatus.SC_INTERNAL_SERVER_ERROR;
            if (e instanceof J4pRemoteException) {
                rc = ((J4pRemoteException) e).getStatus();
            }
            reading.source(RESPONSE, rc);
            createReading(reading);
        } catch (Exception e1) {
            logger.error("Failed to store error message", e1);
        }
    }
}

From source file:com.cubeia.ProtocolGeneratorMojo.java

private void generateCode(String lang, File protocolFile, File outputBaseDirectory, String packageName,
        boolean generateVisitors, String version, boolean failOnBadPacketOrder, String javascript_package_name)
        throws MojoExecutionException, MojoFailureException {

    if (append_language_to_output_base_dir) {
        outputBaseDirectory = appendLangToBaseDir(lang, outputBaseDirectory);
        getLog().info("Appended language '" + lang + "' to base dir, new base dir: " + outputBaseDirectory);
    }//from   w  w  w  .  j a  v  a 2  s  .com

    ScriptEngineManager factory = new ScriptEngineManager();

    // Create a JRuby engine.
    ScriptEngine engine = factory.getEngineByName("jruby");

    // Evaluate JRuby code from string.
    InputStream scriptIn = getClass().getResourceAsStream(GENERATOR_WRAPPER_SCRIPT);
    if (scriptIn == null) {
        new MojoExecutionException(
                "unable to find code generator script resource: " + GENERATOR_WRAPPER_SCRIPT);
    }

    Object[] args = new Object[] { protocolFile.getPath(), lang, outputBaseDirectory.getPath(), packageName,
            generateVisitors ? "true" : null, version, failOnBadPacketOrder ? "true" : null,
            javascript_package_name };

    InputStreamReader scriptReader = new InputStreamReader(scriptIn);

    try {
        engine.eval(scriptReader);
        Invocable invocableEngine = (Invocable) engine;
        invocableEngine.invokeFunction("generate_code", args);
    } catch (ScriptException e) {
        throw new MojoFailureException("code generation error: " + e.toString());
    } catch (NoSuchMethodException e) {
        throw new MojoExecutionException("error calling code generator script: " + e.getMessage());
    }
}

From source file:com.amalto.core.util.Util.java

public static IWhereItem fixWebConditions(IWhereItem whereItem, String userXML) throws Exception {
    if (whereItem == null) {
        return null;
    }/*from   ww  w.  jav a2s  .c  om*/
    if (whereItem instanceof WhereLogicOperator) {
        List<IWhereItem> subItems = ((WhereLogicOperator) whereItem).getItems();
        for (int i = subItems.size() - 1; i >= 0; i--) {
            IWhereItem item = subItems.get(i);
            item = fixWebConditions(item, userXML);
            if (item instanceof WhereLogicOperator) {
                if (((WhereLogicOperator) item).getItems().size() == 0) {
                    subItems.remove(i);
                }
            } else if (item instanceof WhereCondition) {
                WhereCondition condition = (WhereCondition) item;
                if (condition.getRightValueOrPath() != null && condition.getRightValueOrPath().length() > 0
                        && condition.getRightValueOrPath().contains(USER_PROPERTY_PREFIX)) {
                    subItems.remove(i);
                }
            } else if (item == null) {
                subItems.remove(i);
            }
        }
    } else if (whereItem instanceof WhereCondition) {
        WhereCondition condition = (WhereCondition) whereItem;
        if (condition.getRightValueOrPath() != null && condition.getRightValueOrPath().length() > 0
                && condition.getRightValueOrPath().contains(USER_PROPERTY_PREFIX)) {
            // TMDM-7207: Only create the groovy script engine if needed (huge performance issues)
            // TODO Should there be some pool of ScriptEngine instances? (is reusing ok?)
            ScriptEngine scriptEngine = SCRIPT_FACTORY.getEngineByName("groovy"); //$NON-NLS-1$
            if (userXML != null && !userXML.isEmpty()) {
                User user = User.parse(userXML);
                scriptEngine.put("user_context", user);//$NON-NLS-1$
            }
            String rightCondition = condition.getRightValueOrPath();
            String userExpression = rightCondition.substring(rightCondition.indexOf('{') + 1,
                    rightCondition.indexOf('}'));
            try {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Groovy engine evaluating " + userExpression + ".");//$NON-NLS-1$ //$NON-NLS-2$
                }
                Object expressionValue = scriptEngine.eval(userExpression);
                if (expressionValue != null) {
                    String result = String.valueOf(expressionValue);
                    if (!"".equals(result.trim())) {
                        condition.setRightValueOrPath(result);
                    }
                }
            } catch (Exception e) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("No such property " + userExpression, e);
                }
            }
        }

        if (!condition.getOperator().equals(WhereCondition.EMPTY_NULL)) {
            whereItem = "*".equals(condition.getRightValueOrPath()) //$NON-NLS-1$
                    || ".*".equals(condition.getRightValueOrPath()) ? null : whereItem;
        }
    } else {
        throw new XmlServerException("Unknown Where Type : " + whereItem.getClass().getName());
    }
    if (whereItem instanceof WhereLogicOperator) {
        return ((WhereLogicOperator) whereItem).getItems().size() == 0 ? null : whereItem;
    }
    return whereItem;
}