Example usage for javax.script ScriptEngineManager ScriptEngineManager

List of usage examples for javax.script ScriptEngineManager ScriptEngineManager

Introduction

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

Prototype

public ScriptEngineManager() 

Source Link

Document

The effect of calling this constructor is the same as calling ScriptEngineManager(Thread.currentThread().getContextClassLoader()).

Usage

From source file:org.wso2.developerstudio.datamapper.diagram.custom.dialogs.ConfigureMatchOperatorDialog.java

private String validateRegex(String input) {
    String output = input;/*  ww  w.  j a  v  a  2s.c  o  m*/
    String scriptExecutorType = NASHORN;
    String javaVersion = System.getProperty(JAVA_VERSION);
    if (javaVersion.startsWith(JAVA_VERSION_7) || javaVersion.startsWith(JAVA_VERSION_6)) {
        scriptExecutorType = RHINO;
    }
    ScriptEngine engine = new ScriptEngineManager().getEngineByName(scriptExecutorType);
    try {
        engine.eval("function myFunction(input) {\n" + "var sampleString = \"acbdacfac\";\n" + "\n"
                + "   return sampleString.match(input);\n" + "}\n");
        engine.eval("myFunction(" + input + ");");
    } catch (ScriptException e) {
        output = "\"" + input + "\"";
    }
    return output;
}

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

private void showTrayNotification(TrayIcon trayIcon) {
    if (settings.getNumTrayNotifications() <= 0) {
        return;//from   www.  j  av 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:org.jasig.maven.plugin.sass.AbstractSassMojo.java

/**
 * Execute the SASS Compilation Ruby Script
 *///  ww w . j  a v a  2 s.c o  m
protected void executeSassScript(String sassScript) throws MojoExecutionException, MojoFailureException {
    final Log log = this.getLog();
    System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe");

    log.debug("Execute SASS Ruby Script:\n" + sassScript);

    final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby");
    try {
        CompilerCallback compilerCallback = new CompilerCallback(log);
        jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback);
        jruby.eval(sassScript);
        if (failOnError && compilerCallback.hadError()) {
            throw new MojoFailureException("SASS compilation encountered errors (see above for details).");
        }
    } catch (final ScriptException e) {
        throw new MojoExecutionException("Failed to execute SASS ruby script:\n" + sassScript, e);
    }
}

From source file:org.jspringbot.keyword.json.JSONHelper.java

public int getJsonListLength(String jsonExpression) {
    validate();//from   w w w .j  a  v  a 2  s .co m

    try {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript");
        engine.eval("var json = " + jsonString + ";");
        engine.eval("var jsonExpr = json." + jsonExpression + ".length;");

        int length = ((Number) engine.get("jsonExpr")).intValue();

        LOG.createAppender().appendBold("Get JSON List Length:")
                .appendProperty("Json Expression", jsonExpression).appendProperty("Length", length).log();

        return length;
    } catch (Exception e) {
        throw new IllegalStateException("Response is not json.", 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;
    }/*from   ww w .j av  a 2 s .co m*/
    String filterCode = filterField.replace(inputJsons);

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

}

From source file:tk.elevenk.restfulrobot.testcase.TestCase.java

/**
 * Runs the given test script file/*from w  w w. j a va  2 s  . co  m*/
 * 
 * @param fileName
 */
public void runScript(String fileName) {

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

    if (!fileName.endsWith(".js")) {
        fileName = fileName.concat(".js");
    }

    FileReader scriptFile = null;
    // attempt to open the script file
    try {
        scriptFile = new FileReader(new File(RestfulRobot.SCRIPTS_PATH + fileName));
    } catch (FileNotFoundException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        result.setDetails(e.getMessage());
        result.setResultType(TestResult.TYPE_ERROR);
    }

    // run the script
    try {
        logger.info("Running script " + fileName);
        engine.eval(scriptFile);
    } catch (ScriptException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        result.setDetails(e.getMessage());
        result.setResultType(TestResult.TYPE_ERROR);
    }

    // pull data from script
    try {
        this.testCaseID = (String) engine.get("testCaseID");
        this.testCategory = (String) engine.get("testCategory");
        this.testPlan = (String) engine.get("testPlan");
        this.testProject = (String) engine.get("testProject");
        this.testType = (String) engine.get("testType");
        this.testName = (String) engine.get("testName");
    } catch (Exception e) {
        // TODO make this try each parameter
    }

    logger.info("Finished running script");
}

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   ww  w .  j ava2s  . co 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.servioticy.dispatcher.SOProcessor010.java

public SensorUpdate getResultSU(String streamId, Map<String, SensorUpdate> inputSUs, String origin,
        long timestamp) throws JsonParseException, JsonMappingException, IOException, ScriptException {

    Map<String, String> inputDocs = new HashMap<String, String>();
    for (Map.Entry<String, SensorUpdate> inputSUEntry : inputSUs.entrySet()) {
        inputDocs.put(inputSUEntry.getKey(), this.mapper.writeValueAsString(inputSUEntry.getValue()));
    }/*w  w  w  .j  a v  a2s.c o  m*/
    PSOStream pstream = this.streams.get(streamId);
    if (!checkFilter(pstream.preFilter, inputDocs)) {
        return null;
    }
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    SensorUpdate su = new SensorUpdate();

    su.setLastUpdate(timestamp);
    su.setChannels(new LinkedHashMap<String, SUChannel>());

    int nulls = 0;
    for (Entry<String, PSOChannel> channelEntry : pstream.channels.entrySet()) {
        PSOChannel pchannel = channelEntry.getValue();
        SUChannel suChannel = new SUChannel();
        if (pchannel.currentValue == null) {
            suChannel.setCurrentValue(null);
            nulls++;
        } else {
            String currentValueCode = pchannel.currentValue.replace(inputDocs);
            Class type;
            String typeName;
            Object result = null;
            typeName = pchannel.type.toLowerCase();
            if (typeName.equals("number")) {
                type = Double.class;
            } else if (typeName.equals("boolean")) {
                type = Boolean.class;
            } else if (typeName.equals("string")) {
                type = String.class;
            } else if (typeName.equals("geo_point")) {
                type = GeoPoint.class;

            } else {
                return null;
            }

            engine.eval("var result = JSON.stringify(" + currentValueCode + ")");
            result = this.mapper.readValue((String) engine.get("result"), type);
            if (type == GeoPoint.class)
                result = ((GeoPoint) result).getLat() + "," + ((GeoPoint) result).getLon();
            suChannel.setCurrentValue(result);

        }
        suChannel.setUnit(pchannel.unit);

        su.getChannels().put(channelEntry.getKey(), suChannel);
    }

    if (nulls >= su.getChannels().size()) {
        // This stream is mapping a Web Object.
        return null;
    }

    su.setTriggerPath(new ArrayList<ArrayList<String>>());

    su.setPathTimestamps(new ArrayList<Long>());

    this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String resultSUDoc = this.mapper.writeValueAsString(su);
    if (!inputDocs.containsKey("result")) {
        inputDocs.put("result", resultSUDoc);
    }

    if (!checkFilter(pstream.postFilter, inputDocs)) {
        return null;
    }
    return su;
}

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

public SensorUpdate getResultSU(String streamId, Map<String, SensorUpdate> inputSUs, String origin,
        long timestamp) throws IOException, ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    SensorUpdate su = new SensorUpdate();

    su.setLastUpdate(timestamp);//from ww  w.  ja  v  a 2 s .  c o  m
    su.setChannels(new LinkedHashMap<String, SUChannel>());

    SOStream stream = so.getStreams(this.mapper).get(streamId);
    for (Map.Entry<String, SOChannel> channelEntry : stream.getChannels().entrySet()) {
        SOChannel channel = channelEntry.getValue();
        SUChannel suChannel = new SUChannel();
        String currentValueCode = channel.getCurrentValue();
        // TODO Check for invalid calls
        // TODO Check for an invalid header
        if (isFunction(currentValueCode)) {
            // There is no code for one of the channels. Invalid.
            return null;
        } else {
            TypeReference type;
            Class dataClass;
            boolean array = false;

            switch (parseType(channel.getType())) {
            case TYPE_ARRAY_NUMBER:
                type = new TypeReference<List<Double>>() {
                };
                array = true;
                break;
            case TYPE_NUMBER:
                type = new TypeReference<Double>() {
                };
                break;
            case TYPE_ARRAY_BOOLEAN:
                type = new TypeReference<List<Boolean>>() {
                };
                array = true;
                break;
            case TYPE_BOOLEAN:
                type = new TypeReference<Boolean>() {
                };
                break;
            case TYPE_ARRAY_STRING:
                type = new TypeReference<List<String>>() {
                };
                array = true;
                break;
            case TYPE_STRING:
                type = new TypeReference<String>() {
                };
                break;
            // non-primitive types
            case TYPE_ARRAY_GEOPOINT:
                type = new TypeReference<List<GeoPoint>>() {
                };
                array = true;
                break;
            case TYPE_GEOPOINT:
                type = new TypeReference<GeoPoint>() {
                };
                break;
            default:
                return null;
            }

            String resultVar = "$" + Long.toHexString(UUID.randomUUID().getMostSignificantBits());

            engine.eval(initializationCode(inputSUs, origin) + "var " + resultVar + " = JSON.stringify("
                    + currentValueCode + "(" + functionArgsString(currentValueCode) + ")" + ")");
            Object result = this.mapper.readValue((String) engine.get(resultVar), type);

            if (result == null) {
                // Filtered output. The type is not the expected one.
                return null;
            }
            suChannel.setCurrentValue(result);
        }
        suChannel.setUnit(channel.getUnit());

        su.getChannels().put(channelEntry.getKey(), suChannel);
    }

    su.setTriggerPath(new ArrayList<ArrayList<String>>());

    su.setPathTimestamps(new ArrayList<Long>());

    return su;
}

From source file:io.github.microcks.web.SoapController.java

private String getDispatchCriteriaFromScriptEval(Operation operation, String body) {
    ScriptEngineManager sem = new ScriptEngineManager();
    try {/*w  ww.j a  v a  2s .  com*/
        // Evaluating request with script coming from operation dispatcher rules.
        ScriptEngine se = sem.getEngineByExtension("groovy");
        SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body);
        return (String) se.eval(operation.getDispatcherRules());
    } catch (Exception e) {
        log.error("Error during Script evaluation", e);
    }
    return null;
}