Search in sources :

Example 91 with Bindings

use of javax.script.Bindings in project es6draft by anba.

the class ScriptEngineScopeTest method globalScopeAccess.

@Test
public void globalScopeAccess() throws ScriptException {
    Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
    globalScope.put("globalVar", "Aldebaran");
    assertThat(engine.eval("globalVar"), instanceOfWith(String.class, is("Aldebaran")));
}
Also used : Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) Test(org.junit.Test)

Example 92 with Bindings

use of javax.script.Bindings in project frames by tinkerpop.

the class GremlinGroovyAnnotationHandler method processVertex.

public Object processVertex(final GremlinGroovy annotation, final Method method, final Object[] arguments, final FramedGraph framedGraph, final Vertex vertex) {
    try {
        final CompiledScript script = this.engine.compile(annotation.value());
        final Bindings bindings = getBindings(method, arguments);
        bindings.put(IT, vertex);
        bindings.put(G, framedGraph);
        final Object result = script.eval(bindings);
        // TODO: Deprecate the use of _() and replace with it
        if (result instanceof Pipe & annotation.value().startsWith(PIPE)) {
            LOGGER.warning("_() is deprecated in favor of using 'it' to represent the framed vertex");
            ((Pipe) result).setStarts(new SingleIterator<Element>(vertex));
        }
        if (annotation.frame()) {
            if (result instanceof Iterable) {
                final FramedVertexIterable r = new FramedVertexIterable(framedGraph, (Iterable) result, ClassUtilities.getGenericClass(method));
                return (ClassUtilities.returnsIterable(method)) ? r : r.iterator().hasNext() ? r.iterator().next() : null;
            } else if (ClassUtilities.returnsMap(method)) {
                return new FramedVertexMap(framedGraph, (Map) result, ClassUtilities.getGenericClass(method));
            } else if (result instanceof Vertex) {
                return framedGraph.frame((Vertex) result, ClassUtilities.getGenericClass(method));
            } else {
                throw new IllegalStateException("The returned object can not be framed: " + result.getClass());
            }
        } else {
            return result;
        }
    } catch (ScriptException e) {
        //Preserve original exception functionality.
        ExceptionUtils.sneakyThrow(e);
        return null;
    }
}
Also used : CompiledScript(javax.script.CompiledScript) Vertex(com.tinkerpop.blueprints.Vertex) FramedVertexIterable(com.tinkerpop.frames.structures.FramedVertexIterable) Element(com.tinkerpop.blueprints.Element) FramedVertexMap(com.tinkerpop.frames.structures.FramedVertexMap) Pipe(com.tinkerpop.pipes.Pipe) Bindings(javax.script.Bindings) ScriptException(javax.script.ScriptException) FramedVertexIterable(com.tinkerpop.frames.structures.FramedVertexIterable) Map(java.util.Map) FramedVertexMap(com.tinkerpop.frames.structures.FramedVertexMap)

Example 93 with Bindings

use of javax.script.Bindings in project gremlin by tinkerpop.

the class GremlinGroovyScriptEngineTest method testBlowTheHeap.

/**
     * Tries to force the out of memory exceptions that commonly seem to happen with scriptengine.
     */
public void testBlowTheHeap() throws ScriptException {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    final Graph g = TinkerGraphFactory.createTinkerGraph();
    final String[] gremlins = new String[] { "g.v(xxx).out.toList()", "g.v(xxx).in.toList()", "g.v(xxx).out.loop(1){true}{true}.toList()", "g.v(xxx).groupCount.cap.next()" };
    /******************START PARAMETERIZE GREMLIN***************
         * parameterized gremlin doesn't blow the heap
         */
    long parameterizedStartTime = System.currentTimeMillis();
    System.out.println("Try to blow the heap with parameterized Gremlin.");
    try {
        for (int ix = 0; ix < 50001; ix++) {
            final Bindings bindings = engine.createBindings();
            bindings.put("g", g);
            bindings.put("xxx", ((ix % 4) + 1));
            Object x = engine.eval(gremlins[ix % 4], bindings);
            if (ix > 0 && ix % 5000 == 0) {
                System.out.println(String.format("%s scripts processed in %s (ms) - rate %s (ms/q).", ix, System.currentTimeMillis() - parameterizedStartTime, Double.valueOf(System.currentTimeMillis() - parameterizedStartTime) / Double.valueOf(ix)));
            }
        }
    } catch (OutOfMemoryError oome) {
        assertTrue(false);
    }
    /*************************DONE PARAMETERIZE GREMLIN*****************/
    long notParameterizedStartTime = System.currentTimeMillis();
    System.out.println("Try to blow the heap with non-parameterized Gremlin.");
    try {
        for (int ix = 0; ix < 15001; ix++) {
            final Bindings bindings = engine.createBindings();
            bindings.put("g", g);
            engine.eval(String.format("g.v(%s)", ix), bindings);
            if (ix > 0 && ix % 5000 == 0) {
                System.out.println(String.format("%s scripts processed in %s (ms) - rate %s (ms/q).", ix, System.currentTimeMillis() - notParameterizedStartTime, Double.valueOf(System.currentTimeMillis() - notParameterizedStartTime) / Double.valueOf(ix)));
            }
        }
    } catch (OutOfMemoryError oome) {
        assertTrue(false);
    }
}
Also used : TinkerGraph(com.tinkerpop.blueprints.impls.tg.TinkerGraph) Graph(com.tinkerpop.blueprints.Graph) Bindings(javax.script.Bindings)

Example 94 with Bindings

use of javax.script.Bindings in project gremlin by tinkerpop.

the class GremlinGroovyScriptEngineTest method testFunctionsUsedInClosure.

public void testFunctionsUsedInClosure() throws ScriptException {
    GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    final Graph g = TinkerGraphFactory.createTinkerGraph();
    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    // 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.getVertex(2), engine.eval("def isVadas(v){v.name=='vadas'};g.V.filter{isVadas(it)}.next()", bindings));
    // let's reset this piece and make sure isVadas is not hanging around.
    engine = new GremlinGroovyScriptEngine();
    // validate that isVadas throws an exception since it is not defined
    try {
        engine.eval("isVadas(g.v(2))", 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
    engine.eval("def isVadas(v){v.name=='vadas'}", bindings);
    // make sure the function works on its own...no problem
    assertEquals(true, engine.eval("isVadas(g.v(2))", bindings));
    // make sure the function works in a closure...this generates a StackOverflowError
    assertEquals(g.getVertex(2), engine.eval("g.V.filter{isVadas(it)}.next()", bindings));
}
Also used : TinkerGraph(com.tinkerpop.blueprints.impls.tg.TinkerGraph) Graph(com.tinkerpop.blueprints.Graph) Bindings(javax.script.Bindings) ScriptException(javax.script.ScriptException)

Example 95 with Bindings

use of javax.script.Bindings in project gremlin by tinkerpop.

the class GremlinGroovyScriptEngineTest method testBindings.

public void testBindings() throws Exception {
    final TinkerGraph g = TinkerGraphFactory.createTinkerGraph();
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    assertTrue(engine.eval("g = TinkerGraphFactory.createTinkerGraph()") instanceof TinkerGraph);
    assertTrue(engine.get("g") instanceof TinkerGraph);
    assertEquals(engine.eval("g.v(1)"), g.getVertex(1));
    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(g.getEdge(7), engine.eval("g.E.has('weight',f).next()", bindings));
    assertEquals(g.getVertex(1), engine.eval("g.V.has('name',s).next()", bindings));
    assertEquals(g.getVertex(1), engine.eval("g.V.sideEffect{it.bbb=it.name=='marko'}.iterate();g.V.has('bbb',b).next()", bindings));
    assertEquals(g.getVertex(1), engine.eval("g.V.sideEffect{it.iii=it.name=='marko'?1:0}.iterate();g.V.has('iii',i).next()", bindings));
    assertEquals(g.getVertex(1), engine.eval("g.V.sideEffect{it.lll=it.name=='marko'?100l:0l}.iterate();g.V.has('lll',l).next()", bindings));
    assertEquals(g.getVertex(1), engine.eval("g.V.sideEffect{it.ddd=it.name=='marko'?1.55555d:0}.iterate();g.V.has('ddd',d).next()", bindings));
}
Also used : TinkerGraph(com.tinkerpop.blueprints.impls.tg.TinkerGraph) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine)

Aggregations

Bindings (javax.script.Bindings)150 SimpleBindings (javax.script.SimpleBindings)77 Test (org.junit.Test)36 ScriptException (javax.script.ScriptException)30 ScriptContext (javax.script.ScriptContext)26 SimpleScriptContext (javax.script.SimpleScriptContext)24 ScriptEngine (javax.script.ScriptEngine)20 SlingBindings (org.apache.sling.api.scripting.SlingBindings)18 Test (org.testng.annotations.Test)17 CompiledScript (javax.script.CompiledScript)14 Resource (org.apache.sling.api.resource.Resource)11 Map (java.util.Map)10 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)10 SlingScriptHelper (org.apache.sling.api.scripting.SlingScriptHelper)10 IOException (java.io.IOException)9 HashMap (java.util.HashMap)9 ScriptEngineManager (javax.script.ScriptEngineManager)9 PrintWriter (java.io.PrintWriter)8 StringWriter (java.io.StringWriter)8 ArrayList (java.util.ArrayList)7