Example usage for javax.script ScriptEngineManager getEngineByName

List of usage examples for javax.script ScriptEngineManager getEngineByName

Introduction

In this page you can find the example usage for javax.script ScriptEngineManager getEngineByName.

Prototype

public ScriptEngine getEngineByName(String shortName) 

Source Link

Document

Looks up and creates a ScriptEngine for a given name.

Usage

From source file:com.espertech.esper.epl.script.jsr223.JSR223Helper.java

public static CompiledScript verifyCompileScript(ExpressionScriptProvided script, String dialect)
        throws ExprValidationException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName(dialect);
    if (engine == null) {
        throw new ExprValidationException("Failed to obtain script engine for dialect '" + dialect
                + "' for script '" + script.getName() + "'");
    }/*from  ww  w.  j av a 2s  .c  o m*/
    engine.put(ScriptEngine.FILENAME, script.getName());

    Compilable compilingEngine = (Compilable) engine;
    try {
        return compilingEngine.compile(script.getExpression());
    } catch (ScriptException ex) {
        String message = "Exception compiling script '" + script.getName() + "' of dialect '" + dialect + "': "
                + getScriptCompileMsg(ex);
        log.info(message, ex);
        throw new ExprValidationException(message, ex);
    }
}

From source file:fr.assoba.open.sel.generator.LanguageExecutor.java

public static void execute(List<Namespace> namespaceList, IO io, String... languages)
        throws IOException, ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine jsEngine = factory.getEngineByName("JavaScript");
    jsEngine.put("IO", io);
    jsEngine.eval(io.readFile("underscore.js"));
    jsEngine.eval(io.readFile("handlebars-v1.3.0.js"));
    ObjectMapper mapper = new ObjectMapper();
    jsEngine.eval("namespaces=" + mapper.writeValueAsString(namespaceList));
    for (String lang : languages) {
        if (generatorMap.containsKey(lang)) {
            generatorMap.get(lang).generate(namespaceList, io);
        } else {/*  ww w  .  j a  v a 2 s .  c  o  m*/
            jsEngine.eval(io.readFile(lang + ".js"));
        }
    }
}

From source file:com.intbit.util.ServletUtil.java

public static String getServerName(ServletContext context) {
    try {//from  w ww  .  j  a  v  a  2 s.  c  o  m
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        String path = context.getRealPath("") + "/js/configurations.js";
        // read script file
        engine.eval(Files.newBufferedReader(Paths.get(path), StandardCharsets.UTF_8));

        Invocable inv = (Invocable) engine;
        // call function from script file
        return inv.invokeFunction("getHost", "").toString();
    } catch (Exception ex) {
        return "http://clients.brndbot.com/BrndBot/";
    }
}

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

private static ScriptEngine findScriptEngine(String scriptEngineName) {
    final ScriptEngineManager manager = getScriptEngineManager();
    return checkNotNull(manager.getEngineByName(scriptEngineName), "name", scriptEngineName);
}

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  a2s  . c  o  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.jumpmind.metl.core.runtime.component.ModelAttributeScriptHelper.java

public static Object eval(Message message, ComponentContext context, ModelAttribute attribute, Object value,
        ModelEntity entity, EntityData data, String expression) {
    ScriptEngine engine = scriptEngine.get();
    if (engine == null) {
        ScriptEngineManager factory = new ScriptEngineManager();
        engine = factory.getEngineByName("groovy");
        scriptEngine.set(engine);/*w  ww  .  j  av a 2 s  . c o m*/
    }
    engine.put("value", value);
    engine.put("data", data);
    engine.put("entity", entity);
    engine.put("attribute", attribute);
    engine.put("message", message);
    engine.put("context", context);

    try {
        String importString = "import org.jumpmind.metl.core.runtime.component.ModelAttributeScriptHelper;\n";
        String code = String.format(
                "return new ModelAttributeScriptHelper(message, context, attribute, entity, data, value) { public Object eval() { return %s } }.eval()",
                expression);
        return engine.eval(importString + code);
    } catch (ScriptException e) {
        throw new RuntimeException("Unable to evaluate groovy script.  Attribute ==> " + attribute.getName()
                + ".  Value ==> " + value.toString() + "." + e.getCause().getMessage(), e);
    }
}

From source file:at.alladin.rmbt.qos.testscript.TestScriptInterpreter.java

/**
 * //from w  w  w.ja  v a  2 s. c o m
 * @param command
 * @return
 */
public static <T> Object interprete(String command, Hstore hstore, AbstractResult<T> object,
        boolean useRecursion, ResultOptions resultOptions) {

    if (jsEngine == null) {
        ScriptEngineManager sem = new ScriptEngineManager();
        jsEngine = sem.getEngineByName("JavaScript");
        System.out.println("JS Engine: " + jsEngine.getClass().getCanonicalName());
        Bindings b = jsEngine.createBindings();
        b.put("nn", new SystemApi());
        jsEngine.setBindings(b, ScriptContext.GLOBAL_SCOPE);
    }

    command = command.replace("\\%", "{PERCENT}");

    Pattern p;
    if (!useRecursion) {
        p = PATTERN_COMMAND;
    } else {
        p = PATTERN_RECURSIVE_COMMAND;

        Matcher m = p.matcher(command);
        while (m.find()) {
            String replace = m.group(0);
            //System.out.println("found: " + replace);
            String toReplace = String.valueOf(interprete(replace, hstore, object, false, resultOptions));
            //System.out.println("replacing: " + m.group(0) + " -> " + toReplace);
            command = command.replace(m.group(0), toReplace);
        }

        command = command.replace("{PERCENT}", "%");
        return command;
    }

    Matcher m = p.matcher(command);
    command = command.replace("{PERCENT}", "%");

    String scriptCommand;
    String[] args;

    if (m.find()) {
        if (m.groupCount() != 2) {
            return command;
        }
        scriptCommand = m.group(1);

        if (!COMMAND_EVAL.equals(scriptCommand)) {
            args = m.group(2).trim().split("\\s");
        } else {
            args = new String[] { m.group(2).trim() };
        }
    } else {
        return command;
    }

    try {
        if (COMMAND_RANDOM.equals(scriptCommand)) {
            return random(args);
        } else if (COMMAND_PARAM.equals(scriptCommand)) {
            return parse(args, hstore, object, resultOptions);
        } else if (COMMAND_EVAL.equals(scriptCommand)) {
            return eval(args, hstore, object);
        } else if (COMMAND_RANDOM_URL.equals(scriptCommand)) {
            return randomUrl(args);
        } else {
            return command;
        }
    } catch (ScriptException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.linkedin.drelephant.util.Utils.java

/**
 * Returns the configured thresholds after evaluating and verifying the levels.
 *
 * @param rawLimits A comma separated string of threshold limits
 * @param thresholdLevels The number of threshold levels
 * @return The evaluated threshold limits
 *//* ww w.  ja va  2s.c  om*/
public static double[] getParam(String rawLimits, int thresholdLevels) {
    double[] parsedLimits = null;

    if (rawLimits != null && !rawLimits.isEmpty()) {
        String[] thresholds = rawLimits.split(",");
        if (thresholds.length != thresholdLevels) {
            logger.error("Could not find " + thresholdLevels + " threshold levels in " + rawLimits);
            parsedLimits = null;
        } else {
            // Evaluate the limits
            parsedLimits = new double[thresholdLevels];
            ScriptEngineManager mgr = new ScriptEngineManager(null);
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
            for (int i = 0; i < thresholdLevels; i++) {
                try {
                    parsedLimits[i] = Double.parseDouble(engine.eval(thresholds[i]).toString());
                } catch (ScriptException e) {
                    logger.error("Could not evaluate " + thresholds[i] + " in " + rawLimits);
                    parsedLimits = null;
                }
            }
        }
    }

    return parsedLimits;
}

From source file:org.wso2.carbon.business.rules.core.util.TemplateManagerHelper.java

/**
 * Runs the script that is given as a string, and gives all the variables specified in the script
 *
 * @param script//from  w  ww.ja va 2 s .co m
 * @return Map of Strings
 * @throws TemplateManagerHelperException
 */
public static Map<String, String> getScriptGeneratedVariables(String script)
        throws RuleTemplateScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    ScriptContext scriptContext = new SimpleScriptContext();
    scriptContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

    try {
        // Run script
        engine.eval(script);
        Map<String, Object> returnedScriptContextBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);

        // Variable names and their values as strings, from the script context binding
        Map<String, String> scriptVariables = new HashMap<>();
        for (Map.Entry scriptVariable : returnedScriptContextBindings.entrySet()) {
            if (scriptVariable.getValue() == null) {
                scriptVariables.put(scriptVariable.getKey().toString(), null);
            } else {
                scriptVariables.put(scriptVariable.getKey().toString(), scriptVariable.getValue().toString());
            }
        }
        return scriptVariables;
    } catch (ScriptException e) {
        throw new RuleTemplateScriptException(e.getCause().getMessage(), e);
    }
}

From source file:com.t_oster.visicut.misc.Helper.java

public static Double evaluateExpression(String expr) {
    expr = expr.replace(",", ".");
    try {/*  w ww . ja v  a2s . co m*/
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        expr = engine.eval(expr).toString();
    } catch (Exception e) {
        //e.printStackTrace();
    }
    return Double.parseDouble(expr);
}