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: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   ww  w.  j  av  a 2  s  .com*/
    } 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:mrf.Graficar.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    ArrayList<Integer> Datosx = new ArrayList<Integer>();
    ArrayList<Double> Datosy = new ArrayList<Double>();
    int in = Integer.parseInt(jTextField2.getText());
    int sup = Integer.parseInt(jTextField3.getText());
    try {//from   www  .  j ava  2  s .c  om
        XYSeries series = new XYSeries("");
        int inferior = in, superior = sup;
        while (inferior <= superior) {
            Datosx.add(inferior);
            engine.put("X", inferior);
            String a = jTextField1.getText();
            Object operation = engine.eval(a);
            Datosy.add(Double.parseDouble("" + operation));
            jTextArea1.append("Parejas ordenadas " + inferior + ":" + operation + "\n");
            series.add(inferior, Double.parseDouble("" + operation));
            inferior++;
        }

        XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(series);

        JFreeChart chart = ChartFactory.createXYLineChart("Grafica del polinomio ingresado", // Ttulo
                "Eje x", // Etiqueta Coordenada X
                "Eje y", // Etiqueta Coordenada Y
                dataset, // Datos
                PlotOrientation.VERTICAL, true, // Muestra la leyenda de los productos (Producto A)              
                false, false);

        // Mostramos la grafica en pantalla
        ChartFrame frame = new ChartFrame("GRAFICA POLINOMIO", chart);
        frame.pack();
        frame.setVisible(true);

    } catch (ScriptException e) {
        e.printStackTrace();
    }

}

From source file:Engine.Lua.PlayerLua.java

public PlayerLua(String luaFile) {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine scriptEngine = sem.getEngineByName("luaj");
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("Scripts/" + luaFile);
    InputStreamReader isr = new InputStreamReader(is);
    CompiledScript script;/*from w  w w . j  a  v a 2s .com*/
    try {
        script = ((Compilable) scriptEngine).compile(isr);
        isr.close();
        is.close();
        sb = new SimpleBindings();
        script.eval(sb); // Put the Lua functions into the sb environment
    } catch (ScriptException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.jumpmind.metl.core.runtime.component.Transformer.java

@Override
public void handle(Message inputMessage, ISendMessageCallback callback, boolean unitOfWorkBoundaryReached) {
    if (scriptEngine == null) {
        ScriptEngineManager factory = new ScriptEngineManager();
        scriptEngine = factory.getEngineByName("groovy");
    }//from www.ja v  a2s . c om
    totalTime = 0;
    if (inputMessage instanceof EntityDataMessage) {
        Model inputModel = getComponent().getInputModel();
        List<EntityData> inDatas = ((EntityDataMessage) inputMessage).getPayload();
        ArrayList<EntityData> outDatas = new ArrayList<EntityData>(inDatas != null ? inDatas.size() : 0);

        if (inDatas != null) {
            for (EntityData inData : inDatas) {
                EntityData outData = new EntityData();
                outData.setChangeType(inData.getChangeType());
                outDatas.add(outData);

                Set<String> attributeIds = new HashSet<String>();
                Set<ModelEntity> processedEntities = new HashSet<ModelEntity>();
                for (String attributeId : inData.keySet()) {
                    ModelAttribute attribute = inputModel.getAttributeById(attributeId);
                    if (attribute != null) {
                        ModelEntity entity = inputModel.getEntityById(attribute.getEntityId());
                        if (entity != null && !processedEntities.contains(entity)) {
                            List<ModelAttribute> attributes = entity.getModelAttributes();
                            for (ModelAttribute modelAttribute : attributes) {
                                attributeIds.add(modelAttribute.getId());
                            }
                            processedEntities.add(entity);
                        }
                    }
                }

                for (String attributeId : attributeIds) {
                    String transform = transformsByAttributeId.get(attributeId);
                    Object value = inData.get(attributeId);
                    if (isNotBlank(transform)) {
                        ModelAttribute attribute = inputModel.getAttributeById(attributeId);
                        ModelEntity entity = inputModel.getEntityById(attribute.getEntityId());

                        ModelAttributeScriptHelper helper = helpers.get(attribute.getId());
                        if (helper == null) {
                            long ts = System.currentTimeMillis();
                            scriptEngine.put("entity", entity);
                            scriptEngine.put("attribute", attribute);
                            scriptEngine.put("context", context);

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

                            log.debug("It took " + (System.currentTimeMillis() - ts) + "ms to create class");
                        }

                        helper.setData(inData);
                        helper.setValue(value);
                        helper.setMessage(inputMessage);
                        long ts = System.currentTimeMillis();
                        value = helper.eval();
                        totalTime += (System.currentTimeMillis() - ts);
                        totalCalls++;
                    }
                    if (value != ModelAttributeScriptHelper.REMOVE_ATTRIBUTE) {
                        outData.put(attributeId, value);
                    }
                }
                getComponentStatistics().incrementNumberEntitiesProcessed(threadNumber);
            }
        }
        callback.sendEntityDataMessage(null, outDatas);

        if (totalCalls > 0) {
            log.debug("It took " + (totalTime / totalCalls) + "ms on average to call eval");
        }

    } else if (inputMessage instanceof ControlMessage) {
        callback.sendControlMessage();
    }
}

From source file:org.jumpmind.metl.core.runtime.component.Script.java

@Override
protected void start() {
    String importStatements = getComponent().get(IMPORTS);
    String initScript = getComponent().get(INIT_SCRIPT);
    String handleMessageScript = getComponent().get(HANDLE_SCRIPT);
    String methods = getComponent().get(METHODS);
    String onSuccess = getComponent().get(ON_FLOW_SUCCESS);
    String onError = getComponent().get(ON_FLOW_ERROR);

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("groovy");

    engine.put("component", this);
    StringBuilder script = new StringBuilder();
    try {/*from  ww  w.  j  a  v a  2s.  com*/
        script.append(String.format("import %s;\n", ISendMessageCallback.class.getName()));
        script.append(String.format("import %s;\n", File.class.getName()));
        script.append(String.format("import %s;\n", FileUtils.class.getName()));
        script.append(String.format("import static %s.*;\n", FileUtils.class.getName()));
        script.append(String.format("import %s.*;\n", Message.class.getPackage().getName()));
        script.append(String.format("import %s;\n", ScriptHelper.class.getName()));
        script.append(String.format("import %s;\n", EntityDataMessage.class.getName()));
        script.append(String.format("import %s;\n", TextMessage.class.getName()));
        script.append(String.format("import %s;\n", ControlMessage.class.getName()));
        script.append(String.format("import %s;\n", BinaryMessage.class.getName()));
        script.append(String.format("import %s;\n", MisconfiguredException.class.getName()));
        script.append(String.format("import %s;\n", AssertException.class.getName()));
        script.append(
                String.format("import %s.%s;\n", EntityData.class.getName(), ChangeType.class.getSimpleName()));
        script.append("import org.jumpmind.db.sql.*;\n");
        if (isNotBlank(importStatements)) {
            script.append(importStatements);
        }
        script.append("\n");
        script.append(String.format("helper = new %1$s(component) { \n", ScriptHelper.class.getSimpleName()));

        if (isNotBlank(methods)) {
            script.append("\n");
            script.append(String.format("%s\n", methods));
        }

        if (isNotBlank(initScript)) {
            script.append("\n");
            script.append(String.format(" protected void onInit() { %s \n} \n", initScript));
        }
        if (isNotBlank(handleMessageScript)) {
            script.append("\n");
            script.append(String.format(" protected void onHandle() { %s \n} \n", handleMessageScript));
        }
        if (isNotBlank(onSuccess)) {
            script.append("\n");
            script.append(String.format(" protected void onSuccess() { %s \n} \n", onSuccess));
        }
        if (isNotBlank(onError)) {
            script.append("\n");
            script.append(String.format(" protected void onError(Throwable myError) { %s \n} \n", onError));
        }
        script.append("\n};\n");

        log(LogLevel.DEBUG, script.toString());
        script.append("helper.onInit();");
        engine.eval(script.toString());
        this.engine = engine;
    } catch (ScriptException e) {
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause != null) {
            if (rootCause instanceof RuntimeException) {
                throw (RuntimeException) rootCause;
            } else {
                throw new RuntimeException(rootCause);
            }
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.mnxfst.stream.pipeline.element.script.ScriptEvaluatorPipelineElement.java

/**
 * @see akka.actor.UntypedActor#preStart()
 *//*w ww .ja v a 2  s  . co m*/
public void preStart() throws Exception {

    // initialize the script engine 
    ScriptEngineManager factory = new ScriptEngineManager();
    try {
        this.scriptEngine = factory.getEngineByName(getStringProperty(CONFIG_SCRIPT_ENGINE_NAME));
    } catch (Exception e) {
        context().parent()
                .tell(new PipelineElementSetupFailedMessage(getPipelineElementConfiguration().getPipelineId(),
                        getPipelineElementConfiguration().getElementId(),
                        PipelineElementSetupFailedMessage.GENERAL, e.getMessage()), getSelf());
        return;
    }

    // iterate from zero to max, read out init code snippets and interrupt if an empty one occurs
    for (int i = 0; i < Integer.MAX_VALUE; i++) {
        String initScript = getStringProperty(CONFIG_SCRIPT_INIT_CODE_PREFIX + i);
        if (StringUtils.isNotBlank(initScript)) {
            this.initScripts.add(loadScript(initScript.toString()));
        } else {
            break;
        }
    }

    // fetch the script to be applied for each message
    String scriptUrl = getStringProperty(CONFIG_SCRIPT_EVAL_CODE);
    //      this.evalScript = getStringProperty(CONFIG_SCRIPT_EVAL_CODE);
    if (StringUtils.isBlank(scriptUrl)) {
        context().parent()
                .tell(new PipelineElementSetupFailedMessage(getPipelineElementConfiguration().getPipelineId(),
                        getPipelineElementConfiguration().getElementId(),
                        PipelineElementSetupFailedMessage.GENERAL, "Required script code missing"), getSelf());
        return;
    }
    this.evalScript = loadScript(scriptUrl);

    // retrieve the name of the variable where the script expects the input 
    this.scriptInputVariable = getStringProperty(CONFIG_SCRIPT_INPUT_VARIABLE);
    if (StringUtils.isBlank(this.scriptInputVariable)) {
        context().parent()
                .tell(new PipelineElementSetupFailedMessage(getPipelineElementConfiguration().getPipelineId(),
                        getPipelineElementConfiguration().getElementId(),
                        PipelineElementSetupFailedMessage.GENERAL, "Required input variable missing"),
                        getSelf());
        return;
    }

    // retrieve the name of the variable where the script writes the identifier of the next pipeline element to
    this.scriptOutputNextElementVariable = getStringProperty(CONFIG_SCRIPT_OUTPUT_NEXT_ELEMENT_VARIABLE);
    if (StringUtils.isBlank(this.scriptOutputNextElementVariable)) {
        context().parent()
                .tell(new PipelineElementSetupFailedMessage(getPipelineElementConfiguration().getPipelineId(),
                        getPipelineElementConfiguration().getElementId(),
                        PipelineElementSetupFailedMessage.GENERAL,
                        "Required output (next element) variable missing"), getSelf());
        return;
    }

    // if the set of init scripts is not empty, provide them to the script engine 
    if (!initScripts.isEmpty()) {
        for (String script : initScripts) {
            this.scriptEngine.eval(script);
        }
    }
}

From source file:org.cryptomator.ui.ExitUtil.java

private void showTrayNotification(TrayIcon trayIcon) {
    if (settings.getNumTrayNotifications() <= 0) {
        return;/*w ww .  jav a2  s .  c  om*/
    } else {
        settings.setNumTrayNotifications(settings.getNumTrayNotifications() - 1);
        settings.save();
    }
    final Runnable notificationCmd;
    if (SystemUtils.IS_OS_MAC_OSX) {
        final String title = localization.getString("tray.infoMsg.title");
        final String msg = localization.getString("tray.infoMsg.msg.osx");
        final String notificationCenterAppleScript = String
                .format("display notification \"%s\" with title \"%s\"", msg, title);
        notificationCmd = () -> {
            try {
                final ScriptEngineManager mgr = new ScriptEngineManager();
                final ScriptEngine engine = mgr.getEngineByName("AppleScriptEngine");
                if (engine != null) {
                    engine.eval(notificationCenterAppleScript);
                } else {
                    Runtime.getRuntime()
                            .exec(new String[] { "/usr/bin/osascript", "-e", notificationCenterAppleScript });
                }
            } catch (ScriptException | IOException e) {
                // ignore, user will notice the tray icon anyway.
            }
        };
    } else {
        final String title = localization.getString("tray.infoMsg.title");
        final String msg = localization.getString("tray.infoMsg.msg");
        notificationCmd = () -> {
            trayIcon.displayMessage(title, msg, MessageType.INFO);
        };
    }
    SwingUtilities.invokeLater(() -> {
        notificationCmd.run();
    });
}

From source file:Engine.Lua.PlayerLua.java

public void tester(String luaFile) {
    Dog dog = new Dog("Rex");
    Cat cat = new Cat("Felix");
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine scriptEngine = sem.getEngineByName("luaj");
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("Scripts/" + luaFile);
    InputStreamReader isr = new InputStreamReader(is);
    CompiledScript script;/*from   w w w . j a v a2 s . c o m*/
    try {
        script = ((Compilable) scriptEngine).compile(isr);
        isr.close();
        is.close();
        Bindings sb = new SimpleBindings();
        script.eval(sb); // Put the Lua functions into the sb environment
        LuaValue luaDog = CoerceJavaToLua.coerce(dog); // Java to Lua
        //CoerceLuaToJava()
        LuaFunction onTalk = (LuaFunction) sb.get("onTalk"); // Get Lua function
        LuaValue b = onTalk.call(luaDog); // Call the function
        System.out.println("onTalk answered: " + b);
        LuaFunction onWalk = (LuaFunction) sb.get("onWalk");
        LuaValue[] dogs = { luaDog };
        Varargs dist = onWalk.invoke(LuaValue.varargsOf(dogs)); // Alternative

        System.out.println("onWalk returned: " + dist);

        Dog retunredDog = (Dog) CoerceLuaToJava.coerce(luaDog, Dog.class);
        System.out.println("AAAAAAAAAa:" + retunredDog.name);
    } catch (ScriptException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.jumpmind.metl.core.runtime.component.ContentRouter.java

@Override
protected void start() {
    ScriptEngineManager factory = new ScriptEngineManager();
    scriptEngine = factory.getEngineByName("groovy");
    TypedProperties properties = getTypedProperties();
    rowsPerMessage = properties.getLong(ROWS_PER_MESSAGE);
    String json = getComponent().get(SETTING_CONFIG);
    onlyRouteFirstMatch = getComponent().getBoolean(ONLY_ROUTE_FIRST_MATCH, false);
    if (isNotBlank(json)) {
        try {/*  ww  w. j a  va 2 s.  co  m*/
            routes = new ObjectMapper().readValue(json, new TypeReference<List<Route>>() {
            });
            // Verify all routes are valid
            for (Route route : routes) {
                FlowStepLink link = getFlow().findLinkBetweenSourceAndTarget(this.getFlowStepId(),
                        route.getTargetStepId());
                if (link == null) {
                    throw new MisconfiguredException("A route target step is not linked.");
                }
            }
        } catch (Exception e) {
            throw new IoException(e);
        }
    }
}

From source file:com.servioticy.dispatcher.SOProcessor010.java

public boolean checkFilter(JsonPathReplacer filterField, Map<String, String> inputJsons)
        throws ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    if (filterField == null) {
        return true;
    }/*  w  w w .j  a  v  a 2 s .com*/
    String filterCode = filterField.replace(inputJsons);

    engine.eval("var result = Boolean(" + filterCode + ")");
    return (Boolean) engine.get("result");

}