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

The following examples show how to use org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph. 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: GraphSONMessageSerializerV3d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeEdgeProperty() throws Exception {
    final Graph graph = TinkerGraph.open();
    final Vertex v1 = graph.addVertex();
    final Vertex v2 = graph.addVertex();
    final Edge e = v1.addEdge("test", v2);
    e.property("abc", 123);

    final Iterable<Property<Object>> iterable = IteratorUtils.list(e.properties("abc"));
    final ResponseMessage response = convert(iterable);
    assertCommon(response);

    final List<Property> propertyList = (List<Property>) response.getResult().getData();
    assertEquals(1, propertyList.size());
    assertEquals(123, propertyList.get(0).value());
}
 
Example #2
Source File: GraphBinaryReaderWriterBenchmark.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Setup(Level.Trial)
public void doSetup() throws IOException {
    bytecode1.addStep("V");
    bytecode1.addStep("values", "name");
    bytecode1.addStep("tail", 5);

    Graph g = TinkerGraph.open();

    bytecode2 = g.traversal()
            .addV("person")
            .property("name1", 1)
            .property("name2", UUID.randomUUID())
            .property("name3", InetAddress.getByAddress(new byte[] { 127, 0, 0, 1}))
            .property("name4", BigInteger.valueOf(33343455342245L))
            .property("name5", "kjlkdnvlkdrnvldnvndlrkvnlhkjdkgkrtnlkndblknlknonboirnlkbnrtbonrobinokbnrklnbkrnblktengotrngotkrnglkt")
            .property("name6", Instant.now())
            .asAdmin().getBytecode();

    writer.writeValue(bytecode1, bytecodeBuffer1, false);
    writer.writeValue(bytecode2, bytecodeBuffer2, false);
    writer.writeValue(P.between(1, 2), pBuffer1, false);
}
 
Example #3
Source File: NetworkGraphLoader.java    From Ferma with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs network graph with the following devices and connections.
 * All connections are bidirectional.
 * There are 5 devices named DEV1 to DEV5
 * DEV1 is connected to DEV2, DEV3, DEV4
 * DEV5 is connected to DEV2, DEV3, DEV4
 * @return 
 */
public DelegatingFramedGraph<?> load() {
    final DelegatingFramedGraph<TinkerGraph> framedGraph = new DelegatingFramedGraph(TinkerGraph.open(), true, NETWORK_GRAPH_TYPES);
    
    ComputerVertex dev1 = makeDevice(framedGraph, "DEV1");
    ComputerVertex dev2 = makeDevice(framedGraph, "DEV2");
    ComputerVertex dev3 = makeDevice(framedGraph, "DEV3");
    ComputerVertex dev4 = makeDevice(framedGraph, "DEV4");
    ComputerVertex dev5 = makeDevice(framedGraph, "DEV5");
    
    makeTwoWayConnection(framedGraph, dev1, dev2);
    makeTwoWayConnection(framedGraph, dev1, dev3);
    makeTwoWayConnection(framedGraph, dev1, dev4);
    
    makeTwoWayConnection(framedGraph, dev5, dev2);
    makeTwoWayConnection(framedGraph, dev5, dev3);
    makeTwoWayConnection(framedGraph, dev5, dev4);
    
    return framedGraph;
}
 
Example #4
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 #5
Source File: TinkerGraphProvider.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = selectIdMakerFromGraphData(loadGraphWith);
    final String idMaker = (idManager.equals(TinkerGraph.DefaultIdManager.ANY) ? selectIdMakerFromTest(test, testMethodName) : idManager).name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,TestHelper.makeTestDataFile(test, "temp", testMethodName + ".kryo"));
        }
    }};
}
 
Example #6
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 #7
Source File: TinkerGraphProvider.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Test that load with specific graph data can be configured with a specific id manager as the data type to
 * be used in the test for that graph is known.
 */
protected TinkerGraph.DefaultIdManager selectIdMakerFromGraphData(final LoadGraphWith.GraphData loadGraphWith) {
    if (null == loadGraphWith) return TinkerGraph.DefaultIdManager.ANY;
    if (loadGraphWith.equals(LoadGraphWith.GraphData.CLASSIC))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.MODERN))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.CREW))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.GRATEFUL))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.SINK))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else
        throw new IllegalStateException(String.format("Need to define a new %s for %s", TinkerGraph.IdManager.class.getName(), loadGraphWith.name()));
}
 
Example #8
Source File: PolymorphicTypeResolverTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testHasTypeChildFromPackage() {
    final Graph godGraph = TinkerGraph.open();
    final FramedGraph framedGraph = new DelegatingFramedGraph(godGraph, TEST_MODEL_PACKAGE);

    //add a single node to the graph, a programmer.
    framedGraph.addFramedVertex(Programmer.class);

    //make sure the newly added node is actually a programmer
    final Person programmer = framedGraph.traverse(input -> framedGraph.getTypeResolver().hasType(input.V(), Programmer.class)).next(Person.class);
    Assert.assertTrue(programmer instanceof Programmer);

    //change the type resolution to person
    programmer.setTypeResolution(Person.class);

    //make sure the newly added node is not actually a programmer
    final Person person = framedGraph.traverse(input -> input.V()).next(Person.class);
    Assert.assertFalse(person instanceof Programmer);
}
 
Example #9
Source File: TinkerGraphProvider.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Test that load with specific graph data can be configured with a specific id manager as the data type to
 * be used in the test for that graph is known.
 */
protected TinkerGraph.DefaultIdManager selectIdMakerFromGraphData(final LoadGraphWith.GraphData loadGraphWith) {
    if (null == loadGraphWith) return TinkerGraph.DefaultIdManager.ANY;
    if (loadGraphWith.equals(LoadGraphWith.GraphData.CLASSIC))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.MODERN))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.CREW))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.GRATEFUL))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.SINK))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else
        throw new IllegalStateException(String.format("Need to define a new %s for %s", TinkerGraph.IdManager.class.getName(), loadGraphWith.name()));
}
 
Example #10
Source File: PropertyMethodHandlerTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveName() {
    final Graph godGraph = TinkerGraph.open();
    GodGraphLoader.load(godGraph);

    final FramedGraph framedGraph = new DelegatingFramedGraph(godGraph, TEST_TYPES);

    List<? extends God> gods = framedGraph.traverse(
        input -> input.V().has("name", "jupiter")).toList(God.class);

    final God father = gods.iterator().next();
    Assert.assertTrue(father != null);
    final VertexFrame fatherVertex = father;
    Assert.assertEquals(fatherVertex.getProperty("name"), "jupiter");
    father.removeName();

    Assert.assertNull(fatherVertex.getProperty("name"));
}
 
Example #11
Source File: GraphSONUtilityTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void processEdge_PropagateSetTo_ONE_TO_TWO() {
    Map<String, RelationshipCacheGenerator.TypeInfo> typeCache = new HashMap<String, RelationshipCacheGenerator.TypeInfo>() {{
        put("__Process.inputs", new RelationshipCacheGenerator.TypeInfo("dataset_process_inputs", AtlasRelationshipDef.PropagateTags.TWO_TO_ONE));
    }};

    ElementProcessors elementProcessors = new ElementProcessors(typeCache, getPostProcessMap(), new HashMap<>());
    TinkerGraph tg = TinkerGraph.open();
    GraphSONUtility gu = new GraphSONUtility(elementProcessors);

    addVertexToGraph(tg, gu, getDBV(), getTableV(), getProcessV());
    addEdgeToGraph(tg, gu, new MappedElementCache(), getEdgeProcess());

    Iterator<Edge> edges = tg.edges();
    while(edges.hasNext()) {
        Edge e = edges.next();
        assertTrue(e.property(Constants.RELATIONSHIPTYPE_TAG_PROPAGATION_KEY).isPresent());
        assertEquals(e.property(Constants.RELATIONSHIPTYPE_TAG_PROPAGATION_KEY).value().toString(), "TWO_TO_ONE");
        assertEquals(e.property(STATE_PROPERTY_KEY).value(), "ACTIVE");
        assertTrue(e.property(Constants.RELATIONSHIP_GUID_PROPERTY_KEY).isPresent());
    }
}
 
Example #12
Source File: PolymorphicTypeResolverTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomTypeKeyExplicitByClass() {
    final Graph g = TinkerGraph.open();
    final ReflectionCache cache = new ReflectionCache(TEST_TYPES);
    final FramedGraph fg = new DelegatingFramedGraph(g, new AnnotationFrameFactory(cache), new PolymorphicTypeResolver(cache, CUSTOM_TYPE_KEY));

    final Person p1 = fg.addFramedVertexExplicit(Programmer.class);
    p1.setName("Bryn");

    final Person p2 = fg.addFramedVertexExplicit(Person.class);
    p2.setName("Julia");

    final Person bryn = fg.traverse(input -> input.V().has("name", "Bryn")).next(Person.class);
    final Person julia = fg.traverse(input -> input.V().has("name", "Julia")).next(Person.class);

    Assert.assertEquals(Person.class, bryn.getClass());
    Assert.assertEquals(Person.class, julia.getClass());

    Assert.assertFalse(bryn.getElement().property(CUSTOM_TYPE_KEY).isPresent());
    Assert.assertFalse(bryn.getElement().property(PolymorphicTypeResolver.TYPE_RESOLUTION_KEY).isPresent());
    Assert.assertFalse(julia.getElement().property(CUSTOM_TYPE_KEY).isPresent());
    Assert.assertFalse(julia.getElement().property(PolymorphicTypeResolver.TYPE_RESOLUTION_KEY).isPresent());
}
 
Example #13
Source File: TinkerGraphStep.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
private Iterator<? extends Edge> edges() {
    final TinkerGraph graph = (TinkerGraph) this.getTraversal().getGraph().get();
    final HasContainer indexedContainer = getIndexKey(Edge.class);
    final Optional<HasContainer> hasLabelContainer = findHasLabelStep();
    // ids are present, filter on them first
    if (null == this.ids)
        return Collections.emptyIterator();
    else if (this.ids.length > 0)
        return this.iteratorList(graph.edges(this.ids));
    else if (graph.ondiskOverflowEnabled && hasLabelContainer.isPresent())
        return graph.edgesByLabel((P<String>) hasLabelContainer.get().getPredicate());
    else
        return null == indexedContainer ?
                this.iteratorList(graph.edges()) :
                TinkerHelper.queryEdgeIndex(graph, indexedContainer.getKey(), indexedContainer.getPredicate().getValue()).stream()
                        .filter(edge -> HasContainer.testAll(edge, this.hasContainers))
                        .collect(Collectors.<Edge>toList()).iterator();
}
 
Example #14
Source File: FramedGraphTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeyValues() {
    final Graph g = TinkerGraph.open();
    final FramedGraph fg = new DelegatingFramedGraph(g, true, false);

    final Person p1 = fg.addFramedVertex(Programmer.DEFAULT_INITIALIZER, "key", "value");
    p1.setName("Bryn");

    final Person p2 = fg.addFramedVertex(Person.DEFAULT_INITIALIZER, T.label, "label");
    p2.setName("Julia");

    final Person bryn = fg.traverse(
        input -> input.V().has("key", "value")).next(Person.class);
    final Person julia = fg.traverse(
        input -> input.V().hasLabel("label")).next(Person.class);

    Assert.assertEquals(Programmer.class, bryn.getClass());
    Assert.assertEquals(Person.class, julia.getClass());

    Assert.assertNotNull(bryn.getElement().property(PolymorphicTypeResolver.TYPE_RESOLUTION_KEY).value());
    Assert.assertNotNull(julia.getElement().property(PolymorphicTypeResolver.TYPE_RESOLUTION_KEY).value());
}
 
Example #15
Source File: TinkerGraphIoStepTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteReadWithCustomIoRegistryGryo() throws Exception {
    final UUID uuid = UUID.randomUUID();
    g.addV("person").property("name","stephen").property("custom", new CustomId("a", uuid)).iterate();

    final File file = TestHelper.generateTempFile(TinkerGraphIoStepTest.class, "shouldWriteReadWithCustomIoRegistryGryo", ".kryo");
    g.io(file.getAbsolutePath()).with(IO.registry, CustomId.CustomIdIoRegistry.class.getName()).write().iterate();

    final Graph emptyGraph = TinkerGraph.open();
    final GraphTraversalSource emptyG = emptyGraph.traversal();

    try {
        emptyG.io(file.getAbsolutePath()).read().iterate();
        fail("Can't read without a registry");
    } catch (Exception ignored) {
        // do nothing
    }

    emptyG.io(file.getAbsolutePath()).with(IO.registry, CustomId.CustomIdIoRegistry.instance()).read().iterate();

    assertEquals(1, emptyG.V().has("custom", new CustomId("a", uuid)).count().next().intValue());
}
 
Example #16
Source File: TinkerGraphComputerView.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
public TinkerGraphComputerView(final TinkerGraph graph, final GraphFilter graphFilter, final Set<VertexComputeKey> computeKeys) {
    this.graph = graph;
    this.computeKeys = new HashMap<>();
    computeKeys.forEach(key -> this.computeKeys.put(key.getKey(), key));
    this.computeProperties = new ConcurrentHashMap<>();
    this.graphFilter = graphFilter;
    if (this.graphFilter.hasFilter()) {
        graph.vertices().forEachRemaining(vertex -> {
            boolean legalVertex = false;
            if (this.graphFilter.hasVertexFilter() && this.graphFilter.legalVertex(vertex)) {
                this.legalVertices.add(vertex.id());
                legalVertex = true;
            }
            if ((legalVertex || !this.graphFilter.hasVertexFilter()) && this.graphFilter.hasEdgeFilter()) {
                final Set<Object> edges = new HashSet<>();
                this.legalEdges.put(vertex.id(), edges);
                this.graphFilter.legalEdges(vertex).forEachRemaining(edge -> edges.add(edge.id()));
            }
        });
    }
}
 
Example #17
Source File: TinkerGraphCountStrategyTest.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> generateTestParameters() {
    return Arrays.asList(new Object[][]{
            {__.V().count(), countStep(Vertex.class), Collections.emptyList()},
            {__.V().count(), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().as("a").count(), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().count().as("a"), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().map(out()).count().as("a"), null, TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().map(out()).identity().count().as("a"), null, TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().map(out().groupCount()).identity().count().as("a"), null, TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().label().map(s -> s.get().length()).count(), null, TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().as("a").map(select("a")).count(), null, TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            //
            {__.V(), null, Collections.emptyList()},
            {__.V().out().count(), null, Collections.emptyList()},
            {__.V(1).count(), null, Collections.emptyList()},
            {__.count(), null, Collections.emptyList()},
            {__.V().map(out().groupCount("m")).identity().count().as("a"), null, Collections.emptyList()},
    });
}
 
Example #18
Source File: TinkerGraphProvider.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = selectIdMakerFromGraphData(loadGraphWith);
    final String idMaker = (idManager.equals(TinkerGraph.DefaultIdManager.ANY) ? selectIdMakerFromTest(test, testMethodName) : idManager).name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            final File tempDir = TestHelper.makeTestDataPath(test, "temp");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,
                    tempDir.getAbsolutePath() + File.separator + testMethodName + ".kryo");
        }
    }};
}
 
Example #19
Source File: OutVertexMethodHandlerTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSonEdges() {
    final TinkerGraph godGraph = TinkerGraph.open();
    GodGraphLoader.load(godGraph);

    final FramedGraph framedGraph = new DelegatingFramedGraph(godGraph, TEST_TYPES);

    final List<? extends God> gods = framedGraph.traverse(
        input -> input.V().has("name", "jupiter")).toList(God.class);

    final God father = gods.iterator().next();
    Assert.assertTrue(father != null);
    final VertexFrame fatherVertex = father;
    Assert.assertEquals(fatherVertex.getProperty("name"), "jupiter");

    final Iterator<? extends FatherEdge> childEdgeIterator = father.getSonEdges(FatherEdge.class);
    Assert.assertTrue(childEdgeIterator.hasNext());
    final FatherEdge childEdge = childEdgeIterator.next();

    final God son = childEdge.getSon();
    Assert.assertTrue(son != null);
    final VertexFrame sonVertex = son;
    Assert.assertEquals(sonVertex.getProperty("name"), "hercules");
}
 
Example #20
Source File: TinkerGraphProvider.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
/**
 * Test that load with specific graph data can be configured with a specific id manager as the data type to
 * be used in the test for that graph is known.
 */
protected TinkerGraph.DefaultIdManager selectIdMakerFromGraphData(final LoadGraphWith.GraphData loadGraphWith) {
    if (null == loadGraphWith) return TinkerGraph.DefaultIdManager.ANY;
    if (loadGraphWith.equals(LoadGraphWith.GraphData.CLASSIC))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.MODERN))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.CREW))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.GRATEFUL))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else if (loadGraphWith.equals(LoadGraphWith.GraphData.SINK))
        return TinkerGraph.DefaultIdManager.INTEGER;
    else
        throw new IllegalStateException(String.format("Need to define a new %s for %s", TinkerGraph.IdManager.class.getName(), loadGraphWith.name()));
}
 
Example #21
Source File: PolymorphicTypeResolverTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testHasTypeParentFromPackage() {
    final Graph godGraph = TinkerGraph.open();
    final FramedGraph framedGraph = new DelegatingFramedGraph(godGraph, TEST_MODEL_PACKAGE);

    //add a single node to the graph, a programmer.
    framedGraph.addFramedVertex(Programmer.class);

    //make sure the newly added node is actually a programmer
    final Person programmer = framedGraph.traverse(input -> framedGraph.getTypeResolver().hasType(input.V(), Person.class)).next(Person.class);
    Assert.assertTrue(programmer instanceof Programmer);

    //change the type resolution to person
    programmer.setTypeResolution(Person.class);

    //make sure the newly added node is not actually a programmer
    final Person person = framedGraph.traverse(input -> input.V()).next(Person.class);
    Assert.assertFalse(person instanceof Programmer);
}
 
Example #22
Source File: DefaultGraphManagerTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetAsBindings() {
    final Settings settings = Settings.read(DefaultGraphManagerTest.class.getResourceAsStream("../gremlin-server-integration.yaml"));
    final GraphManager graphManager = new DefaultGraphManager(settings);
    final Bindings bindings = graphManager.getAsBindings();

    assertNotNull(bindings);
    assertEquals(6, bindings.size());
    assertThat(bindings.containsKey("graph"), is(true));
    assertThat(bindings.containsKey("classic"), is(true));
    assertThat(bindings.containsKey("modern"), is(true));
    assertThat(bindings.containsKey("crew"), is(true));
    assertThat(bindings.containsKey("sink"), is(true));
    assertThat(bindings.containsKey("grateful"), is(true));
    assertThat(bindings.get("graph"), instanceOf(TinkerGraph.class));
}
 
Example #23
Source File: DocumentGraphConsumerTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException {
  JCasTestGraphUtil.populateJcas(jCas);
  tempDirectory = Files.createTempDirectory(DocumentGraphConsumerTest.class.getSimpleName());
  tempDirectory.toFile().deleteOnExit();

  graphFile = tempDirectory.resolve("testgraph.json").toFile();
  graphFile.deleteOnExit();

  propertiesFile = tempDirectory.resolve("graph.properties").toFile();
  propertiesFile.deleteOnExit();

  properties = new Properties();
  properties.setProperty(
      Graph.GRAPH, "org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph");
  properties.setProperty(
      TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT,
      GraphFormat.GRAPHSON.toString().toLowerCase());
  properties.setProperty(
      TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, graphFile.getAbsolutePath());
}
 
Example #24
Source File: IncidenceMethodHandlerTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSonEdgesSetDefault() {
    final TinkerGraph godGraph = TinkerGraph.open();
    GodGraphLoader.load(godGraph);

    final FramedGraph framedGraph = new DelegatingFramedGraph(godGraph, TEST_TYPES);

    final List<? extends God> gods = framedGraph.traverse(
        input -> input.V().has("name", "jupiter")).toList(God.class);

    final God father = gods.iterator().next();
    Assert.assertTrue(father != null);
    final VertexFrame fatherVertex = father;
    Assert.assertEquals(fatherVertex.getProperty("name"), "jupiter");

    final Set<? extends EdgeFrame> sonEdgesSet = father.getSonEdgesSet();
    Assert.assertFalse(sonEdgesSet.isEmpty());
    final EdgeFrame childEdge = sonEdgesSet.iterator().next();
    Assert.assertEquals(childEdge.getElement().outVertex().property("name").value(), "hercules");
}
 
Example #25
Source File: TinkerGraphProvider.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = selectIdMakerFromGraphData(loadGraphWith);
    final String idMaker = (idManager.equals(TinkerGraph.DefaultIdManager.ANY) ? selectIdMakerFromTest(test, testMethodName) : idManager).name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, TestHelper.makeTestDataFile(test, "temp", testMethodName + ".kryo"));
        }
    }};
}
 
Example #26
Source File: IncidenceMethodHandlerTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSonEdgesByType() {
    final TinkerGraph godGraph = TinkerGraph.open();
    GodGraphLoader.load(godGraph);

    final FramedGraph framedGraph = new DelegatingFramedGraph(godGraph, TEST_TYPES);

    final List<? extends God> gods = framedGraph.traverse(
        input -> input.V().has("name", "jupiter")).toList(God.class);

    final God father = gods.iterator().next();
    Assert.assertTrue(father != null);
    final VertexFrame fatherVertex = father;
    Assert.assertEquals(fatherVertex.getProperty("name"), "jupiter");

    final Iterator<? extends FatherEdge> childEdgeIterator = father.getSonEdges(FatherEdge.class);
    Assert.assertTrue(childEdgeIterator.hasNext());
    final FatherEdge childEdge = childEdgeIterator.next();
    Assert.assertTrue(childEdge != null);
    final EdgeFrame edge = childEdge;
    Assert.assertEquals(edge.getElement().outVertex().property("name").value(), "hercules");
}
 
Example #27
Source File: FramedGraphTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeyValuesByClass() {
    final Graph g = TinkerGraph.open();
    final FramedGraph fg = new DelegatingFramedGraph(g, true, false);

    final Person p1 = fg.addFramedVertex(Programmer.class, "key", "value");
    p1.setName("Bryn");

    final Person p2 = fg.addFramedVertex(Person.class, T.label, "label");
    p2.setName("Julia");

    final Person bryn = fg.traverse(
        input -> input.V().has("key", "value")).next(Person.class);
    final Person julia = fg.traverse(
        input -> input.V().hasLabel("label")).next(Person.class);

    Assert.assertEquals(Programmer.class, bryn.getClass());
    Assert.assertEquals(Person.class, julia.getClass());
    
    Assert.assertNotNull(bryn.getElement().property(PolymorphicTypeResolver.TYPE_RESOLUTION_KEY).value());
    Assert.assertNotNull(julia.getElement().property(PolymorphicTypeResolver.TYPE_RESOLUTION_KEY).value());
}
 
Example #28
Source File: IncidenceMethodHandlerTest.java    From Ferma with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSonEdgeByType() {
    final TinkerGraph godGraph = TinkerGraph.open();
    GodGraphLoader.load(godGraph);

    final FramedGraph framedGraph = new DelegatingFramedGraph(godGraph, TEST_TYPES);

    final List<? extends God> gods = framedGraph.traverse(
        input -> input.V().has("name", "jupiter")).toList(God.class);

    final God father = gods.iterator().next();
    Assert.assertTrue(father != null);
    final VertexFrame fatherVertex = father;
    Assert.assertEquals(fatherVertex.getProperty("name"), "jupiter");

    final FatherEdge childEdge = father.getSonEdge(FatherEdge.class);
    Assert.assertTrue(childEdge != null);
    final EdgeFrame edge = childEdge;
    Assert.assertEquals(childEdge.getElement().outVertex().property("name").value(), "hercules");
}
 
Example #29
Source File: GraphSONMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeEdgeProperty() throws Exception {
    final Graph g = TinkerGraph.open();
    final Vertex v1 = g.addVertex();
    final Vertex v2 = g.addVertex();
    final Edge e = v1.addEdge("test", v2);
    e.property("abc", 123);

    final Iterable<Property<Object>> iterable = IteratorUtils.list(e.properties("abc"));
    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(iterable).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);
    assertEquals(1, converted.size());

    final JsonNode propertyAsJson = converted.get(0);
    assertNotNull(propertyAsJson);

    assertEquals(123, propertyAsJson.get("value").asInt());
}
 
Example #30
Source File: App.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // Create a new TinkerGraph and load some test data. The Graph instance is typically named "graph" as a
    // variable name. You will see this pattern consistently in TinkerPop documentation, the mailing list, etc.
    Graph graph = TinkerGraph.open();
    loadData(graph);

    // Create a GraphTraversalSource instance that is used to query the data in the Graph instance. This variable
    // is typically denoted as "g".  In TinkerPop documentation you can always count on references to "g" as
    // being a object of this type.
    GraphTraversalSource g = graph.traversal();

    Vertex fromNode = findByName(g, "marko");
    Vertex toNode = findByName(g, "peter");

    List list = calculateShortestPathBetween(g, fromNode, toNode);
    System.out.println(list.toString());
    System.exit(0);
}