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:io.stallion.dataAccess.db.SqlMigrationAction.java

@Override
public void execute(SqlMigrateCommandOptions options) throws Exception {
    createMigrationTrackingTableIfNotExists();
    // Get a ticket to make sure the tickets table is operational
    Long nonce = DB.instance().getTickets().nextId();
    DB db = DB.instance();/*from  w w w  . j av a 2  s .  com*/
    for (SqlMigration migration : findNotRunMigrations()) {
        Log.info("Run migration app:" + migration.getAppName() + " file:" + migration.getFilename());
        if (migration.isJavascript()) {
            ScriptEngine engine = getOrCreateScriptEngine();
            ;
            engine.put("db", db);
            engine.eval("load(" + JSON.stringify(map(val("script", transformJavascript(migration.getSource())),
                    val("name", migration.getFilename()))) + ");");
        } else {
            db.execute(migration.getSource());

        }
        db.execute(
                "INSERT INTO stallion_sql_migrations (versionNumber, appName, fileName, executedAt) VALUES(?, ?, ?, UTC_TIMESTAMP())",
                migration.getVersionNumber(), migration.getAppName(), migration.getFilename());
    }
}

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

private void showTrayNotification(TrayIcon trayIcon) {
    if (settings.getNumTrayNotifications() <= 0) {
        return;//from   w w  w . ja v a  2  s  . c  o m
    } 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:cz.vity.freerapid.plugins.services.webshare.PasswordJS.java

public String encryptPassword(String pass, String salt) throws Exception {
    try {/*from   w  w  w.  j  a v  a2  s. c  o m*/
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        if (engine == null)
            throw new RuntimeException("JavaScript engine not found");
        final String md5enc = (String) engine
                .eval(JavaScript_MD5Crypt + "md5crypt(\"" + pass + "\", \"" + salt + "\")");
        return DigestUtils.shaHex(md5enc);
    } catch (Exception e) {
        throw new ServiceConnectionProblemException("Can't execute javascript");
    }
}

From source file:org.nyu.edu.dlts.CodeViewerDialog.java

/**
 * Method to evaluate the syntax of the script.
 * Basically try running and see if any syntax errors occur
 *//*  ww  w  .j  av a 2  s.c  o  m*/
private void evaluateButtonActionPerformed() {
    try {
        if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_JAVA)) {
            Interpreter bsi = new Interpreter();
            bsi.set("record", new String("Test"));
            bsi.set("recordType", "test");
            bsi.eval(getCurrentScript());
        } else if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_RUBY)) {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine jri = manager.getEngineByName("jruby");
            jri.put("recordType", "test");
            jri.eval(getCurrentScript());
        } else if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_PYTHON)) {
            PythonInterpreter pyi = new PythonInterpreter();
            pyi.set("record", new String("Test"));
            pyi.set("recordType", "test");
            pyi.exec(getCurrentScript());
        } else {
            // must be java script
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine jsi = manager.getEngineByName("javascript");
            jsi.put("record", new String("Test"));
            jsi.put("recordType", "test");
            jsi.eval(getCurrentScript());
        }

        messageTextArea.setText("No Syntax Errors Found ...");
    } catch (Exception e) {
        messageTextArea.setText("Error Occurred:\n" + dbCopyFrame.getStackTrace(e));
    }
}

From source file:sample.fa.ScriptRunnerApplication.java

private void executeScript(ActionEvent ae) {
    ScriptEngine se = (ScriptEngine) languagesModel.getSelectedItem();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(baos);) {
        se.getContext().setWriter(w);/* w ww.  ja  va2  s  .co  m*/

        Optional<Object> result = Optional.ofNullable(se.eval(scriptContents.getText()));

        scriptResults.setText(baos.toString() + "\n>>>>>>\n" + result.orElse("-null-").toString());
    } catch (Exception e) {
        e.printStackTrace(System.out);
        scriptResults.setText(e.getClass().getName() + " - " + e.getMessage());
    }
}

From source file:org.eclairjs.nashorn.JSComparator.java

@SuppressWarnings({ "null", "unchecked" })
@Override//ww  w  .j  ava2s .c o  m
public int compare(Object o, Object o2) {
    int ret = -1;

    try {

        ScriptEngine e = NashornEngineSingleton.getEngine();
        // if (this.fn == null) {
        /*
        if we try to save teh evaluated function for future use we get serialization exception,
        why Comparators are different than java.api.functions ?
         */
        Object fn = e.eval(func);
        //}
        Invocable invocable = (Invocable) e;

        Object params[] = { fn, o, o2 };

        if (this.args != null && this.args.length > 0) {
            params = ArrayUtils.addAll(params, this.args);
        }
        //Tuple2<String, String> s = new Tuple2("foo", "bar");
        //scala.collection.Iterator<Object> i = s.productIterator();

        ret = Integer.valueOf(invocable.invokeFunction("Utils_invoke", params).toString());

        return ret;
    } catch (Exception exc) {
        exc.printStackTrace();
    }

    return ret;
}

From source file:utybo.branchingstorytree.swing.impl.XSFClient.java

@Override
public Object invokeScript(String resourceName, String function, XSFBridge bst, BranchingStory story, int line)
        throws BSTException {
    ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    SimpleBindings binds = new SimpleBindings();
    binds.putAll(story.getRegistry().getAllInt());
    binds.putAll(story.getRegistry().getAllString());
    binds.put("bst", bst);
    scriptEngine.setBindings(binds, ScriptContext.ENGINE_SCOPE);
    try {/*from  w  w w  . j a  v a  2  s  .  c  om*/
        scriptEngine.eval(scripts.get(resourceName));
        return scriptEngine.eval(function + "()");
    } catch (ScriptException e) {
        throw new BSTException(line, "Script exception : " + e.getMessage(), story);
    }
}

From source file:net.sf.keystore_explorer.utilities.net.PacProxySelector.java

private Invocable compilePacScript(String pacScript) throws PacProxyException {
    try {//from  w  w  w. j  ava2 s. c  o m
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");

        Invocable invocale = (Invocable) jsEngine;

        jsEngine.eval(pacScript);
        jsEngine.eval(new InputStreamReader(PacProxySelector.class.getResourceAsStream("pacUtils.js")));

        return invocale;
    } catch (ScriptException ex) {
        throw new PacProxyException(res.getString("NoCompilePacScript.exception.message"), ex);
    }
}

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;
    }//from   w  ww . java  2  s.c  o m
    String filterCode = filterField.replace(inputJsons);

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

}

From source file:com.github.safrain.remotegsh.server.RgshFilter.java

private void performRunScript(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String script = toString(request.getInputStream(), charset);
    try {//from  w  w w .  ja va 2  s  .  c o m
        ScriptEngine engine = prepareEngine(request, response);
        engine.eval(script);
        response.setStatus(200);
        // Post and run won't return evaluate result to client
    } catch (ScriptException e) {
        log.log(Level.SEVERE, "Error while running script:" + script, e);
        response.setStatus(500);
        e.getCause().printStackTrace(response.getWriter());
    }
}