Java Code Examples for org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph#traversal()

The following examples show how to use org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph#traversal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIncludeCustomTypeTranslationForSomethingSilly() throws Exception {
    final TinkerGraph graph = TinkerGraph.open();
    final SillyClass notSillyEnough = SillyClass.from("not silly enough", 100);
    final GraphTraversalSource g = graph.traversal();

    // without type translation we get uglinesss
    final String scriptBad = GroovyTranslator.of("g").
            translate(g.inject(notSillyEnough).asAdmin().getBytecode()).getScript();
    assertEquals(String.format("g.inject(%s)", "not silly enough:100"), scriptBad);

    // with type translation we get valid gremlin
    final String scriptGood = GroovyTranslator.of("g", new SillyClassTranslator(false)).
            translate(g.inject(notSillyEnough).asAdmin().getBytecode()).getScript();
    assertEquals(String.format("g.inject(org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslatorTest.SillyClass.from('%s', (int) %s))", notSillyEnough.getX(), notSillyEnough.getY()), scriptGood);
    assertThatScriptOk(scriptGood, "g", g);

    final GremlinGroovyScriptEngine customEngine = new GremlinGroovyScriptEngine(new SillyClassTranslatorCustomizer());
    final Bindings b = new SimpleBindings();
    b.put("g", g);
    final Traversal t = customEngine.eval(g.inject(notSillyEnough).asAdmin().getBytecode(), b, "g");
    final SillyClass sc = (SillyClass) t.next();
    assertEquals(notSillyEnough.getX(), sc.getX());
    assertEquals(notSillyEnough.getY(), sc.getY());
    assertThat(t.hasNext(), is(false));
}
 
Example 2
Source File: GraphSONMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(map).create());
    final JsonNode json = mapper.readTree(results);

    assertNotNull(json);
    assertEquals(msg.getRequestId().toString(), json.get(SerTokens.TOKEN_REQUEST).asText());
    final JsonNode converted = json.get(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA);

    assertNotNull(converted);

    // with no embedded types the key (which is a vertex) simply serializes out to an id
    // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
    assertEquals(1000, converted.get("1").asInt());
}
 
Example 3
Source File: GroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleConfusingSacks() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();

    final Traversal<Vertex,Double> tConstantUnary = g.withSack(1.0, Lambda.unaryOperator("it + 1")).V().sack();
    final String scriptConstantUnary = GroovyTranslator.of("g").translate(tConstantUnary.asAdmin().getBytecode()).getScript();
    assertEquals("g.withSack(1.0d, (java.util.function.UnaryOperator) {it + 1}).V().sack()", scriptConstantUnary);
    assertThatScriptOk(scriptConstantUnary, "g", g);

    final Traversal<Vertex,Double> tSupplierUnary = g.withSack(Lambda.supplier("1.0d"), Lambda.<Double>unaryOperator("it + 1")).V().sack();
    final String scriptSupplierUnary = GroovyTranslator.of("g").translate(tSupplierUnary.asAdmin().getBytecode()).getScript();
    assertEquals("g.withSack((java.util.function.Supplier) {1.0d}, (java.util.function.UnaryOperator) {it + 1}).V().sack()", scriptSupplierUnary);
    assertThatScriptOk(scriptSupplierUnary, "g", g);

    final Traversal<Vertex,Double> tConstantBinary = g.withSack(1.0, Lambda.binaryOperator("x,y -> x + y + 1")).V().sack();
    final String scriptConstantBinary = GroovyTranslator.of("g").translate(tConstantBinary.asAdmin().getBytecode()).getScript();
    assertEquals("g.withSack(1.0d, (java.util.function.BinaryOperator) {x,y -> x + y + 1}).V().sack()", scriptConstantBinary);
    assertThatScriptOk(scriptConstantBinary, "g", g);

    final Traversal<Vertex,Double> tSupplierBinary = g.withSack(Lambda.supplier("1.0d"), Lambda.<Double>binaryOperator("x,y -> x + y + 1")).V().sack();
    final String scriptSupplierBinary = GroovyTranslator.of("g").translate(tSupplierBinary.asAdmin().getBytecode()).getScript();
    assertEquals("g.withSack((java.util.function.Supplier) {1.0d}, (java.util.function.BinaryOperator) {x,y -> x + y + 1}).V().sack()", scriptSupplierBinary);
    assertThatScriptOk(scriptSupplierBinary, "g", g);
}
 
Example 4
Source File: GraphSONMessageSerializerV2d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(map).create());
    final JsonNode json = mapper.readTree(results);

    assertNotNull(json);
    assertEquals(msg.getRequestId().toString(), json.get(SerTokens.TOKEN_REQUEST).asText());
    final JsonNode converted = json.get(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA);

    assertNotNull(converted);

    // with no embedded types the key (which is a vertex) simply serializes out to an id
    // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
    assertEquals(1000, converted.get("1").get(GraphSONTokens.VALUEPROP).asInt());
}
 
Example 5
Source File: GroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEscapeStrings() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final String script = GroovyTranslator.of("g").translate(g.addV("customer")
            .property("customer_id", 501L)
            .property("name", "Foo\u0020Bar")
            .property("age", 25)
            .property("special", "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?")
            .asAdmin().getBytecode()).getScript();

    assertEquals("g.addV(\"customer\")" +
                    ".property(\"customer_id\",501L)" +
                    ".property(\"name\",\"Foo Bar\")" +
                    ".property(\"age\",(int) 25)" +
                    ".property(\"special\",\"\"\"`~!@#\\$%^&*()-_=+[{]}\\\\|;:'\\\",<.>/?\"\"\")",
            script);
}
 
Example 6
Source File: GryoLiteMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final ResponseMessage response = convertBinary(map);
    assertCommon(response);

    final Map<Vertex, Integer> deserializedMap = (Map<Vertex, Integer>) response.getResult().getData();
    assertEquals(1, deserializedMap.size());

    final Vertex deserializedMarko = deserializedMap.keySet().iterator().next();
    assertEquals(0, IteratorUtils.count(deserializedMarko.properties()));
    assertEquals(1, deserializedMarko.id());
    assertEquals(Vertex.DEFAULT_LABEL, deserializedMarko.label());

    assertEquals(new Integer(1000), deserializedMap.values().iterator().next());
}
 
Example 7
Source File: GraphSONMessageSerializerGremlinV2d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final ResponseMessage response = convert(map);
    assertCommon(response);

    final Map<String, Integer> deserializedMap = (Map<String, Integer>) response.getResult().getData();
    assertEquals(1, deserializedMap.size());

    // with no embedded types the key (which is a vertex) simply serializes out to an id
    // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
    assertEquals(new Integer(1000), deserializedMap.get("1"));
}
 
Example 8
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleMaps() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final Script script = GroovyTranslator.of("g", true).translate(g.V().id().is(new LinkedHashMap<Object,Object>() {{
        put(3, "32");
        put(Arrays.asList(1, 2, 3.1d), 4);
    }}).asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(6, bindings.size());
    assertEquals(Integer.valueOf(3), bindings.get("_args_0"));
    assertEquals("32", bindings.get("_args_1"));
    assertEquals(Integer.valueOf(1), bindings.get("_args_2"));
    assertEquals(Integer.valueOf(2), bindings.get("_args_3"));
    assertEquals(Double.valueOf(3.1), bindings.get("_args_4"));
    assertEquals(Integer.valueOf(4), bindings.get("_args_5"));
    assertEquals("g.V().id().is([(_args_0):(_args_1),([_args_2, _args_3, _args_4]):(_args_5)])", script.getScript());
    final Script standard = GroovyTranslator.of("g").translate(g.V().id().is(new LinkedHashMap<Object,Object>() {{
        put(3, "32");
        put(Arrays.asList(1, 2, 3.1d), 4);
    }}).asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard.getScript(), script.getScript(), bindings, true);
}
 
Example 9
Source File: GremlinExecutorOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAllowTraversalToIterateInDifferentThreadThanOriginallyEvaluatedWithAutoCommit() throws Exception {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();

    // this test sort of simulates Gremlin Server interaction where a Traversal is eval'd in one Thread, but
    // then iterated in another.  note that Gremlin Server configures the script engine to auto-commit
    // after evaluation.  this basically tests the state of the Gremlin Server GremlinExecutor when
    // being used in sessionless mode
    final ExecutorService evalExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build()
            .afterSuccess(b -> {
                final GraphTraversalSource ig = (GraphTraversalSource) b.get("g");
                if (ig.getGraph().features().graph().supportsTransactions())
                    ig.tx().commit();
            })
            .executorService(evalExecutor).create();

    final Map<String,Object> bindings = new HashMap<>();
    bindings.put("g", g);

    final AtomicInteger vertexCount = new AtomicInteger(0);

    final ExecutorService iterationExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    gremlinExecutor.eval("g.V().out()", bindings).thenAcceptAsync(o -> {
        final Iterator itty = (Iterator) o;
        itty.forEachRemaining(v -> vertexCount.incrementAndGet());
    }, iterationExecutor).join();

    assertEquals(6, vertexCount.get());

    gremlinExecutor.close();
    evalExecutor.shutdown();
    evalExecutor.awaitTermination(30000, TimeUnit.MILLISECONDS);
    iterationExecutor.shutdown();
    iterationExecutor.awaitTermination(30000, TimeUnit.MILLISECONDS);
}
 
Example 10
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEscapeStrings() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final Script script = GroovyTranslator.of("g", true).translate(g.addV("customer")
            .property("customer_id", 501L)
            .property("name", "Foo\u0020Bar")
            .property("age", 25)
            .property("special", "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?")
            .asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(9, bindings.size());
    assertEquals("customer", bindings.get("_args_0"));
    assertEquals("customer_id", bindings.get("_args_1"));
    assertEquals(Long.valueOf(501), bindings.get("_args_2"));
    assertEquals("name", bindings.get("_args_3"));
    assertEquals("Foo\u0020Bar", bindings.get("_args_4"));
    assertEquals("age", bindings.get("_args_5"));
    assertEquals(Integer.valueOf(25), bindings.get("_args_6"));
    assertEquals("special", bindings.get("_args_7"));
    assertEquals("`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?", bindings.get("_args_8"));
    assertEquals("g.addV(_args_0).property(_args_1,_args_2).property(_args_3,_args_4).property(_args_5,_args_6).property(_args_7,_args_8)", script.getScript());

    final Script standard = GroovyTranslator.of("g").translate(g.addV("customer")
            .property("customer_id", 501L)
            .property("name", "Foo\u0020Bar")
            .property("age", 25)
            .property("special", "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?")
            .asAdmin().getBytecode());

    bindings.put("g", g);
    //add vertex will return different vertex id
    assertParameterizedScriptOk(standard.getScript(), script.getScript(), bindings, false);
}
 
Example 11
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleEmptyMaps() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final Function identity = new Lambda.OneArgLambda("it.get()", "gremlin-groovy");
    final Script script = GroovyTranslator.of("g", true).translate(g.inject(Collections.emptyMap()).map(identity).asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(1, bindings.size());
    assertEquals(identity, bindings.get("_args_0"));
    assertEquals("g.inject([]).map(_args_0)", script.getScript());
    bindings.put("g", g);
    assertThatScriptOk(script.getScript(), bindings);
}
 
Example 12
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleSet() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final Script script = GroovyTranslator.of("g", true).translate(g.V().id().is(new HashSet<Object>() {{
        add(3);
        add(Arrays.asList(1, 2, 3.1d));
        add(3);
        add("3");
    }}).asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(5, bindings.size());
    assertEquals(Integer.valueOf(3), bindings.get("_args_0"));
    assertEquals("3", bindings.get("_args_1"));
    assertEquals(Integer.valueOf(1), bindings.get("_args_2"));
    assertEquals(Integer.valueOf(2), bindings.get("_args_3"));
    assertEquals(Double.valueOf(3.1), bindings.get("_args_4"));
    assertEquals("g.V().id().is([_args_0, _args_1, [_args_2, _args_3, _args_4]] as Set)", script.getScript());

    final Script standard = GroovyTranslator.of("g" ).translate(g.V().id().is(new HashSet<Object>() {{
        add(3);
        add(Arrays.asList(1, 2, 3.1d));
        add(3);
        add("3");
    }}).asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard.getScript(), script.getScript(), bindings, true);
}
 
Example 13
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleArray() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final Script script = GroovyTranslator.of("g", true).translate(g.V().has(T.id, P.within(new ArrayList() {{
        add(1);
        add(2);
        add(3);
        add(4);
        add(5);
    }})).asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(5, bindings.size());
    assertEquals(Integer.valueOf(1), bindings.get("_args_0"));
    assertEquals(Integer.valueOf(2), bindings.get("_args_1"));
    assertEquals(Integer.valueOf(3), bindings.get("_args_2"));
    assertEquals(Integer.valueOf(4), bindings.get("_args_3"));
    assertEquals(Integer.valueOf(5), bindings.get("_args_4"));
    assertEquals("g.V().has(T.id,P.within([_args_0, _args_1, _args_2, _args_3, _args_4]))", script.getScript());

    final Script standard = GroovyTranslator.of("g").translate(g.V().has(T.id, P.within(new ArrayList() {{
        add(1);
        add(2);
        add(3);
        add(4);
        add(5);
    }})).asAdmin().getBytecode());

    bindings.put("g", g);
    assertParameterizedScriptOk(standard.getScript(), script.getScript(), bindings, true);
}
 
Example 14
Source File: GremlinExecutorOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAllowTraversalToIterateInDifferentThreadThanOriginallyEvaluatedWithoutAutoCommit() throws Exception {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();

    // this test sort of simulates Gremlin Server interaction where a Traversal is eval'd in one Thread, but
    // then iterated in another.  this basically tests the state of the Gremlin Server GremlinExecutor when
    // being used in session mode
    final ExecutorService evalExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().executorService(evalExecutor).create();

    final Map<String,Object> bindings = new HashMap<>();
    bindings.put("g", g);

    final AtomicInteger vertexCount = new AtomicInteger(0);

    final ExecutorService iterationExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    gremlinExecutor.eval("g.V().out()", bindings).thenAcceptAsync(o -> {
        final Iterator itty = (Iterator) o;
        itty.forEachRemaining(v -> vertexCount.incrementAndGet());
    }, iterationExecutor).join();

    assertEquals(6, vertexCount.get());

    gremlinExecutor.close();
    evalExecutor.shutdown();
    evalExecutor.awaitTermination(30000, TimeUnit.MILLISECONDS);
    iterationExecutor.shutdown();
    iterationExecutor.awaitTermination(30000, TimeUnit.MILLISECONDS);
}
 
Example 15
Source File: AppTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateGraph() {
    TinkerGraph graph = TinkerGraph.open();
    App.loadData(graph);

    GraphTraversalSource g = graph.traversal();

    assertEquals(6, g.V().count().next().intValue());
    assertEquals(6, g.E().count().next().intValue());
}
 
Example 16
Source File: GroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleMaps() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final String script = GroovyTranslator.of("g").translate(g.V().id().is(new LinkedHashMap<Object,Object>() {{
        put(3, "32");
        put(Arrays.asList(1, 2, 3.1d), 4);
    }}).asAdmin().getBytecode()).getScript();
    assertEquals("g.V().id().is([((int) 3):(\"32\"),([(int) 1, (int) 2, 3.1d]):((int) 4)])", script);
    assertThatScriptOk(script, "g", g);
}
 
Example 17
Source File: GraphSONMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeToJsonTree() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Tree t = g.V(1).out().properties("name").tree().next();

    
    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(t).create());

    final JsonNode json = mapper.readTree(results);

    assertNotNull(json);
    assertEquals(msg.getRequestId().toString(), json.get(SerTokens.TOKEN_REQUEST).asText());
    final JsonNode converted = json.get(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA);
    assertNotNull(converted);
    
    //check the first object and it's properties
    assertEquals(1, converted.get("1").get("key").get("id").asInt());
    assertEquals("marko", converted.get("1").get("key").get("properties").get("name").get(0).get("value").asText());
    
    //check objects tree structure
    //check Vertex property
    assertEquals("vadas", converted.get("1")
                             .get("value")
                             .get("2")
                             .get("value")
                             .get("3").get("key").get("value").asText());
    assertEquals("name", converted.get("1")
                             .get("value")
                             .get("2")
                             .get("value")
                             .get("3").get("key").get("label").asText());
    
    // check subitem
    assertEquals("lop", converted.get("1")
                             .get("value")
                             .get("3")
                             .get("key")
                             .get("properties").get("name").get(0).get("value").asText());
}
 
Example 18
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldSupportStringSupplierLambdas() {
    final TinkerGraph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal();
    g = g.withStrategies(new TranslationStrategy(g, GroovyTranslator.of("g", true), false));
    final GraphTraversal.Admin<Vertex, Integer> t = g.withSideEffect("lengthSum", 0).withSack(1)
            .V()
            .filter(Lambda.predicate("it.get().label().equals('person')"))
            .flatMap(Lambda.function("it.get().vertices(Direction.OUT)"))
            .map(Lambda.<Traverser<Object>, Integer>function("it.get().value('name').length()"))
            .sideEffect(Lambda.consumer("{ x -> x.sideEffects(\"lengthSum\", x.<Integer>sideEffects('lengthSum') + x.get()) }"))
            .order().by(Lambda.comparator("a,b -> a <=> b"))
            .sack(Lambda.biFunction("{ a,b -> a + b }"))
            .asAdmin();

    final List<Integer> sacks = new ArrayList<>();
    final List<Integer> lengths = new ArrayList<>();
    while (t.hasNext()) {
        final Traverser.Admin<Integer> traverser = t.nextTraverser();
        sacks.add(traverser.sack());
        lengths.add(traverser.get());
    }
    assertFalse(t.hasNext());
    //
    assertEquals(6, lengths.size());
    assertEquals(3, lengths.get(0).intValue());
    assertEquals(3, lengths.get(1).intValue());
    assertEquals(3, lengths.get(2).intValue());
    assertEquals(4, lengths.get(3).intValue());
    assertEquals(5, lengths.get(4).intValue());
    assertEquals(6, lengths.get(5).intValue());
    ///
    assertEquals(6, sacks.size());
    assertEquals(4, sacks.get(0).intValue());
    assertEquals(4, sacks.get(1).intValue());
    assertEquals(4, sacks.get(2).intValue());
    assertEquals(5, sacks.get(3).intValue());
    assertEquals(6, sacks.get(4).intValue());
    assertEquals(7, sacks.get(5).intValue());
    //
    assertEquals(24, t.getSideEffects().<Number>get("lengthSum").intValue());

    final Script script = GroovyTranslator.of("g", true).translate(t.getBytecode());
    Bindings bindings = new SimpleBindings();
    script.getParameters().ifPresent(bindings::putAll);
    assertEquals(9, bindings.size());
    assertEquals("lengthSum", bindings.get("_args_0"));
    assertEquals(Integer.valueOf(0), bindings.get("_args_1"));
    assertEquals(Integer.valueOf(1), bindings.get("_args_2"));
    assertEquals(Lambda.predicate("it.get().label().equals('person')"), bindings.get("_args_3"));
    assertEquals(Lambda.function("it.get().vertices(Direction.OUT)"), bindings.get("_args_4"));
    assertEquals(Lambda.<Traverser<Object>, Integer>function("it.get().value('name').length()"), bindings.get("_args_5"));
    assertEquals(Lambda.consumer("{ x -> x.sideEffects(\"lengthSum\", x.<Integer>sideEffects('lengthSum') + x.get()) }"), bindings.get("_args_6"));
    assertEquals(Lambda.comparator("a,b -> a <=> b"), bindings.get("_args_7"));
    assertEquals(Lambda.biFunction("{ a,b -> a + b }"), bindings.get("_args_8"));
    assertEquals("g.withStrategies(org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.TranslationStrategy.instance())" +
                    ".withSideEffect(_args_0,_args_1).withSack(_args_2)" +
                    ".V()" +
                    ".filter(_args_3)" +
                    ".flatMap(_args_4)" +
                    ".map(_args_5)" +
                    ".sideEffect(_args_6)" +
                    ".order().by(_args_7)" +
                    ".sack(_args_8)",
            script.getScript());
}
 
Example 19
Source File: GroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldHandleVertexAndEdge() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();

    final Object id1 = "customer:10:foo\u0020bar\u0020\u0024100#90"; // customer:10:foo bar $100#90
    final Vertex vertex1 = DetachedVertex.build().setLabel("customer").setId(id1)
            .create();
    final String script1 = GroovyTranslator.of("g").translate(g.inject(vertex1).asAdmin().getBytecode()).getScript();
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(" +
                    "\"customer:10:foo bar \\$100#90\"," +
                    "\"customer\", Collections.emptyMap()))",
            script1);
    assertThatScriptOk(script1, "g", g);

    final Object id2 = "user:20:foo\\u0020bar\\u005c\\u0022mr\\u005c\\u0022\\u00241000#50"; // user:20:foo\u0020bar\u005c\u0022mr\u005c\u0022\u00241000#50
    final Vertex vertex2 = DetachedVertex.build().setLabel("user").setId(id2)
            .create();
    final String script2 = GroovyTranslator.of("g").translate(g.inject(vertex2).asAdmin().getBytecode()).getScript();
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(" +
                    "\"user:20:foo\\\\u0020bar\\\\u005c\\\\u0022mr\\\\u005c\\\\u0022\\\\u00241000#50\"," +
                    "\"user\", Collections.emptyMap()))",
            script2);
    assertThatScriptOk(script2, "g", g);

    final Object id3 = "knows:30:foo\u0020bar\u0020\u0024100:\\u0020\\u0024500#70";
    final Edge edge = DetachedEdge.build().setLabel("knows").setId(id3)
            .setOutV((DetachedVertex) vertex1)
            .setInV((DetachedVertex) vertex2)
            .create();
    final String script3 = GroovyTranslator.of("g").translate(g.inject(edge).asAdmin().getBytecode()).getScript();
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge(" +
                    "\"knows:30:foo bar \\$100:\\\\u0020\\\\u0024500#70\"," +
                    "\"knows\",Collections.emptyMap()," +
                    "\"customer:10:foo bar \\$100#90\",\"customer\"," +
                    "\"user:20:foo\\\\u0020bar\\\\u005c\\\\u0022mr\\\\u005c\\\\u0022\\\\u00241000#50\",\"user\"))",
            script3);
    assertThatScriptOk(script3, "g", g);

    final String script4 = GroovyTranslator.of("g").translate(
            g.addE("knows").from(vertex1).to(vertex2).property("when", "2018/09/21")
                    .asAdmin().getBytecode()).getScript();
    assertEquals("g.addE(\"knows\")" +
                    ".from(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(\"customer:10:foo bar \\$100#90\",\"customer\", Collections.emptyMap()))" +
                    ".to(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(\"user:20:foo\\\\u0020bar\\\\u005c\\\\u0022mr\\\\u005c\\\\u0022\\\\u00241000#50\",\"user\", Collections.emptyMap()))" +
                    ".property(\"when\",\"2018/09/21\")",
            script4);
}
 
Example 20
Source File: GroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldSupportStringSupplierLambdas() {
    final TinkerGraph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal();
    g = g.withStrategies(new TranslationStrategy(g, GroovyTranslator.of("g"), false));
    final GraphTraversal.Admin<Vertex, Integer> t = g.withSideEffect("lengthSum", 0).withSack(1)
            .V()
            .filter(Lambda.predicate("it.get().label().equals('person')"))
            .flatMap(Lambda.function("it.get().vertices(Direction.OUT)"))
            .map(Lambda.<Traverser<Object>, Integer>function("it.get().value('name').length()"))
            .sideEffect(Lambda.consumer("{ x -> x.sideEffects(\"lengthSum\", x.<Integer>sideEffects('lengthSum') + x.get()) }"))
            .order().by(Lambda.comparator("a,b -> a <=> b"))
            .sack(Lambda.biFunction("{ a,b -> a + b }"))
            .asAdmin();
    final List<Integer> sacks = new ArrayList<>();
    final List<Integer> lengths = new ArrayList<>();
    while (t.hasNext()) {
        final Traverser.Admin<Integer> traverser = t.nextTraverser();
        sacks.add(traverser.sack());
        lengths.add(traverser.get());
    }
    assertFalse(t.hasNext());
    //
    assertEquals(6, lengths.size());
    assertEquals(3, lengths.get(0).intValue());
    assertEquals(3, lengths.get(1).intValue());
    assertEquals(3, lengths.get(2).intValue());
    assertEquals(4, lengths.get(3).intValue());
    assertEquals(5, lengths.get(4).intValue());
    assertEquals(6, lengths.get(5).intValue());
    ///
    assertEquals(6, sacks.size());
    assertEquals(4, sacks.get(0).intValue());
    assertEquals(4, sacks.get(1).intValue());
    assertEquals(4, sacks.get(2).intValue());
    assertEquals(5, sacks.get(3).intValue());
    assertEquals(6, sacks.get(4).intValue());
    assertEquals(7, sacks.get(5).intValue());
    //
    assertEquals(24, t.getSideEffects().<Number>get("lengthSum").intValue());

    final String script = GroovyTranslator.of("g").translate(t.getBytecode()).getScript();
    assertEquals("g.withStrategies(org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.TranslationStrategy.instance())" +
                    ".withSideEffect(\"lengthSum\",(int) 0).withSack((int) 1)" +
                    ".V()" +
                    ".filter({it.get().label().equals('person')})" +
                    ".flatMap({it.get().vertices(Direction.OUT)})" +
                    ".map({it.get().value('name').length()})" +
                    ".sideEffect({ x -> x.sideEffects(\"lengthSum\", x.<Integer>sideEffects('lengthSum') + x.get()) })" +
                    ".order().by({a,b -> a <=> b})" +
                    ".sack({ a,b -> a + b })",
            script);
}