org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory. 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: 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 #2
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 #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: 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 #5
Source File: HaltedTraverserStrategyTest.java    From tinkerpop 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 #6
Source File: GryoMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeTree() throws Exception {
    final Graph g = TinkerFactory.createModern();
    final Tree t = g.traversal().V().out().out().tree().by("name").next();

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

    final Tree deserialized = (Tree) response.getResult().getData();
    assertEquals(t, deserialized);

    assertThat(deserialized.containsKey("marko"), is(true));
    assertEquals(1, deserialized.size());

    final Tree markoChildren = (Tree) deserialized.get("marko");
    assertThat(markoChildren.containsKey("josh"), is(true));
    assertEquals(1, markoChildren.size());

    final Tree joshChildren = (Tree) markoChildren.get("josh");
    assertThat(joshChildren.containsKey("lop"), is(true));
    assertThat(joshChildren.containsKey("ripple"), is(true));
    assertEquals(2, joshChildren.size());
}
 
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: 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 #9
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 #10
Source File: GraphSONMessageSerializerGremlinV1d0Test.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 #11
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldProperlyHandleBindings() throws Exception {
    final Graph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.put("g", g);
    engine.put("marko", convertToVertexId(graph, "marko"));
    Assert.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");
    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(graph, "marko", "knows", "vadas")).next());
    assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()", bindings), g.V(convertToVertexId(graph, "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(graph, "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(graph, "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(graph, "marko")).next());
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: ToyGraphInputRDD.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public JavaPairRDD<Object, VertexWritable> readGraphRDD(final Configuration configuration, final JavaSparkContext sparkContext) {
    KryoShimServiceLoader.applyConfiguration(TinkerGraph.open().configuration());
    final List<VertexWritable> vertices;
    if (configuration.getString(Constants.GREMLIN_HADOOP_INPUT_LOCATION).contains("modern"))
        vertices = IteratorUtils.list(IteratorUtils.map(TinkerFactory.createModern().vertices(), VertexWritable::new));
    else if (configuration.getString(Constants.GREMLIN_HADOOP_INPUT_LOCATION).contains("classic"))
        vertices = IteratorUtils.list(IteratorUtils.map(TinkerFactory.createClassic().vertices(), VertexWritable::new));
    else if (configuration.getString(Constants.GREMLIN_HADOOP_INPUT_LOCATION).contains("crew"))
        vertices = IteratorUtils.list(IteratorUtils.map(TinkerFactory.createTheCrew().vertices(), VertexWritable::new));
    else if (configuration.getString(Constants.GREMLIN_HADOOP_INPUT_LOCATION).contains("sink"))
        vertices = IteratorUtils.list(IteratorUtils.map(TinkerFactory.createKitchenSink().vertices(), VertexWritable::new));
    else if (configuration.getString(Constants.GREMLIN_HADOOP_INPUT_LOCATION).contains("grateful")) {
        try {
            final Graph graph = TinkerGraph.open();
            final GraphReader reader = GryoReader.build().mapper(graph.io(GryoIo.build()).mapper().create()).create();
            try (final InputStream stream = GryoResourceAccess.class.getResourceAsStream("grateful-dead-v3d0.kryo")) {
                reader.readGraph(stream, graph);
            }
            vertices = IteratorUtils.list(IteratorUtils.map(graph.vertices(), VertexWritable::new));
        } catch (final IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    } else
        throw new IllegalArgumentException("No legal toy graph was provided to load: " + configuration.getProperty(Constants.GREMLIN_HADOOP_INPUT_LOCATION));

    return sparkContext.parallelize(vertices).mapToPair(vertex -> new Tuple2<>(vertex.get().id(), vertex));
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeThreadSafe() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    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);
                } finally {
                    if (graph.features().graph().supportsTransactions())
                        g.tx().rollback();
                }
                latch.countDown();
            }
        }.start();
    }
    latch.await();
}
 
Example #24
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 #25
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@org.junit.Ignore
public void shouldAllowUseOfClasses() throws ScriptException {
    final Graph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("vadas", convertToVertexId(graph, "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));
}
 
Example #26
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 #27
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeThreadSafeOnCompiledScript() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    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);
                } finally {
                    if (graph.features().graph().supportsTransactions())
                        g.tx().rollback();
                }
                latch.countDown();
            }
        }.start();
    }
    latch.await();
}
 
Example #28
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDoSomeGremlin() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    final List list = new ArrayList();
    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    bindings.put("temp", list);
    assertEquals(list.size(), 0);
    engine.eval("g.V(marko).out().fill(temp)",bindings);
    assertEquals(list.size(), 3);
}
 
Example #29
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 #30
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"));
}