Example usage for javax.script ScriptEngine put

List of usage examples for javax.script ScriptEngine put

Introduction

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

Prototype

public void put(String key, Object value);

Source Link

Document

Sets a key/value pair in the state of the ScriptEngine that may either create a Java Language Binding to be used in the execution of scripts or be used in some other way, depending on whether the key is reserved.

Usage

From source file:it.delli.mwebc.command.impl.EventCommand.java

public void execute(Page page, JsonObject data) {
    String eventName = data.get("event").getAsString();
    String eventType = data.get("eventType").getAsString();
    String method = data.get("forward").getAsString();
    Widget widget = null;//from ww  w  .  ja  v a2  s  .  c  o  m
    EventListener eventListener = null;
    if (data.get("id") != null) {
        widget = page.getWidget(data.get("id").getAsString());
        eventListener = widget.getEventListener(eventName);
    } else {
        eventListener = page.getEventListener();
    }
    Class eventTypeClass = page.getApplication().getEventClass(eventType);
    Event event = null;
    try {
        event = (Event) eventTypeClass.getConstructor(String.class, Widget.class, JsonObject.class)
                .newInstance(eventName, widget, data.get("data").getAsJsonObject());
    } catch (Exception e) {
        log.error("Exception in creating event instance for event type " + eventType);
    }
    ;
    event.setPage(page);
    // bind widgets
    ReflectionUtils.bindWidgets(eventListener, page);
    //
    Method forwardMethod = null;
    if (eventListener instanceof PageEventListener && page.getWidget(method) != null) {
        try {
            it.delli.mwebc.widget.Method widgetMethod = (it.delli.mwebc.widget.Method) page.getWidget(method);
            ScriptEngineManager factory = new ScriptEngineManager();
            ScriptEngine engine = factory.getEngineByName("groovy");
            engine.put("eventListener", null);
            engine.eval(widgetMethod.getScript());
            eventListener = (EventListener) engine.get("eventListener");
            forwardMethod = eventListener.getClass().getMethod(method, Event.class);
            forwardMethod.setAccessible(true);
        } catch (Exception e) {
            log.error("Exception in getting method to execute", e);
        }
    } else {
        try {
            forwardMethod = eventListener.getClass().getMethod(method, Event.class);
            forwardMethod.setAccessible(true);
        } catch (Exception e) {
            log.error("Exception in getting method to execute", e);
        }
    }
    if (forwardMethod != null) {
        if (event.getWidget() != null) {
            log.info("Executing forward method " + eventListener.getClass().getName() + "."
                    + forwardMethod.getName() + " for event " + event.getName() + " on widget "
                    + event.getWidget().getClass().getName() + " (" + event.getWidget().getId() + ")");
        } else {
            log.info("Executing forward method " + eventListener.getClass().getName() + "."
                    + forwardMethod.getName() + " for event " + event.getName());
        }
        try {
            forwardMethod.invoke(eventListener, event);
        } catch (Exception e) {
            if (event.getWidget() != null) {
                log.error("Exception in executing of forward method " + eventListener.getClass().getName() + "."
                        + forwardMethod.getName() + " for event " + event.getName() + " on widget "
                        + event.getWidget().getClass().getName() + " (" + event.getWidget().getId() + ")", e);
            } else {
                log.error("Exception in executing of forward method " + eventListener.getClass().getName() + "."
                        + forwardMethod.getName() + " for event " + event.getName(), e);
            }
            log.error("Exception in forward method execution", e);
        }
    } else {
        log.info("Forward method does not exist in event listener " + eventListener.getClass().getName()
                + " for event " + event.getName());
        log.info("Notifying end of failed execution for event " + event.getName());
    }
}

From source file:org.jdto.mergers.ScriptMerger.java

private Object doMergeObjects(Object value, String[] extraParam) {
    String script = extractScript(extraParam);
    ScriptEngine engine = initializeScriptEngine(extraParam);

    //populate local variables
    engine.put("sourceValue", value);

    //if the value is a list then, just make it available as sourceValues
    if (value instanceof List) {
        engine.put("sourceValues", value);
    }/*from   w  ww.  jav  a2s.  c  o  m*/

    //try to execute the script.
    return executeScript(engine, script);
}

From source file:org.archive.modules.deciderules.ScriptedDecideRule.java

/**
 * Create a new ScriptEngine instance, preloaded with any supplied
 * source file and the variables 'self' (this ScriptedDecideRule) 
 * and 'context' (the ApplicationContext). 
 * /*  w w  w .j a v a 2  s  .  co  m*/
 * @return  the new Interpreter instance
 */
protected ScriptEngine newEngine() {
    ScriptEngine interpreter = new ScriptEngineManager().getEngineByName(engineName);

    interpreter.put("self", this);
    interpreter.put("context", appCtx);

    Reader reader = null;
    try {
        reader = getScriptSource().obtainReader();
        interpreter.eval(reader);
    } catch (ScriptException e) {
        logger.log(Level.SEVERE, "script problem", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return interpreter;
}

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

private void initScriptProperties(final ScriptEngine se, final Properties properties) {
    for (String name : properties.stringPropertyNames()) {
        se.put(name, properties.getProperty(name));
    }/*from   w w  w  . jav a2  s . co  m*/
}

From source file:com.seajas.search.profiler.validator.ModifierValidator.java

/**
 * Validate the given command object./*from w ww .  java  2s  .  co  m*/
 * 
 * @param command
 * @param errors
 */
@Override
public void validate(final Object command, final Errors errors) {
    ModifierCommand modifier = (ModifierCommand) command;

    if (modifier.getAction() != null
            && (modifier.getAction().equals("add") || modifier.getAction().equals("edit"))) {
        if (StringUtils.isEmpty(modifier.getUrlExpression()))
            errors.rejectValue("urlExpression", "modifiers.validator.error.url.expression.empty");
        else
            try {
                Pattern.compile(modifier.getUrlExpression());
            } catch (PatternSyntaxException e) {
                errors.rejectValue("urlExpression", "modifiers.validator.error.url.expression.invalid");
            }

        if (StringUtils.isEmpty(modifier.getUrlType()))
            errors.rejectValue("urlType", "modifiers.validator.error.url.type.empty");
    } else if (modifier.getFilterAction() != null && (modifier.getFilterAction().equals("add-filter")
            || modifier.getFilterAction().equals("edit-filter"))) {
        if (StringUtils.isEmpty(modifier.getFilterStart()))
            errors.rejectValue("filterStart", "modifiers.validator.error.filter.start.empty");
        else if (modifier.getFilterAsExpression())
            try {
                Pattern.compile(modifier.getFilterStart());
            } catch (PatternSyntaxException e) {
                errors.rejectValue("filterStart", "modifiers.validator.error.filter.start.invalid");
            }

        if (StringUtils.isEmpty(modifier.getFilterEnd()))
            errors.rejectValue("filterEnd", "modifiers.validator.error.filter.end.empty");
        else if (modifier.getFilterAsExpression())
            try {
                Pattern.compile(modifier.getFilterEnd());
            } catch (PatternSyntaxException e) {
                errors.rejectValue("filterEnd", "modifiers.validator.error.filter.end.invalid");
            }
    } else if (modifier.getScriptAction() != null && (modifier.getScriptAction().equals("add-script")
            || modifier.getScriptAction().equals("edit-script"))) {
        if (StringUtils.isEmpty(modifier.getScriptLanguage()))
            errors.rejectValue("scriptLanguage", "modifiers.validator.error.script.language.invalid");

        if (StringUtils.isEmpty(modifier.getScriptContent()))
            errors.rejectValue("scriptContent", "modifiers.validator.error.script.content.empty");
        else {
            if (modifier.getScriptLanguage().equalsIgnoreCase("xslt")) {
                StreamSource source = new StreamSource(new StringReader(modifier.getScriptContent()));

                try {
                    TransformerFactory.newInstance().newTransformer(source);
                } catch (Exception e) {
                    errors.rejectValue("scriptContent",
                            "modifiers.validator.error.script.content.invalid.transformation");
                }
            } else {
                ScriptEngineManager engineManager = new ScriptEngineManager();
                ScriptEngine engine = engineManager.getEngineByName(modifier.getScriptLanguage().toLowerCase());

                engine.put("input", "");
                engine.put("inputUrl", "");
                engine.put("inputMaximumContentLength", 0L);

                try {
                    engine.eval(modifier.getScriptContent());
                } catch (ScriptException e) {
                    errors.rejectValue("scriptContent",
                            "modifiers.validator.error.script.content.syntax.error");

                    logger.warn("Script validation failed", e);
                }
            }
        }
    }
}

From source file:net.mindengine.galen.suite.actions.GalenPageActionRunJavascript.java

private void provideWrappedWebDriver(ScriptEngine engine, Browser browser) {
    if (browser instanceof SeleniumBrowser) {
        SeleniumBrowser seleniumBrowser = (SeleniumBrowser) browser;
        engine.put("driver", new WebDriverWrapper(seleniumBrowser.getDriver()));
    }//from www . ja v  a  2s  .c  om

}

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  w ww . j  av a2s  .  c  o  m*/
        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:org.siphon.db2js.DbjsRunner.java

protected void initEngineContext(JsEngineHandlerContext engineContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    ScriptEngine engine = engineContext.getScriptEngine();
    engine.put("request", request);
    engine.put("response", response);
    engine.put("session", JsServlet.getJsSesson(request.getSession()));
    engine.put("dbjsRunner", this);

    JsspWriter out = new JsspWriter(response, engineContext);
    engine.put("out", out);
}

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  ww  w. jav a2s.  c o  m
    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.siphon.db2js.DbjsUnitManager.java

@Override
protected JsEngineHandlerContext createEngineContext(String srcFile, String aliasPath, DataSource dataSource,
        final Map<String, Object> otherArgs) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

    JsEngineUtil.initEngine(engine, (Object[]) otherArgs.get("jslib"));

    File path = new File(srcFolder);

    engine.put("logger", logger);
    engine.put("dataSource", dataSource);
    engine.put("application", otherArgs.get("application"));
    //  js ??? java 
    if (otherArgs.get("preloadJs") != null) {
        String[] preloadJs = (String[]) otherArgs.get("preloadJs"); // [abs path, alias]
        logger.info("evaluate preload js: " + preloadJs[0]);
        JsEngineUtil.eval(engine, preloadJs[0], preloadJs[1],
                FileUtils.readFileToString(new File(preloadJs[0]), "utf-8"), true, false);
    }//from ww  w  .  j  ava  2 s  .c  om

    File src = new File(srcFile);
    String code = FileUtils.readFileToString(src, "utf-8");
    String covertedCode = this.convertCode(code, src);
    File tmp = new File(srcFile + ".converted.js");
    FileUtils.write(tmp, covertedCode, "utf-8");
    if (logger.isDebugEnabled())
        logger.debug(srcFile + " converted as " + tmp.getAbsolutePath());

    JsEngineUtil.eval(engine, srcFile, aliasPath, covertedCode, false, true);

    JsEngineHandlerContext ctxt = new JsEngineHandlerContext();
    ctxt.setScriptEngine(engine);
    ctxt.setHandler((ScriptObjectMirror) engine.eval("dbjs"));
    ctxt.setJson(new JSON(engine)); // jdk has a NativeJSON class inside but
    // it's sealed
    ctxt.setJsTypeUtil(new JsTypeUtil(engine));

    return ctxt;
}