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:org.nuxeo.ecm.webengine.scripting.Scripting.java

protected Object _runScript(ScriptFile script, Map<String, Object> args) throws Exception {
    SimpleBindings bindings = new SimpleBindings();
    if (args != null) {
        bindings.putAll(args);/*from   w  w  w  .  java2 s. com*/
    }
    String ext = script.getExtension();
    // check for a script engine
    ScriptEngine engine = getEngineManager().getEngineByExtension(ext);
    if (engine != null) {
        ScriptContext ctx = new SimpleScriptContext();
        ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        CompiledScript comp = getCompiledScript(engine, script.getFile()); // use cache for compiled scripts
        if (comp != null) {
            return comp.eval(ctx);
        } // compilation not supported - eval it on the fly
        try {
            Reader reader = new FileReader(script.getFile());
            try { // TODO use __result__ to pass return value for engine that doesn't returns like jython
                Object result = engine.eval(reader, ctx);
                if (result == null) {
                    result = bindings.get("__result__");
                }
                return result;
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    }
    return null;
}

From source file:org.onesec.raven.ivr.actions.CollectDtmfsActionNode.java

@Override
public Collection<Node> getEffectiveNodes() {
    if (getStatus() != Node.Status.STARTED)
        return null;
    Bindings bindings = new SimpleBindings();
    formExpressionBindings(bindings);//from  ww  w.j a v  a 2 s.c o  m
    String tempDtmfsKey = getTempDtmfsKey();
    ConversationScenarioState state = getConversationState(bindings);
    List<String> dtmfs = (List<String>) state.getBindings().get(tempDtmfsKey);
    if (dtmfs == null) {
        dtmfs = new LinkedList<String>();
        state.setBinding(tempDtmfsKey, dtmfs, BindingScope.POINT);
        state.setBinding(dtmfsBindingName, dtmfs, bindingScope);
    }
    String dtmf = (String) bindings.get(DTMF_BINDING);
    Integer _maxDtmfsCount = maxDtmfsCount;
    if (stopDtmf.equals(dtmf))
        return processStopAction(state, dtmfs, tempDtmfsKey);
    else {
        String lastTsKey = getLastTsKey();
        long curTime = System.currentTimeMillis();
        if (!(EMPTY_DTMF + "").equals(dtmf)) {
            dtmfs.add(dtmf);
            if (_maxDtmfsCount != null && dtmfs.size() == _maxDtmfsCount)
                return processStopAction(state, dtmfs, tempDtmfsKey);
            else if (autoStopDelay != null)
                state.setBinding(lastTsKey, curTime, BindingScope.POINT);
        } else {
            Long _autoStopDelay = autoStopDelay;
            if (_autoStopDelay != null) {
                Long lastTs = (Long) state.getBindings().get(lastTsKey);
                if (lastTs != null && lastTs + autoStopDelayUnit.toMillis(autoStopDelay) <= curTime)
                    return processStopAction(state, dtmfs, tempDtmfsKey);
            }
        }
        return null;
    }
}

From source file:org.jahia.services.scheduler.JSR223ScriptJob.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    final JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    String jobScriptPath;/*ww w.  j av  a  2  s  .  c o m*/
    boolean isAbsolutePath = false;
    if (map.containsKey(JOB_SCRIPT_ABSOLUTE_PATH)) {
        isAbsolutePath = true;
        jobScriptPath = map.getString(JOB_SCRIPT_ABSOLUTE_PATH);
    } else {
        jobScriptPath = map.getString(JOB_SCRIPT_PATH);
    }
    logger.info("Start executing JSR223 script job {}", jobScriptPath);

    ScriptEngine scriptEngine = ScriptEngineUtils.getInstance()
            .scriptEngine(FilenameUtils.getExtension(jobScriptPath));
    if (scriptEngine != null) {
        ScriptContext scriptContext = new SimpleScriptContext();
        final Bindings bindings = new SimpleBindings();
        bindings.put("jobDataMap", map);

        InputStream scriptInputStream;
        if (!isAbsolutePath) {
            scriptInputStream = JahiaContextLoaderListener.getServletContext()
                    .getResourceAsStream(jobScriptPath);
        } else {
            scriptInputStream = FileUtils.openInputStream(new File(jobScriptPath));
        }
        if (scriptInputStream != null) {
            Reader scriptContent = null;
            try {
                scriptContent = new InputStreamReader(scriptInputStream);
                StringWriter out = new StringWriter();
                scriptContext.setWriter(out);
                // 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);
                map.put(JOB_SCRIPT_OUTPUT, out.toString());
                logger.info("...JSR-223 script job {} execution finished", jobScriptPath);
            } catch (ScriptException e) {
                logger.error("Error during execution of the JSR-223 script job " + jobScriptPath
                        + " execution failed with error " + e.getMessage(), e);
                throw new Exception("Error during execution of script " + jobScriptPath, e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }
    }
}

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;/*from  w  w  w  .  j  a  v  a2  s .c  om*/
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:org.apache.sling.scripting.sightly.js.impl.JsEnvironment.java

private Bindings buildBindings(Resource scriptResource, Bindings local, Bindings arguments,
        CommonJsModule commonJsModule) {
    Bindings bindings = new SimpleBindings();
    bindings.putAll(engineBindings);// w w w .j a va  2 s . c o m
    DependencyResolver dependencyResolver = new DependencyResolver(scriptResource, this, local);
    UseFunction useFunction = new UseFunction(dependencyResolver, arguments);
    bindings.put(Variables.JS_USE, useFunction);
    bindings.put(Variables.MODULE, commonJsModule);
    bindings.put(Variables.EXPORTS, commonJsModule.getExports());
    bindings.put(Variables.CONSOLE, new Console(LoggerFactory.getLogger(scriptResource.getName())));
    bindings.putAll(local);
    return bindings;
}

From source file:org.apache.felix.webconsole.plugins.scriptconsole.internal.ScriptConsolePlugin.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final String contentType = getContentType(req);
    resp.setContentType(contentType);//from w ww.j  a  v  a  2 s. c o  m
    if (contentType.startsWith("text/")) {
        resp.setCharacterEncoding("UTF-8");
    }
    final String script = getCodeValue(req);
    final Bindings bindings = new SimpleBindings();
    final PrintWriter pw = resp.getWriter();
    final ScriptHelper osgi = new ScriptHelper(getBundleContext());
    final Writer errorWriter = new LogWriter(log);
    final Reader reader = new StringReader(script);
    //Populate bindings
    bindings.put("request", req);
    bindings.put("reader", reader);
    bindings.put("response", resp);
    bindings.put("out", pw);
    bindings.put("osgi", osgi);

    //Also expose the bundleContext to simplify scripts interaction with the
    //enclosing OSGi container
    bindings.put("bundleContext", getBundleContext());

    final String lang = WebConsoleUtil.getParameter(req, "lang");
    final boolean webClient = "webconsole".equals(WebConsoleUtil.getParameter(req, "client"));

    SimpleScriptContext sc = new SimpleScriptContext();
    sc.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    sc.setWriter(pw);
    sc.setErrorWriter(errorWriter);
    sc.setReader(reader);

    try {
        log.log(LogService.LOG_DEBUG, "Executing script" + script);
        eval(script, lang, sc);
    } catch (Throwable t) {
        if (!webClient) {
            resp.setStatus(500);
        }
        pw.println(exceptionToString(t));
        log.log(LogService.LOG_ERROR, "Error in executing script", t);
    } finally {
        if (osgi != null) {
            osgi.cleanup();
        }
    }
}

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

@Test
public void shouldRaiseExceptionInWithResultOfLifeCycle() throws Exception {
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();
    final GremlinExecutor.LifeCycle lc = GremlinExecutor.LifeCycle.build().withResult(r -> {
        throw new RuntimeException("no worky");
    }).create();//from   w  w w  .ja  v  a 2s . c o m

    final AtomicBoolean exceptionRaised = new AtomicBoolean(false);

    final CompletableFuture<Object> future = gremlinExecutor.eval("1+1", "gremlin-groovy", new SimpleBindings(),
            lc);
    future.handle((r, t) -> {
        exceptionRaised.set(t != null && t instanceof RuntimeException && t.getMessage().equals("no worky"));
        return null;
    }).get();

    assertThat(exceptionRaised.get(), is(true));

    gremlinExecutor.close();
}

From source file:JrubyTest.java

/**
 * //w  ww  .j  av a  2s  . com
 * @throws Exception
 */
@Test
public void poi() throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("jruby");
    Reader scriptReader = null;
    InputStream in = null;
    try {
        in = getClass().getClassLoader().getResourceAsStream("sample1.xls");
        Workbook workbook = load(in);
        Book book = new Book(workbook);
        scriptReader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test.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 shouldMergeBindingsFromLocalAndGlobalWithMultiplePlugins() throws Exception {
    final ScriptEngines engines = new ScriptEngines(se -> {
    });/* w ww  .  j a va 2  s  . c  o m*/
    engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(),
            Collections.emptyMap());

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

        @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"));

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

        @Override
        public void pluginTo(final PluginAcceptor pluginAcceptor)
                throws IllegalEnvironmentException, PluginInitializationException {
            pluginAcceptor.addBinding("z", "where");
            pluginAcceptor.addImports(new HashSet<>(Arrays.asList("import java.awt.Color")));
        }
    }));

    assertEquals("heretherewhere", engines.eval("y+x+z", localBindings, "gremlin-groovy"));
    assertEquals(Color.RED, engines.eval("Color.RED", localBindings, "gremlin-groovy"));

}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTest.java

@Test
public void shouldPromoteDefinedVarsInInterpreterModeWithBindings() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(
            new InterpreterModeCustomizerProvider());
    final Bindings b = new SimpleBindings();
    b.put("x", 2);
    engine.eval("def addItUp = { x, y -> x + y }", b);
    assertEquals(3, engine.eval("int xxx = 1 + x", b));
    assertEquals(4, engine.eval("yyy = xxx + 1", b));
    assertEquals(7, engine.eval("def zzz = yyy + xxx", b));
    assertEquals(4, engine.eval("zzz - xxx", b));
    assertEquals("accessible-globally", engine.eval(
            "if (yyy > 0) { def inner = 'should-stay-local'; outer = 'accessible-globally' }\n outer", b));
    assertEquals("accessible-globally", engine.eval("outer", b));

    try {// w w w .  j  a v a2 s  .c  o m
        engine.eval("inner", b);
        fail("Should not have been able to access 'inner'");
    } catch (Exception ex) {
        final Throwable root = ExceptionUtils.getRootCause(ex);
        assertThat(root, instanceOf(MissingPropertyException.class));
    }

    assertEquals(10, engine.eval("addItUp(zzz,xxx)", b));
}