Java Code Examples for org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory#createModern()

The following examples show how to use org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory#createModern() . 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: HaltedTraverserStrategyTest.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnDetachedElements() {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.create(new MapConfiguration(new HashMap<String, Object>() {{
        put(HaltedTraverserStrategy.HALTED_TRAVERSER_FACTORY, DetachedFactory.class.getCanonicalName());
    }})));
    g.V().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(DetachedVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(DetachedEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(DetachedProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(DetachedPath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    // should handle nested collections
    g.V().out().fold().next().forEach(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
}
 
Example 2
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 3
Source File: GraphSONMessageSerializerV2d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeAndDeserializeResponseMessageFromObjectMapper() throws IOException {
    final ObjectMapper om = GraphSONMapper.build().version(GraphSONVersion.V2_0)
            .addCustomModule(new GraphSONMessageSerializerGremlinV2d0.GremlinServerModule())
            .create().createMapper();
    final Graph graph = TinkerFactory.createModern();

    final ResponseMessage responseMessage = ResponseMessage.build(UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786")).
            code(org.apache.tinkerpop.gremlin.driver.message.ResponseStatusCode.SUCCESS).
            result(Collections.singletonList(graph.vertices().next())).create();

    final String respJson = om.writeValueAsString(responseMessage);
    final ResponseMessage responseMessageRead = om.readValue(respJson, ResponseMessage.class);

    assertEquals(responseMessage.getRequestId(), responseMessageRead.getRequestId());
    assertEquals(responseMessage.getResult().getMeta(), responseMessageRead.getResult().getMeta());
    assertEquals(responseMessage.getResult().getData(), responseMessageRead.getResult().getData());
    assertEquals(responseMessage.getStatus().getAttributes(), responseMessageRead.getStatus().getAttributes());
    assertEquals(responseMessage.getStatus().getCode().getValue(), responseMessageRead.getStatus().getCode().getValue());
    assertEquals(responseMessage.getStatus().getCode().isSuccess(), responseMessageRead.getStatus().getCode().isSuccess());
    assertEquals(responseMessage.getStatus().getMessage(), responseMessageRead.getStatus().getMessage());
}
 
Example 4
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldClearBindingsBetweenEvals() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.put("g", g);
    engine.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()"));

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

    assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());

    try {
        engine.eval("g.V().has('name',s).next()");
        fail("This should have failed because s is no longer bound");
    } catch (Exception ex) {
        final Throwable t = ExceptionUtils.getRootCause(ex);
        assertEquals(MissingPropertyException.class, t.getClass());
        assertTrue(t.getMessage().startsWith("No such property: s for class"));
    }

}
 
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: HaltedTraverserStrategyTest.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnReferenceElements() {
    final Graph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.reference());
    g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    // the default should be reference elements
    g = graph.traversal().withComputer();
    g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    // should handle nested collections
    g.V().out().fold().next().forEach(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
}
 
Example 7
Source File: GremlinGroovyScriptEngineTinkerPopSandboxTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEvalOnGAsTheMethodIsWhiteListed() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final CompileStaticGroovyCustomizer standardSandbox = new CompileStaticGroovyCustomizer(TinkerPopSandboxExtension.class.getName());
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(standardSandbox);

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()", bindings));
    assertEquals(g.V(convertToVertexId(graph, "marko")).out("created").count().next(), engine.eval("g.V(marko).out(\"created\").count().next()", bindings));
}
 
Example 8
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 9
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 10
Source File: GremlinGroovyScriptEngineFileSandboxTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    graph = TinkerFactory.createModern();
    g = graph.traversal();
    if (System.getProperty(FileSandboxExtension.GREMLIN_SERVER_SANDBOX) == null) {
        final File f = TestHelper.generateTempFileFromResource(TinkerGraph.class, GremlinGroovyScriptEngineFileSandboxTest.class, "sandbox.yaml", ".yaml");
        System.setProperty(FileSandboxExtension.GREMLIN_SERVER_SANDBOX, Storage.toPath(f));
    }
}
 
Example 11
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadImports() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engineWithImports = new GremlinGroovyScriptEngine();
    engineWithImports.put("g", g);
    assertEquals(Vertex.class.getName(), engineWithImports.eval("Vertex.class.getName()"));
    assertEquals(2l, engineWithImports.eval("g.V().has('age',gt(30)).count().next()"));
    assertEquals(Direction.IN, engineWithImports.eval("Direction.IN"));
    assertEquals(Direction.OUT, engineWithImports.eval("Direction.OUT"));
    assertEquals(Direction.BOTH, engineWithImports.eval("Direction.BOTH"));
}
 
Example 12
Source File: GremlinGroovyScriptEngineIntegrateTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotBlowTheHeapParameterized() throws ScriptException {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final String[] gremlins = new String[]{
            "g.V(xxx).out().toList()",
            "g.V(xxx).in().toList()",
            "g.V(xxx).out().out().out().toList()",
            "g.V(xxx).out().groupCount()"
    };

    long parameterizedStartTime = System.currentTimeMillis();
    logger.info("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);
            engine.eval(gremlins[ix % 4], bindings);

            if (ix > 0 && ix % 5000 == 0) {
                logger.info(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) {
        fail("Blew the heap - the cache should prevent this from happening.");
    }
}
 
Example 13
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 14
Source File: HaltedTraverserStrategyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnReferenceElements() {
    final Graph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.reference());
    g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    // the default should be reference elements
    g = graph.traversal().withComputer();
    g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    // should handle nested collections
    g.V().out().fold().next().forEach(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
}
 
Example 15
Source File: GremlinGroovyScriptEngineSandboxedStandardTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEvalGraphTraversalSource() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()", bindings));

    engine = new GremlinGroovyScriptEngine(notSandboxed);
    try {
        bindings = engine.createBindings();
        bindings.put("g", g);
        bindings.put("marko", convertToVertexId(graph, "marko"));
        engine.eval("g.V(marko).next()", bindings);
        fail("Type checking should have forced an error as 'g' is not defined");
    } catch (Exception ex) {
        assertEquals(MultipleCompilationErrorsException.class, ex.getCause().getClass());
        assertThat(ex.getMessage(), containsString("The variable [g] is undeclared."));
    }

    engine = new GremlinGroovyScriptEngine(sandboxed);
    bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()", bindings));
    assertEquals(g.V(convertToVertexId(graph, "marko")).out("created").count().next(), engine.eval("g.V(marko).out(\"created\").count().next()", bindings));
}
 
Example 16
Source File: BaseSqlGremlinTest.java    From sql-gremlin with Apache License 2.0 5 votes vote down vote up
public void setUpBefore(Data data) {
    switch(data) {
        case MODERN:
            graph = TinkerFactory.createModern();
            break;
        case CLASSIC:
            graph = TinkerFactory.createClassic();
            break;
        case CREW:
            graph = TinkerFactory.createTheCrew();
            break;
        case SPACE:
            graph = SqlFactory.createSpaceGraph();
            break;
        default:
            throw new UnsupportedOperationException("Unsupported graph " + data);
    }
    g = graph.traversal();

    ObjectMapper mapper = new ObjectMapper();
    try {
        schemaConfig = mapper.readValue(new File("schema.json"), SchemaConfig.class);
    } catch (Exception e) {
        throw new SchemaException("Error reading the schema file.", e);
    }

    compiler = new GremlinCompiler(graph, schemaConfig);

}
 
Example 17
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAllowFunctionsUsedInClosure() throws ScriptException {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    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(graph, "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(graph, "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();

    // 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(graph, "vadas")).next(), engine.eval("g.V().filter{isVadas(it.get())}.next()", bindings));
}
 
Example 18
Source File: GroovyTranslatorTest.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 String script = GroovyTranslator.of("g").translate(g.inject(Collections.emptyMap()).map(identity).asAdmin().getBytecode()).getScript();
    assertEquals("g.inject([]).map({it.get()})", script);
    assertThatScriptOk(script, "g", g);
}
 
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: ParameterizedGroovyTranslatorTest.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 Script script1 = GroovyTranslator.of("g", true).translate(g.inject(vertex1).asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script1.getParameters().ifPresent(bindings::putAll);
    assertEquals(2, bindings.size());
    assertEquals(id1, bindings.get("_args_0"));
    assertEquals("customer", bindings.get("_args_1"));
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(_args_0,_args_1, Collections.emptyMap()))", script1.getScript());
    final Script standard1 = GroovyTranslator.of("g").translate(g.inject(vertex1).asAdmin().getBytecode());
    bindings.put("g", g);
    // TinkerGraph not support string id
    assertParameterizedScriptOk(standard1.getScript(), script1.getScript(), bindings, false);
    bindings.clear();

    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 Script script2 = GroovyTranslator.of("g", true).translate(g.inject(vertex2).asAdmin().getBytecode());
    script2.getParameters().ifPresent(bindings::putAll);
    assertEquals(2, bindings.size());
    assertEquals(id2, bindings.get("_args_0"));
    assertEquals("user", bindings.get("_args_1"));
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(_args_0,_args_1, Collections.emptyMap()))", script2.getScript());
    final Script standard2 = GroovyTranslator.of("g").translate(g.inject(vertex2).asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard2.getScript(), script2.getScript(), bindings, false);
    bindings.clear();

    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 Script script3 = GroovyTranslator.of("g", true).translate(g.inject(edge).asAdmin().getBytecode());
    script3.getParameters().ifPresent(bindings::putAll);
    assertEquals(6, bindings.size());
    assertEquals(id3, bindings.get("_args_0"));
    assertEquals("knows", bindings.get("_args_1"));
    assertEquals(id1, bindings.get("_args_2"));
    assertEquals("customer", bindings.get("_args_3"));
    assertEquals(id2, bindings.get("_args_4"));
    assertEquals("user", bindings.get("_args_5"));
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge(_args_0,_args_1,Collections.emptyMap(),_args_2,_args_3,_args_4,_args_5))", script3.getScript());
    final Script standard3 = GroovyTranslator.of("g").translate(g.inject(edge).asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard3.getScript(), script3.getScript(), bindings, false);
    bindings.clear();

    final Script script4 = GroovyTranslator.of("g", true).translate(
            g.addE("knows").from(vertex1).to(vertex2).property("when", "2018/09/21")
                    .asAdmin().getBytecode());
    script4.getParameters().ifPresent(bindings::putAll);
    assertEquals(7, bindings.size());
    assertEquals("knows", bindings.get("_args_0"));
    assertEquals(id1, bindings.get("_args_1"));
    assertEquals("customer", bindings.get("_args_2"));
    assertEquals(id2, bindings.get("_args_3"));
    assertEquals("user", bindings.get("_args_4"));
    assertEquals("when", bindings.get("_args_5"));
    assertEquals("2018/09/21", bindings.get("_args_6"));
    assertEquals("g.addE(_args_0).from(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(_args_1,_args_2, Collections.emptyMap())).to(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(_args_3,_args_4, Collections.emptyMap())).property(_args_5,_args_6)", script4.getScript());
    final Script standard4 = GroovyTranslator.of("g").translate(
            g.addE("knows").from(vertex1).to(vertex2).property("when", "2018/09/21")
                    .asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard4.getScript(), script4.getScript(), bindings, false);
    bindings.clear();

    final Script script5 = GroovyTranslator.of("g", true).translate(g.V().has("age").asAdmin().getBytecode());
    script5.getParameters().ifPresent(bindings::putAll);
    assertEquals(1, bindings.size());
    assertEquals("age", bindings.get("_args_0"));
    assertEquals("g.V().has(_args_0)", script5.getScript());
    final Script standard5 = GroovyTranslator.of("g").translate(g.V().has("age").asAdmin().getBytecode());
    bindings.put("g", g);
    // Ok, here we checking all the result
    assertParameterizedScriptOk(standard5.getScript(), script5.getScript(), bindings, true);
    bindings.clear();
}