Example usage for javax.script SimpleBindings SimpleBindings

List of usage examples for javax.script SimpleBindings SimpleBindings

Introduction

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

Prototype

public SimpleBindings() 

Source Link

Document

Default constructor uses a HashMap .

Usage

From source file:ru.iris.events.EventsService.java

public EventsService() {
    Status status = new Status("Events");

    if (status.checkExist()) {
        status.running();/*from   w  w  w  .j a  va2s  . c  om*/
    } else {
        status.addIntoDB("Events", "Service that listen for events and exec scripts as needed");
    }

    try {

        events = Ebean.find(Event.class).findList();

        // take pause to save/remove new entity
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // load all scripts, compile and put into map
        compiledScriptMap = loadAndCompile(events);

        // Pass jsonmessaging instance to js engine
        Bindings bindings = new SimpleBindings();
        bindings.put("jsonMessaging", jsonMessaging);
        bindings.put("LOGGER", scriptLogger);

        // subscribe to events from db
        for (Event event : events) {
            jsonMessaging.subscribe(event.getSubject());
            LOGGER.debug("Subscribe to subject: " + event.getSubject());
        }

        // command launch
        jsonMessaging.subscribe("event.command");

        // scripts
        jsonMessaging.subscribe("event.script.get");
        jsonMessaging.subscribe("event.script.save");
        jsonMessaging.subscribe("event.script.delete");
        jsonMessaging.subscribe("event.script.list");
        jsonMessaging.subscribe("event.reload");

        jsonMessaging.setNotification(new JsonNotification() {

            @Override
            public void onNotification(JsonEnvelope envelope) {

                LOGGER.debug("Got envelope with subject: " + envelope.getSubject());

                try {

                    // Get script content
                    if (envelope.getObject() instanceof EventGetScriptAdvertisement) {
                        LOGGER.debug("Return JS script to: " + envelope.getReceiverInstance());
                        EventGetScriptAdvertisement advertisement = envelope.getObject();
                        File jsFile;

                        if (advertisement.isCommand())
                            jsFile = new File("./scripts/command/" + advertisement.getName());
                        else
                            jsFile = new File("./scripts/" + advertisement.getName());

                        jsonMessaging.response(envelope,
                                new EventResponseGetScriptAdvertisement(FileUtils.readFileToString(jsFile)));

                    }
                    // Save new/existing script
                    else if (envelope.getObject() instanceof EventResponseSaveScriptAdvertisement) {

                        EventResponseSaveScriptAdvertisement advertisement = envelope.getObject();
                        LOGGER.debug("Request to save changes: " + advertisement.getName());
                        File jsFile;

                        if (advertisement.isCommand())
                            jsFile = new File("./scripts/command/" + advertisement.getName());
                        else
                            jsFile = new File("./scripts/" + advertisement.getName());

                        FileUtils.writeStringToFile(jsFile, advertisement.getBody());
                        LOGGER.info("Restart event service (reason: script change)");
                        reloadService();
                    }
                    // Remove script
                    else if (envelope.getObject() instanceof EventRemoveScriptAdvertisement) {

                        EventRemoveScriptAdvertisement advertisement = envelope.getObject();
                        LOGGER.debug("Request to remove script: " + advertisement.getName());
                        File jsFile;

                        if (advertisement.isCommand())
                            jsFile = new File("./scripts/command/" + advertisement.getName());
                        else
                            jsFile = new File("./scripts/" + advertisement.getName());

                        FileUtils.forceDelete(jsFile);
                        LOGGER.info("Restart event service (reason: script removed)");
                        reloadService();
                    }
                    // List available scripts
                    else if (envelope.getObject() instanceof EventListScriptsAdvertisement) {

                        EventListScriptsAdvertisement advertisement = envelope.getObject();
                        File jsFile;

                        if (advertisement.isCommand())
                            jsFile = new File("./scripts/command/");
                        else
                            jsFile = new File("./scripts/");

                        EventResponseListScriptsAdvertisement response = new EventResponseListScriptsAdvertisement();
                        response.setScripts(
                                (List<File>) FileUtils.listFiles(jsFile, new String[] { "js" }, false));

                        jsonMessaging.response(envelope, response);
                    }
                    // Check command and launch script
                    else if (envelope.getObject() instanceof CommandAdvertisement) {

                        CommandAdvertisement advertisement = envelope.getObject();
                        bindings.put("advertisement", envelope.getObject());

                        if (compiledCommandScriptMap.get(advertisement.getScript()) == null) {

                            LOGGER.debug("Compile command script: " + advertisement.getScript());

                            File jsFile = new File("./scripts/command/" + advertisement.getScript());
                            CompiledScript compile = engine.compile(FileUtils.readFileToString(jsFile));
                            compiledCommandScriptMap.put(advertisement.getScript(), compile);

                            LOGGER.debug("Launch compiled command script: " + advertisement.getScript());
                            compile.eval(bindings);
                        } else {
                            LOGGER.info("Launch compiled command script: " + advertisement.getScript());
                            compiledCommandScriptMap.get(advertisement.getScript()).eval(bindings);
                        }
                    } else if (envelope.getObject() instanceof EventChangesAdvertisement) {
                        reloadService();
                    } else {
                        for (Event event : events) {
                            if (envelope.getSubject().equals(event.getSubject())
                                    || wildCardMatch(event.getSubject(), envelope.getSubject())) {

                                LOGGER.debug("Run compiled script: " + event.getScript());

                                try {
                                    bindings.put("advertisement", envelope.getObject());
                                    CompiledScript script = compiledScriptMap.get(event.getScript());

                                    if (script != null)
                                        script.eval(bindings);
                                    else
                                        LOGGER.error("Error! Script " + event.getScript() + " is NULL!");

                                } catch (ScriptException e) {
                                    LOGGER.error("Error in script scripts/command/" + event.getScript() + ": "
                                            + e.toString());
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                } catch (ScriptException | IOException e) {
                    LOGGER.error("Error in script: " + e.toString());
                    e.printStackTrace();
                }
            }
        });

        jsonMessaging.start();
    } catch (final RuntimeException t) {
        LOGGER.error("Error in Events!");
        status.crashed();
        t.printStackTrace();
    }
}

From source file:com.jkoolcloud.tnt4j.streams.filters.GroovyExpressionFilter.java

@Override
public boolean doFilter(Object value, ActivityInfo ai) throws FilterException {
    Bindings bindings = new SimpleBindings();
    bindings.put(StreamsScriptingUtils.FIELD_VALUE_VARIABLE_EXPR, value);

    if (ai != null && CollectionUtils.isNotEmpty(exprVars)) {
        for (String eVar : exprVars) {
            Property eKV = resolveFieldKeyAndValue(eVar, ai);

            bindings.put(eKV.getKey(), eKV.getValue());
        }/*from   w ww . jav  a  2s. co  m*/
    }

    try {
        boolean match = (boolean) script.eval(bindings);

        logEvaluationResult(bindings, match);

        return isFilteredOut(getHandleType(), match);
    } catch (Exception exc) {
        throw new FilterException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ExpressionFilter.filtering.failed", filterExpression), exc);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.transform.JavaScriptTransformation.java

@Override
public Object transform(Object value, ActivityInfo ai) throws TransformationException {
    Bindings bindings = new SimpleBindings();
    bindings.put(StreamsScriptingUtils.FIELD_VALUE_VARIABLE_EXPR, value);

    if (ai != null && CollectionUtils.isNotEmpty(exprVars)) {
        for (String eVar : exprVars) {
            Property eKV = resolveFieldKeyAndValue(eVar, ai);

            bindings.put(eKV.getKey(), eKV.getValue());
        }//from w ww .  j a va 2 s . c o m
    }

    try {
        Object tValue = script.eval(bindings);

        logEvaluationResult(bindings, tValue);

        return tValue;
    } catch (Exception exc) {
        throw new TransformationException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "ValueTransformation.transformation.failed", getName(), getPhase()),
                exc);
    }
}

From source file:net.unit8.longadeseo.plugin.impl.JRubyExcelPlugin.java

@Override
public void afterService(DavResource resource, InputStream in) {
    try {//from www  .j  a  va2  s .c om
        Workbook workbook = load(in);
        Book book = new Book(workbook);
        SimpleBindings bindings = new SimpleBindings();
        bindings.put("@book", book);
        script.eval(bindings);
    } catch (Exception e) {
        throw new PluginExecutionException(e);
    }
}

From source file:com.googlecode.starflow.core.script.spel.SpelScriptEngine.java

@Override
public Bindings createBindings() {
    return new SimpleBindings();
}

From source file:org.apache.sling.scripting.sightly.compiler.java.JavaClassBackendCompilerTest.java

@Test
public void testScript() throws Exception {
    CompilationUnit compilationUnit = TestUtils.readScriptFromClasspath("/test.html");
    JavaClassBackendCompiler backendCompiler = new JavaClassBackendCompiler();
    SightlyCompiler sightlyCompiler = new SightlyCompiler();
    sightlyCompiler.compile(compilationUnit, backendCompiler);
    ClassInfo classInfo = new ClassInfo() {
        @Override//from   ww  w.j av  a 2s. com
        public String getSimpleClassName() {
            return "Test";
        }

        @Override
        public String getPackageName() {
            return "org.example.test";
        }

        @Override
        public String getFullyQualifiedClassName() {
            return "org.example.test.Test";
        }
    };
    String source = backendCompiler.build(classInfo);
    ClassLoader classLoader = JavaClassBackendCompilerTest.class.getClassLoader();
    CharSequenceJavaCompiler<RenderUnit> compiler = new CharSequenceJavaCompiler<>(classLoader, null);
    Class<RenderUnit> newClass = compiler.compile(classInfo.getFullyQualifiedClassName(), source,
            new Class<?>[] {});
    RenderUnit renderUnit = newClass.newInstance();
    StringWriter writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    RenderContext renderContext = new RenderContext() {
        @Override
        public AbstractRuntimeObjectModel getObjectModel() {
            return new AbstractRuntimeObjectModel() {
            };
        }

        @Override
        public Bindings getBindings() {
            return new SimpleBindings();
        }

        @Override
        public Object call(String functionName, Object... arguments) {
            assert arguments.length == 2;
            // for this test case only the xss runtime function will be called; return the unfiltered input
            return arguments[0];
        }
    };
    renderUnit.render(printWriter, renderContext, new SimpleBindings());
    String expectedOutput = IOUtils.toString(this.getClass().getResourceAsStream("/test-output.html"), "UTF-8");
    assertEquals(expectedOutput, writer.toString());

}

From source file:JrubyTest.java

/**
 * //  w  w  w . j  a  v a  2 s  . c o m
 */
@Test
public void repeatedTitle() throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("jruby");
    Reader scriptReader = null;
    InputStream in = null;
    try {
        in = getClass().getClassLoader().getResourceAsStream("test-specifications.xls");
        Workbook workbook = load(in);
        Book book = new Book(workbook);
        scriptReader = new InputStreamReader(
                getClass().getClassLoader().getResourceAsStream("test-specification-repeated-title.rb"));
        if (engine instanceof Compilable) {
            CompiledScript script = ((Compilable) engine).compile(scriptReader);
            SimpleBindings bindings = new SimpleBindings();
            bindings.put("@book", book);
            script.eval(bindings);
        }
    } finally {
        IOUtils.closeQuietly(scriptReader);
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.ScriptEnginesTest.java

@Test
public void shouldMergeBindingsFromLocalAndGlobal() throws Exception {
    final ScriptEngines engines = new ScriptEngines(se -> {
    });//  w  ww.  j av  a  2  s.c  om
    engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(),
            Collections.emptyMap());

    engines.loadPlugins(Arrays.asList(new GremlinPlugin() {
        @Override
        public String getName() {
            return "mock";
        }

        @Override
        public void pluginTo(final PluginAcceptor pluginAcceptor)
                throws IllegalEnvironmentException, PluginInitializationException {
            pluginAcceptor.addBinding("y", "here");
        }
    }));

    final Bindings localBindings = new SimpleBindings();
    localBindings.put("x", "there");

    assertEquals("herethere", engines.eval("y+x", localBindings, "gremlin-groovy"));
}

From source file:org.jahia.services.render.scripting.JSR223Script.java

/**
 * Execute the script and return the result as a string
 *
 * @param resource resource to display//from ww w . java 2s .c  om
 * @param context
 * @return the rendered resource
 * @throws org.jahia.services.render.RenderException
 */
public String execute(Resource resource, RenderContext context) throws RenderException {
    ScriptEngine scriptEngine = null;

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(view.getModule().getChainedClassLoader());

    try {
        scriptEngine = ScriptEngineUtils.getInstance().scriptEngine(view.getFileExtension());

        if (scriptEngine != null) {
            ScriptContext scriptContext = new SimpleScriptContext();
            final Bindings bindings = new SimpleBindings();
            Enumeration<?> attrNamesEnum = context.getRequest().getAttributeNames();
            while (attrNamesEnum.hasMoreElements()) {
                String currentAttributeName = (String) attrNamesEnum.nextElement();
                if (!"".equals(currentAttributeName)) {
                    bindings.put(currentAttributeName, context.getRequest().getAttribute(currentAttributeName));
                }
            }
            bindings.put("params", context.getRequest().getParameterMap());
            Reader scriptContent = null;
            try {
                InputStream scriptInputStream = getViewInputStream();
                if (scriptInputStream != null) {
                    scriptContent = new InputStreamReader(scriptInputStream);
                    scriptContext.setWriter(new StringWriter());
                    scriptContext.setErrorWriter(new StringWriter());
                    // The following binding is necessary for Javascript, which doesn't offer a console by default.
                    bindings.put("out", new PrintWriter(scriptContext.getWriter()));
                    scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
                    scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                            ScriptContext.GLOBAL_SCOPE);

                    scriptEngine.eval(scriptContent, scriptContext);

                    StringWriter writer = (StringWriter) scriptContext.getWriter();
                    return writer.toString().trim();
                } else {
                    throw new RenderException(
                            "Error while retrieving input stream for the resource " + view.getPath());
                }
            } catch (ScriptException e) {
                throw new RenderException("Error while executing script " + view.getPath(), e);
            } catch (IOException e) {
                throw new RenderException(
                        "Error while retrieving input stream for the resource " + view.getPath(), e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }

    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    return null;
}

From source file:org.gatherdata.alert.detect.bsf.internal.BsfEventDetector.java

private Bindings adaptToScriptContext(Map<String, Object> attributes) {
    Bindings scriptBindings = new SimpleBindings();
    scriptBindings.putAll(attributes);/* w  ww. j  av a 2  s .c om*/
    return scriptBindings;
}