Java Code Examples for org.apache.tinkerpop.gremlin.structure.Graph#addVertex()

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Graph#addVertex() . 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: TinkerGraphGraphSONSerializerV2d0Test.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts the approximateGraphsChecks function fails when expected. Edge props.
 */
@Test
public void shouldLoseTypesWithGraphSONNoTypesForEdgeProps() throws IOException {
    final GraphWriter writer = getWriter(noTypesMapperV2d0);
    final GraphReader reader = getReader(noTypesMapperV2d0);
    final Graph sampleGraph1 = TinkerFactory.createModern();

    final Vertex v1 = sampleGraph1.addVertex(T.id, 100, "name", "kevin");
    v1.addEdge("hello", sampleGraph1.traversal().V().has("name", "marko").next(), T.id, 101,
            "uuid", UUID.randomUUID());
    try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        writer.writeGraph(out, sampleGraph1);
        final String json = out.toString();
        final TinkerGraph read = TinkerGraph.open();
        reader.readGraph(new ByteArrayInputStream(json.getBytes()), read);
        // Should fail on deserialized edge prop.
        assertFalse(approximateGraphsCheck(sampleGraph1, read));
    }
}
 
Example 2
Source File: IoTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldReadWriteSelfLoopingEdges() throws Exception {
    final GraphSONMapper mapper = graph.io(graphson).mapper().version(GraphSONVersion.V2_0).create();
    final Graph source = graph;
    final Vertex v1 = source.addVertex();
    final Vertex v2 = source.addVertex();
    v1.addEdge("CONTROL", v2);
    v1.addEdge("SELFLOOP", v1);

    final Configuration targetConf = graphProvider.newGraphConfiguration("target", this.getClass(), name.getMethodName(), null);
    final Graph target = graphProvider.openTestGraph(targetConf);
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        source.io(IoCore.graphson()).writer().mapper(mapper).create().writeGraph(os, source);
        try (ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray())) {
            target.io(IoCore.graphson()).reader().mapper(mapper).create().readGraph(is, target);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    assertEquals(IteratorUtils.count(source.vertices()), IteratorUtils.count(target.vertices()));
    assertEquals(IteratorUtils.count(source.edges()), IteratorUtils.count(target.edges()));
}
 
Example 3
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 4
Source File: TinkerGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private static void generate(final Graph graph) {
    final int size = 100;
    final List<Object> ids = new ArrayList<>();
    final Vertex v = graph.addVertex("sin", 0.0f, "cos", 1.0f, "ii", 0f);
    ids.add(v.id());

    final GraphTraversalSource g = graph.traversal();

    final Random rand = new Random();
    for (int ii = 1; ii < size; ii++) {
        final Vertex t = graph.addVertex("ii", ii, "sin", Math.sin(ii / 5.0f), "cos", Math.cos(ii / 5.0f));
        final Vertex u = g.V(ids.get(rand.nextInt(ids.size()))).next();
        t.addEdge("linked", u);
        ids.add(u.id());
        ids.add(v.id());
    }
}
 
Example 5
Source File: GraphSONMessageSerializerGremlinV2d0Test.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 6
Source File: GraphSONMessageSerializerV2d0Test.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(GraphSONTokens.VALUEPROP).get("value").get(GraphSONTokens.VALUEPROP).asInt());
}
 
Example 7
Source File: IoTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldReadWriteSelfLoopingEdges() throws Exception {
    final GraphSONMapper mapper = graph.io(graphson).mapper().version(GraphSONVersion.V3_0).create();
    final Graph source = graph;
    final Vertex v1 = source.addVertex();
    final Vertex v2 = source.addVertex();
    v1.addEdge("CONTROL", v2);
    v1.addEdge("SELFLOOP", v1);

    final Configuration targetConf = graphProvider.newGraphConfiguration("target", this.getClass(), name.getMethodName(), null);
    final Graph target = graphProvider.openTestGraph(targetConf);
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        source.io(IoCore.graphson()).writer().mapper(mapper).create().writeGraph(os, source);
        try (ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray())) {
            target.io(IoCore.graphson()).reader().mapper(mapper).create().readGraph(is, target);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    assertEquals(IteratorUtils.count(source.vertices()), IteratorUtils.count(target.vertices()));
    assertEquals(IteratorUtils.count(source.edges()), IteratorUtils.count(target.edges()));
}
 
Example 8
Source File: IoTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldReadWriteSelfLoopingEdges() throws Exception {
    final GraphSONMapper mapper = graph.io(graphson).mapper().version(GraphSONVersion.V1_0).create();
    final Graph source = graph;
    final Vertex v1 = source.addVertex();
    final Vertex v2 = source.addVertex();
    v1.addEdge("CONTROL", v2);
    v1.addEdge("SELFLOOP", v1);

    final Configuration targetConf = graphProvider.newGraphConfiguration("target", this.getClass(), name.getMethodName(), null);
    final Graph target = graphProvider.openTestGraph(targetConf);
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        source.io(IoCore.graphson()).writer().mapper(mapper).create().writeGraph(os, source);
        try (ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray())) {
            target.io(IoCore.graphson()).reader().mapper(mapper).create().readGraph(is, target);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    assertEquals(IteratorUtils.count(source.vertices()), IteratorUtils.count(target.vertices()));
    assertEquals(IteratorUtils.count(source.edges()), IteratorUtils.count(target.edges()));
}
 
Example 9
Source File: App.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static void loadData(Graph graph) {
    // see org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory.generateModern()
    final Vertex marko = graph.addVertex(T.id, 1, T.label, "person", "name", "marko", "age", 29);
    final Vertex vadas = graph.addVertex(T.id, 2, T.label, "person", "name", "vadas", "age", 27);
    final Vertex lop = graph.addVertex(T.id, 3, T.label, "software", "name", "lop", "lang", "java");
    final Vertex josh = graph.addVertex(T.id, 4, T.label, "person", "name", "josh", "age", 32);
    final Vertex ripple = graph.addVertex(T.id, 5, T.label, "software", "name", "ripple", "lang", "java");
    final Vertex peter = graph.addVertex(T.id, 6, T.label, "person", "name", "peter", "age", 35);
    marko.addEdge("knows", vadas, T.id, 7, "weight", 0.5d);
    marko.addEdge("knows", josh, T.id, 8, "weight", 1.0d);
    marko.addEdge("created", lop, T.id, 9, "weight", 0.4d);
    josh.addEdge("created", ripple, T.id, 10, "weight", 1.0d);
    josh.addEdge("created", lop, T.id, 11, "weight", 0.4d);
    peter.addEdge("created", lop, T.id, 12, "weight", 0.2d);
}
 
Example 10
Source File: GraphSONMessageSerializerGremlinV1d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeMapEntries() throws Exception {
    final Graph graph = TinkerGraph.open();
    final Vertex v1 = graph.addVertex();
    final Date d = new Date();

    final Map<Object, Object> map = new HashMap<>();
    map.put("x", 1);
    map.put(v1, 100);
    map.put(d, "test");

    final ResponseMessage response = convert(IteratorUtils.asList(map.entrySet()));
    assertCommon(response);

    final List<Map<String, Object>> deserializedEntries = (List<Map<String, Object>>) response.getResult().getData();
    assertEquals(3, deserializedEntries.size());
    deserializedEntries.forEach(e -> {
        if (e.containsKey("x"))
            assertEquals(1, e.get("x"));
        else if (e.containsKey(v1.id().toString()))
            assertEquals(100, e.get(v1.id().toString()));
        else if (e.containsKey(StdDateFormat.instance.format(d)))
            assertEquals("test", e.get(StdDateFormat.instance.format(d)));
        else
            fail("Map entries contains a key that is not part of what was serialized");
    });
}
 
Example 11
Source File: GraphSONMessageSerializerGremlinV2d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeEdge() 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<Edge> iterable = IteratorUtils.list(graph.edges());

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

    final List<Edge> edgeList = (List<Edge>) response.getResult().getData();
    assertEquals(1, edgeList.size());

    final Edge deserializedEdge = edgeList.get(0);
    assertEquals(e.id(), deserializedEdge.id());
    assertEquals(v1.id(), deserializedEdge.outVertex().id());
    assertEquals(v2.id(), deserializedEdge.inVertex().id());
    assertEquals(v1.label(), deserializedEdge.outVertex().label());
    assertEquals(v2.label(), deserializedEdge.inVertex().label());
    assertEquals(e.label(), deserializedEdge.label());

    final List<Property> properties = new ArrayList<>();
    deserializedEdge.properties().forEachRemaining(properties::add);
    assertEquals(1, properties.size());

    assertNotNull(properties);
    assertEquals("abc", properties.get(0).key());
    assertEquals(123, properties.get(0).value());

}
 
Example 12
Source File: Attachable.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static Vertex createVertex(final Attachable<Vertex> attachableVertex, final Graph hostGraph) {
    final Vertex baseVertex = attachableVertex.get();
    final Vertex vertex = hostGraph.features().vertex().willAllowId(baseVertex.id()) ?
            hostGraph.addVertex(T.id, baseVertex.id(), T.label, baseVertex.label()) :
            hostGraph.addVertex(T.label, baseVertex.label());
    baseVertex.properties().forEachRemaining(vp -> {
        final VertexProperty vertexProperty = hostGraph.features().vertex().properties().willAllowId(vp.id()) ?
                vertex.property(hostGraph.features().vertex().getCardinality(vp.key()), vp.key(), vp.value(), T.id, vp.id()) :
                vertex.property(hostGraph.features().vertex().getCardinality(vp.key()), vp.key(), vp.value());
        vp.properties().forEachRemaining(p -> vertexProperty.property(p.key(), p.value()));
    });
    return vertex;
}
 
Example 13
Source File: AdjacencyHandlerWithNetworkGraphTest.java    From Ferma with Apache License 2.0 5 votes vote down vote up
private RouterVertex makeRouterVertex(Graph graph, String name) {
    Element e = graph.addVertex();
    RouterVertex rv = new RouterVertex();
    rv.setElement(e);
    rv.setName(name);
    return rv;
}
 
Example 14
Source File: GryoMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeMapEntry() throws Exception {
    final Graph graph = TinkerGraph.open();
    final Vertex v1 = graph.addVertex();
    final Date d = new Date();

    final Map<Object, Object> map = new HashMap<>();
    map.put("x", 1);
    map.put(v1, 100);
    map.put(d, "test");

    final ResponseMessage response = convertBinary(IteratorUtils.asList(map.entrySet()));
    assertCommon(response);

    final java.util.List<Map.Entry<Object, Object>> deserializedEntries = (java.util.List<Map.Entry<Object, Object>>) response.getResult().getData();
    assertEquals(3, deserializedEntries.size());
    deserializedEntries.forEach(e -> {
        if (e.getKey().equals("x"))
            assertEquals(1, e.getValue());
        else if (e.getKey().equals(v1))
            assertEquals(100, e.getValue());
        else if (e.getKey().equals(d))
            assertEquals("test", e.getValue());
        else
            fail("Map entries contains a key that is not part of what was serialized");
    });
}
 
Example 15
Source File: Vre.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private Vertex findOrCreateVreVertex(Graph graph) {
  // Look for existing VRE vertex
  Vertex vreVertex;
  GraphTraversal<Vertex, Vertex> existing = graph.traversal().V().hasLabel(DATABASE_LABEL)
                                                 .has(VRE_NAME_PROPERTY_NAME, vreName);
  // Create new if does not exist
  if (existing.hasNext()) {
    vreVertex = existing.next();
    LOG.debug("Replacing existing vertex {}.", vreVertex);
  } else {
    vreVertex = graph.addVertex(DATABASE_LABEL);
    LOG.debug("Creating new vertex");
  }
  return vreVertex;
}
 
Example 16
Source File: GraphSONMessageSerializerV2d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeEdge() 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<Edge> iterable = IteratorUtils.list(g.edges());
    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 edgeAsJson = converted.get(0).get(GraphSONTokens.VALUEPROP);
    assertNotNull(edgeAsJson);

    assertEquals(((Long) e.id()).longValue(), edgeAsJson.get(GraphSONTokens.ID).get(GraphSONTokens.VALUEPROP).asLong());
    assertEquals(((Long) v1.id()).longValue(), edgeAsJson.get(GraphSONTokens.OUT).get(GraphSONTokens.VALUEPROP).asLong());
    assertEquals(((Long) v2.id()).longValue(), edgeAsJson.get(GraphSONTokens.IN).get(GraphSONTokens.VALUEPROP).asLong());
    assertEquals(e.label(), edgeAsJson.get(GraphSONTokens.LABEL).asText());

    final JsonNode properties = edgeAsJson.get(GraphSONTokens.PROPERTIES);
    assertNotNull(properties);
    assertEquals(123, properties.get("abc").get(GraphSONTokens.VALUEPROP).get("value").get(GraphSONTokens.VALUEPROP).asInt());
}
 
Example 17
Source File: GraphSONMessageSerializerV2d0Test.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldSerializeToJsonIteratorWithEmbeddedMap() throws Exception {
    final Graph g = TinkerGraph.open();
    final Vertex v = g.addVertex();
    final Map<String, Object> map = new HashMap<>();
    map.put("x", 500);
    map.put("y", "some");

    final ArrayList<Object> friends = new ArrayList<>();
    friends.add("x");
    friends.add(5);
    friends.add(map);

    v.property(VertexProperty.Cardinality.single, "friends", friends);

    final Iterable iterable = IteratorUtils.list(g.vertices());
    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 vertexAsJson = converted.get(0).get(GraphSONTokens.VALUEPROP);
    assertNotNull(vertexAsJson);

    final JsonNode properties = vertexAsJson.get(GraphSONTokens.PROPERTIES);
    assertNotNull(properties);
    assertEquals(1, properties.size());

    final JsonNode friendProperties = properties.get("friends");
    assertEquals(1, friendProperties.size());
    final JsonNode friendsProperty = friendProperties.get(0).get(GraphSONTokens.VALUEPROP).get(GraphSONTokens.VALUE);
    assertNotNull(friendsProperty);
    assertEquals(3, friendsProperty.size());

    final String object1 = friendsProperty.get(0).asText();
    assertEquals("x", object1);

    final int object2 = friendsProperty.get(1).get(GraphSONTokens.VALUEPROP).asInt();
    assertEquals(5, object2);

    final JsonNode object3 = friendsProperty.get(2);
    assertEquals(500, object3.get("x").get(GraphSONTokens.VALUEPROP).asInt());
    assertEquals("some", object3.get("y").asText());
}
 
Example 18
Source File: VertexBuilder.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Tuple<Vertex, String> build(Graph graph, Consumer<RelationData> relationRequestor) {
  Vertex vertex;
  if (labels.size() == 1) {
    // If there is exactly one label, it is still a valid tinkerpop vertex and needs to be passed to the
    // addVertex method. Otherwise the vertex also gets the label "vertex" and hasLabel will stop working
    vertex = graph.addVertex(labels.get(0));
  } else {
    vertex = graph.addVertex();
  }

  try {
    if (vres == null) {
      vres = Lists.newArrayList("");
    }
    if (type == null) {
      type = "<type>";
    }
    vertex.property("types", objectMapper.writeValueAsString(
      Lists.newArrayList(vres.stream().map(vre -> vre + type).iterator()))
    );
    if (timId != null) {
      vertex.property("tim_id", timId);
    }
    vertex.property("isLatest", isLatest);

    for (Map.Entry<String, Object> entry : properties.entrySet()) {
      vertex.property(entry.getKey(), entry.getValue());
    }

    if (labels.size() > 1) {
      for (String label : labels.subList(1, labels.size())) {
        ((Neo4jVertex) vertex).addLabel(label);
      }
    }
    relationList.forEach(relationDataBuilder -> {
      //can't be done earlier because vres might not be complete
      RelationData relationData = relationDataBuilder.build(vres);
      relationRequestor.accept(relationData);
    });

    return tuple(vertex, id);
  } catch (JsonProcessingException e) {
    throw new RuntimeException(e);
  }
}
 
Example 19
Source File: CommunityGeneratorTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
protected void afterLoadGraphWith(final Graph graph) throws Exception {
    final int numNodes = numberOfVertices;
    for (int i = 0; i < numNodes; i++) graph.addVertex("oid", i);
    tryCommit(graph);
}
 
Example 20
Source File: DistributionGeneratorTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
protected void afterLoadGraphWith(final Graph graph) throws Exception {
    final int numNodes = numberOfVertices;
    for (int i = 0; i < numNodes; i++) graph.addVertex("oid", i);
    tryCommit(graph);
}