Example usage for javax.script Bindings put

List of usage examples for javax.script Bindings put

Introduction

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

Prototype

public Object put(String name, Object value);

Source Link

Document

Set a named value.

Usage

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.CLASSIC)
public void shouldProperlyHandleBindings() throws Exception {
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.put("g", g);
    engine.put("marko", convertToVertexId("marko"));
    Assert.assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()"));

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("s", "marko");
    bindings.put("f", 0.5f);
    bindings.put("i", 1);
    bindings.put("b", true);
    bindings.put("l", 100l);
    bindings.put("d", 1.55555d);

    assertEquals(engine.eval("g.E().has('weight',f).next()", bindings),
            g.E(convertToEdgeId("marko", "knows", "vadas")).next());
    assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next());
    assertEquals(engine.eval(//from  ww  w .ja  v a 2  s . c o m
            "g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()",
            bindings), g.V(convertToVertexId("marko")).next());
    assertEquals(engine.eval(
            "g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()",
            bindings), g.V(convertToVertexId("marko")).next());
    assertEquals(engine.eval(
            "g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()",
            bindings), g.V(convertToVertexId("marko")).next());
    assertEquals(engine.eval(
            "g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()",
            bindings), g.V(convertToVertexId("marko")).next());
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAllowFunctionsUsedInClosure() throws ScriptException {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("#jsr223.groovy.engine.keep.globals", "phantom");
    bindings.put("vadas", convertToVertexId("vadas"));

    // this works on its own when the function and the line that uses it is in one "script".  this is the
    // current workaround
    assertEquals(g.V(convertToVertexId("vadas")).next(), engine
            .eval("def isVadas(v){v.value('name')=='vadas'};g.V().filter{isVadas(it.get())}.next()", bindings));

    // let's reset this piece and make sure isVadas is not hanging around.
    engine.reset();//from   w  w w.  j  a v  a2s. com

    // validate that isVadas throws an exception since it is not defined
    try {
        engine.eval("isVadas(g.V(vadas).next())", bindings);

        // fail the test if the above doesn't throw an exception
        fail();
    } catch (Exception ex) {
        // this is good...we want this. it means isVadas isn't hanging about
    }

    // now...define the function separately on its own in one script
    bindings.remove("#jsr223.groovy.engine.keep.globals");
    engine.eval("def isVadas(v){v.value('name')=='vadas'}", bindings);

    // make sure the function works on its own...no problem
    assertEquals(true, engine.eval("isVadas(g.V(vadas).next())", bindings));

    // make sure the function works in a closure...this generates a StackOverflowError
    assertEquals(g.V(convertToVertexId("vadas")).next(),
            engine.eval("g.V().filter{isVadas(it.get())}.next()", bindings));
}

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

@Test
public void shouldEvalWithBindings() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    final Bindings b = new SimpleBindings();
    b.put("x", 2);
    assertEquals(3, engine.eval("1+x", b));
}

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

@Test
public void shouldEvalWithNullInBindings() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    final Bindings b = new SimpleBindings();
    b.put("x", null);
    assertNull(engine.eval("x", b));
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldEvalGlobalClosuresEvenAfterEvictionOfClass() throws ScriptException {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId("marko"));
    bindings.put("vadas", convertToVertexId("vadas"));

    // strong referenced global closure
    engine.eval("def isVadas(v){v.value('name')=='vadas'}", bindings);
    assertEquals(true, engine.eval("isVadas(g.V(vadas).next())", bindings));

    // phantom referenced global closure
    bindings.put(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE,
            GremlinGroovyScriptEngine.REFERENCE_TYPE_PHANTOM);
    engine.eval("def isMarko(v){v.value('name')=='marko'}", bindings);

    try {/*from   w  w w .ja v a 2  s .com*/
        engine.eval("isMarko(g.V(marko).next())", bindings);
        fail("the isMarko function should not be present");
    } catch (Exception ex) {

    }

    assertEquals(true,
            engine.eval("def isMarko(v){v.value('name')=='marko'}; isMarko(g.V(marko).next())", bindings));

    try {
        engine.eval("isMarko(g.V(marko" + ").next())", bindings);
        fail("the isMarko function should not be present");
    } catch (Exception ex) {

    }

    bindings.remove(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE);

    // isVadas class was a hard reference so it should still be hanging about
    assertEquals(true, engine.eval("isVadas(g.V(vadas).next())", bindings));
}

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

@Test
@org.junit.Ignore//from w  ww  .  ja va 2s  . c  om
@LoadGraphWith(LoadGraphWith.GraphData.CLASSIC)
public void shouldAllowUseOfClasses() throws ScriptException {
    GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("vadas", convertToVertexId("vadas"));

    // works when it's all defined together
    assertEquals(true,
            engine.eval(
                    "class c { static def isVadas(v){v.value('name')=='vadas'}};c.isVadas(g.V(vadas).next())",
                    bindings));

    // let's reset this piece and make sure isVadas is not hanging around.
    engine.reset();

    // validate that isVadas throws an exception since it is not defined
    try {
        engine.eval("c.isVadas(g.V(vadas).next())", bindings);

        // fail the test if the above doesn't throw an exception
        fail("Function should be gone");
    } catch (Exception ex) {
        // this is good...we want this. it means isVadas isn't hanging about
    }

    // now...define the class separately on its own in one script...
    // HERE'S an AWKWARD BIT.........
    // YOU HAVE TO END WITH: null;
    // ....OR ELSE YOU GET:
    // javax.script.ScriptException: javax.script.ScriptException:
    // org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack: No signature of method: c.main()
    // is applicable for argument types: ([Ljava.lang.String;) values: [[]]
    // WOULD BE NICE IF WE DIDN'T HAVE TO DO THAT
    engine.eval("class c { static def isVadas(v){v.name=='vadas'}};null;", bindings);

    // make sure the class works on its own...this generates: groovy.lang.MissingPropertyException: No such property: c for class: Script2
    assertEquals(true, engine.eval("c.isVadas(g.V(vadas).next())", bindings));
}

From source file:org.apache.nifi.processors.script.ExecuteScript.java

/**
 * Evaluates the given script body (or file) using the current session, context, and flowfile. The script
 * evaluation expects a FlowFile to be returned, in which case it will route the FlowFile to success. If a script
 * error occurs, the original FlowFile will be routed to failure. If the script succeeds but does not return a
 * FlowFile, the original FlowFile will be routed to no-flowfile
 *
 * @param context        the current process context
 * @param sessionFactory provides access to a {@link ProcessSessionFactory}, which
 *                       can be used for accessing FlowFiles, etc.
 * @throws ProcessException if the scripted processor's onTrigger() method throws an exception
 *///from w  ww.j  a v a 2  s.  c  om
@Override
public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll();
    ComponentLog log = getLogger();
    if (scriptEngine == null) {
        // No engine available so nothing more to do here
        return;
    }
    ProcessSession session = sessionFactory.createSession();
    try {

        try {
            Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            if (bindings == null) {
                bindings = new SimpleBindings();
            }
            bindings.put("session", session);
            bindings.put("context", context);
            bindings.put("log", log);
            bindings.put("REL_SUCCESS", REL_SUCCESS);
            bindings.put("REL_FAILURE", REL_FAILURE);

            // Find the user-added properties and set them on the script
            for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
                if (property.getKey().isDynamic()) {
                    // Add the dynamic property bound to its full PropertyValue to the script engine
                    if (property.getValue() != null) {
                        bindings.put(property.getKey().getName(), context.getProperty(property.getKey()));
                    }
                }
            }

            scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

            // Execute any engine-specific configuration before the script is evaluated
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap
                    .get(scriptingComponentHelper.getScriptEngineName().toLowerCase());

            // Evaluate the script with the configurator (if it exists) or the engine
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules());
            } else {
                scriptEngine.eval(scriptToRun);
            }

            // Commit this session for the user. This plus the outermost catch statement mimics the behavior
            // of AbstractProcessor. This class doesn't extend AbstractProcessor in order to share a base
            // class with InvokeScriptedProcessor
            session.commit();
        } catch (ScriptException e) {
            throw new ProcessException(e);
        }
    } catch (final Throwable t) {
        // Mimic AbstractProcessor behavior here
        getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t });
        session.rollback(true);
        throw t;
    } finally {
        scriptingComponentHelper.engineQ.offer(scriptEngine);
    }
}

From source file:org.mule.module.scripting.component.Scriptable.java

public void populateBindings(Bindings bindings, MuleEvent event) {
    populateBindings(bindings, event.getMessage());
    bindings.put("originalPayload", event.getMessage().getPayload());
    bindings.put("payload", event.getMessage().getPayload());
    bindings.put("eventContext", new DefaultMuleEventContext(event));
    bindings.put("id", event.getId());
    bindings.put("flowConstruct", event.getFlowConstruct());
    if (event.getFlowConstruct() instanceof Service) {
        bindings.put("service", event.getFlowConstruct());
    }/*  w  ww .ja v  a2  s.  c  o  m*/
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldBeThreadSafe() throws Exception {
    final ScriptEngine engine = new GremlinGroovyScriptEngine();

    int runs = 500;
    final CountDownLatch latch = new CountDownLatch(runs);
    final List<String> names = Arrays.asList("marko", "peter", "josh", "vadas", "stephen", "pavel", "matthias");
    final Random random = new Random();

    for (int i = 0; i < runs; i++) {
        new Thread("test-thread-safe-" + i) {
            public void run() {
                String name = names.get(random.nextInt(names.size() - 1));
                try {
                    final Bindings bindings = engine.createBindings();
                    bindings.put("g", g);
                    bindings.put("name", name);
                    final Object result = engine
                            .eval("t = g.V().has('name',name); if(t.hasNext()) { t } else { null }", bindings);
                    if (name.equals("stephen") || name.equals("pavel") || name.equals("matthias"))
                        assertNull(result);
                    else
                        assertNotNull(result);
                } catch (ScriptException e) {
                    assertFalse(true);// w ww .  jav a  2 s. c  om
                } finally {
                    if (graph.features().graph().supportsTransactions())
                        g.tx().rollback();
                }
                latch.countDown();
            }
        }.start();
    }
    latch.await();
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldBeThreadSafeOnCompiledScript() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    final CompiledScript script = engine
            .compile("t = g.V().has('name',name); if(t.hasNext()) { t } else { null }");

    int runs = 500;
    final CountDownLatch latch = new CountDownLatch(runs);
    final List<String> names = Arrays.asList("marko", "peter", "josh", "vadas", "stephen", "pavel", "matthias");
    final Random random = new Random();

    for (int i = 0; i < runs; i++) {
        new Thread("test-thread-safety-on-compiled-script-" + i) {
            public void run() {
                String name = names.get(random.nextInt(names.size() - 1));
                try {
                    final Bindings bindings = engine.createBindings();
                    bindings.put("g", g);
                    bindings.put("name", name);
                    Object result = script.eval(bindings);
                    if (name.equals("stephen") || name.equals("pavel") || name.equals("matthias"))
                        assertNull(result);
                    else
                        assertNotNull(result);
                } catch (ScriptException e) {
                    //System.out.println(e);
                    assertFalse(true);/*from   w w w .  jav  a  2s . c o m*/
                } finally {
                    if (graph.features().graph().supportsTransactions())
                        g.tx().rollback();
                }
                latch.countDown();
            }
        }.start();
    }
    latch.await();
}