org.apache.tinkerpop.gremlin.structure.util.Attachable Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.structure.util.Attachable. 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: GraphSONReader.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Read a {@link Vertex} from output generated by any of the {@link GraphSONWriter} {@code writeVertex} or
 * {@code writeVertices} methods or by {@link GraphSONWriter#writeGraph(OutputStream, Graph)}.
 *
 * @param inputStream a stream containing at least one {@link Vertex} as defined by the accompanying
 *                    {@link GraphWriter#writeVertices(OutputStream, Iterator, Direction)} method.
 * @param vertexAttachMethod a function that creates re-attaches a {@link Vertex} to a {@link Host} object.
 * @param edgeAttachMethod a function that creates re-attaches a {@link Edge} to a {@link Host} object.
 * @param attachEdgesOfThisDirection only edges of this direction are passed to the {@code edgeMaker}.
 */
@Override
public Vertex readVertex(final InputStream inputStream,
                         final Function<Attachable<Vertex>, Vertex> vertexAttachMethod,
                         final Function<Attachable<Edge>, Edge> edgeAttachMethod,
                         final Direction attachEdgesOfThisDirection) throws IOException {
    // graphson v3 has special handling for generic Map instances, by forcing to linkedhashmap (which is probably
    // what it should have been anyway) stargraph format can remain unchanged across all versions
    final Map<String, Object> vertexData = version == GraphSONVersion.V3_0 ?
            mapper.readValue(inputStream, linkedHashMapTypeReference) : mapper.readValue(inputStream, mapTypeReference);
    final StarGraph starGraph = StarGraphGraphSONDeserializer.readStarGraphVertex(vertexData);
    if (vertexAttachMethod != null) vertexAttachMethod.apply(starGraph.getStarVertex());

    if (vertexData.containsKey(GraphSONTokens.OUT_E) && (attachEdgesOfThisDirection == Direction.BOTH || attachEdgesOfThisDirection == Direction.OUT))
        StarGraphGraphSONDeserializer.readStarGraphEdges(edgeAttachMethod, starGraph, vertexData, GraphSONTokens.OUT_E);

    if (vertexData.containsKey(GraphSONTokens.IN_E) && (attachEdgesOfThisDirection == Direction.BOTH || attachEdgesOfThisDirection == Direction.IN))
        StarGraphGraphSONDeserializer.readStarGraphEdges(edgeAttachMethod, starGraph, vertexData, GraphSONTokens.IN_E);

    return starGraph.getStarVertex();
}
 
Example #2
Source File: StarGraphGraphSONDeserializer.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * A helper function for reading vertex edges from a serialized {@link StarGraph} (i.e. a {@code Map}) generated by
 * {@link StarGraphGraphSONSerializerV1d0}.
 */
public static void readStarGraphEdges(final Function<Attachable<Edge>, Edge> edgeMaker,
                                      final StarGraph starGraph,
                                      final Map<String, Object> vertexData,
                                      final String direction) throws IOException {
    final Map<String, List<Map<String,Object>>> edgeDatas = (Map<String, List<Map<String,Object>>>) vertexData.get(direction);
    for (Map.Entry<String, List<Map<String,Object>>> edgeData : edgeDatas.entrySet()) {
        for (Map<String,Object> inner : edgeData.getValue()) {
            final StarGraph.StarEdge starEdge;
            if (direction.equals(GraphSONTokens.OUT_E))
                starEdge = (StarGraph.StarEdge) starGraph.getStarVertex().addOutEdge(edgeData.getKey(), starGraph.addVertex(T.id, inner.get(GraphSONTokens.IN)), T.id, inner.get(GraphSONTokens.ID));
            else
                starEdge = (StarGraph.StarEdge) starGraph.getStarVertex().addInEdge(edgeData.getKey(), starGraph.addVertex(T.id, inner.get(GraphSONTokens.OUT)), T.id, inner.get(GraphSONTokens.ID));

            if (inner.containsKey(GraphSONTokens.PROPERTIES)) {
                final Map<String, Object> edgePropertyData = (Map<String, Object>) inner.get(GraphSONTokens.PROPERTIES);
                for (Map.Entry<String, Object> epd : edgePropertyData.entrySet()) {
                    starEdge.property(epd.getKey(), epd.getValue());
                }
            }

            if (edgeMaker != null) edgeMaker.apply(starEdge);
        }
    }
}
 
Example #3
Source File: GraknSparkExecutor.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
public static <M> JavaPairRDD<Object, VertexWritable> prepareFinalGraphRDD(
        final JavaPairRDD<Object, VertexWritable> graphRDD,
        final JavaPairRDD<Object, ViewIncomingPayload<M>> viewIncomingRDD,
        final Set<VertexComputeKey> vertexComputeKeys) {
    // the graphRDD and the viewRDD must have the same partitioner
    Preconditions.checkState(!graphRDD.partitioner().isPresent() || (graphRDD.partitioner().get().equals(viewIncomingRDD.partitioner().get())));
    final String[] vertexComputeKeysArray = VertexProgramHelper.vertexComputeKeysAsArray(vertexComputeKeys); // the compute keys as an array
    return graphRDD.leftOuterJoin(viewIncomingRDD)
            .mapValues(tuple -> {
                final StarGraph.StarVertex vertex = tuple._1().get();
                vertex.dropVertexProperties(vertexComputeKeysArray); // drop all existing compute keys
                // attach the final computed view to the cached graph
                final List<DetachedVertexProperty<Object>> view = tuple._2().isPresent() ? tuple._2().get().getView() : Collections.emptyList();
                for (final DetachedVertexProperty<Object> property : view) {
                    if (!VertexProgramHelper.isTransientVertexComputeKey(property.key(), vertexComputeKeys)){
                        property.attach(Attachable.Method.create(vertex));}
                }
                return tuple._1();
            });
}
 
Example #4
Source File: TinkerIoRegistryV3d0.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Override
public TinkerGraph deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals("vertices")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedVertex v = (DetachedVertex) deserializationContext.readValue(jsonParser, Vertex.class);
                    v.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        } else if (jsonParser.getCurrentName().equals("edges")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedEdge e = (DetachedEdge) deserializationContext.readValue(jsonParser, Edge.class);
                    e.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        }
    }

    return graph;
}
 
Example #5
Source File: TinkerIoRegistryV2d0.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Override
public TinkerGraph deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals("vertices")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedVertex v = (DetachedVertex) deserializationContext.readValue(jsonParser, Vertex.class);
                    v.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        } else if (jsonParser.getCurrentName().equals("edges")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedEdge e = (DetachedEdge) deserializationContext.readValue(jsonParser, Edge.class);
                    e.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        }
    }

    return graph;
}
 
Example #6
Source File: GraphSONReader.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Read an {@link Edge} from output generated by {@link GraphSONWriter#writeEdge(OutputStream, Edge)} or via
 * an {@link Edge} passed to {@link GraphSONWriter#writeObject(OutputStream, Object)}.
 *
 * @param inputStream a stream containing at least one {@link Edge} as defined by the accompanying
 *                    {@link GraphWriter#writeEdge(OutputStream, Edge)} method.
 * @param edgeAttachMethod a function that creates re-attaches a {@link Edge} to a {@link Host} object.
 */
@Override
public Edge readEdge(final InputStream inputStream, final Function<Attachable<Edge>, Edge> edgeAttachMethod) throws IOException {
    if (version == GraphSONVersion.V1_0) {
        final Map<String, Object> edgeData = mapper.readValue(inputStream, mapTypeReference);

        final Map<String, Object> edgeProperties = edgeData.containsKey(GraphSONTokens.PROPERTIES) ?
                (Map<String, Object>) edgeData.get(GraphSONTokens.PROPERTIES) : Collections.EMPTY_MAP;
        final DetachedEdge edge = new DetachedEdge(edgeData.get(GraphSONTokens.ID),
                edgeData.get(GraphSONTokens.LABEL).toString(),
                edgeProperties,
                edgeData.get(GraphSONTokens.OUT), edgeData.get(GraphSONTokens.OUT_LABEL).toString(),
                edgeData.get(GraphSONTokens.IN), edgeData.get(GraphSONTokens.IN_LABEL).toString());

        return edgeAttachMethod.apply(edge);
    } else {
        return edgeAttachMethod.apply((DetachedEdge) mapper.readValue(inputStream, Edge.class));
    }
}
 
Example #7
Source File: AddEdgeStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected Edge map(final Traverser.Admin<S> traverser) {
    Vertex toVertex = this.parameters.get(traverser, TO, () -> (Vertex) traverser.get()).get(0);
    Vertex fromVertex = this.parameters.get(traverser, FROM, () -> (Vertex) traverser.get()).get(0);
    if (toVertex instanceof Attachable)
        toVertex = ((Attachable<Vertex>) toVertex)
                .attach(Attachable.Method.get(this.getTraversal().getGraph().orElse(EmptyGraph.instance())));
    if (fromVertex instanceof Attachable)
        fromVertex = ((Attachable<Vertex>) fromVertex)
                .attach(Attachable.Method.get(this.getTraversal().getGraph().orElse(EmptyGraph.instance())));
    final String edgeLabel = this.parameters.get(traverser, T.label, () -> Edge.DEFAULT_LABEL).get(0);

    final Edge edge = fromVertex.addEdge(edgeLabel, toVertex, this.parameters.getKeyValues(traverser, TO, FROM, T.label));
    if (callbackRegistry != null) {
        final EventStrategy eventStrategy = getTraversal().getStrategies().getStrategy(EventStrategy.class).get();
        final Event.EdgeAddedEvent vae = new Event.EdgeAddedEvent(eventStrategy.detach(edge));
        callbackRegistry.getCallbacks().forEach(c -> c.accept(vae));
    }
    return edge;
}
 
Example #8
Source File: StarGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void shouldAttachWithGetMethod() {
    // vertex host
    g.V().forEachRemaining(vertex -> TestHelper.validateEquality(vertex, StarGraph.of(vertex).getStarVertex().attach(Attachable.Method.get(vertex))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().properties().forEachRemaining(vertexProperty -> TestHelper.validateEquality(vertexProperty, ((Attachable<VertexProperty>) vertexProperty).attach(Attachable.Method.get(vertex)))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().properties().forEachRemaining(vertexProperty -> vertexProperty.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ((Attachable<Property>) property).attach(Attachable.Method.get(vertex))))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().edges(Direction.OUT).forEachRemaining(edge -> TestHelper.validateEquality(edge, ((Attachable<Edge>) edge).attach(Attachable.Method.get(vertex)))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().edges(Direction.OUT).forEachRemaining(edge -> edge.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ((Attachable<Property>) property).attach(Attachable.Method.get(vertex))))));

    // graph host
    g.V().forEachRemaining(vertex -> TestHelper.validateEquality(vertex, StarGraph.of(vertex).getStarVertex().attach(Attachable.Method.get(graph))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().properties().forEachRemaining(vertexProperty -> TestHelper.validateEquality(vertexProperty, ((Attachable<VertexProperty>) vertexProperty).attach(Attachable.Method.get(graph)))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().properties().forEachRemaining(vertexProperty -> vertexProperty.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ((Attachable<Property>) property).attach(Attachable.Method.get(graph))))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().edges(Direction.OUT).forEachRemaining(edge -> TestHelper.validateEquality(edge, ((Attachable<Edge>) edge).attach(Attachable.Method.get(graph)))));
    g.V().forEachRemaining(vertex -> StarGraph.of(vertex).getStarVertex().edges(Direction.OUT).forEachRemaining(edge -> edge.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ((Attachable<Property>) property).attach(Attachable.Method.get(graph))))));
}
 
Example #9
Source File: StarGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_PROPERTY)
public void shouldAttachWithCreateMethod() {
    final Random random = TestHelper.RANDOM;
    StarGraph starGraph = StarGraph.open();
    Vertex starVertex = starGraph.addVertex(T.label, "person", "name", "stephen", "name", "spmallete");
    starVertex.property("acl", true, "timestamp", random.nextLong(), "creator", "marko");
    for (int i = 0; i < 100; i++) {
        starVertex.addEdge("knows", starGraph.addVertex("person", "name", new UUID(random.nextLong(), random.nextLong()), "since", random.nextLong()));
        starGraph.addVertex(T.label, "project").addEdge("developedBy", starVertex, "public", random.nextBoolean());
    }
    final Vertex createdVertex = starGraph.getStarVertex().attach(Attachable.Method.create(graph));
    starGraph.getStarVertex().edges(Direction.BOTH).forEachRemaining(edge -> ((Attachable<Edge>) edge).attach(Attachable.Method.create(random.nextBoolean() ? graph : createdVertex)));
    TestHelper.validateEquality(starVertex, createdVertex);
}
 
Example #10
Source File: DetachedGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void testAttachableGetMethod() {
    // vertex host
    g.V().forEachRemaining(vertex -> TestHelper.validateEquality(vertex, DetachedFactory.detach(vertex, true).attach(Attachable.Method.get(vertex))));
    g.V().forEachRemaining(vertex -> vertex.properties().forEachRemaining(vertexProperty -> TestHelper.validateEquality(vertexProperty, DetachedFactory.detach(vertexProperty, true).attach(Attachable.Method.get(vertex)))));
    g.V().forEachRemaining(vertex -> vertex.properties().forEachRemaining(vertexProperty -> vertexProperty.properties().forEachRemaining(property -> TestHelper.validateEquality(property, DetachedFactory.detach(property).attach(Attachable.Method.get(vertex))))));
    g.V().forEachRemaining(vertex -> vertex.edges(Direction.OUT).forEachRemaining(edge -> TestHelper.validateEquality(edge, DetachedFactory.detach(edge, true).attach(Attachable.Method.get(vertex)))));
    g.V().forEachRemaining(vertex -> vertex.edges(Direction.OUT).forEachRemaining(edge -> edge.properties().forEachRemaining(property -> TestHelper.validateEquality(property, DetachedFactory.detach(property).attach(Attachable.Method.get(vertex))))));

    // graph host
    g.V().forEachRemaining(vertex -> TestHelper.validateEquality(vertex, DetachedFactory.detach(vertex, true).attach(Attachable.Method.get(graph))));
    g.V().forEachRemaining(vertex -> vertex.properties().forEachRemaining(vertexProperty -> TestHelper.validateEquality(vertexProperty, DetachedFactory.detach(vertexProperty, true).attach(Attachable.Method.get(graph)))));
    g.V().forEachRemaining(vertex -> vertex.properties().forEachRemaining(vertexProperty -> vertexProperty.properties().forEachRemaining(property -> TestHelper.validateEquality(property, DetachedFactory.detach(property).attach(Attachable.Method.get(graph))))));
    g.V().forEachRemaining(vertex -> vertex.edges(Direction.OUT).forEachRemaining(edge -> TestHelper.validateEquality(edge, DetachedFactory.detach(edge, true).attach(Attachable.Method.get(graph)))));
    g.V().forEachRemaining(vertex -> vertex.edges(Direction.OUT).forEachRemaining(edge -> edge.properties().forEachRemaining(property -> TestHelper.validateEquality(property, DetachedFactory.detach(property).attach(Attachable.Method.get(graph))))));

}
 
Example #11
Source File: ReferenceGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void testAttachableGetMethod() {
    // vertex host
    g.V().forEachRemaining(vertex -> TestHelper.validateEquality(vertex, ReferenceFactory.detach(vertex).attach(Attachable.Method.get(vertex))));
    g.V().forEachRemaining(vertex -> vertex.properties().forEachRemaining(vertexProperty -> TestHelper.validateEquality(vertexProperty, ReferenceFactory.detach(vertexProperty).attach(Attachable.Method.get(vertex)))));
    g.V().forEachRemaining(vertex -> vertex.properties().forEachRemaining(vertexProperty -> vertexProperty.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ReferenceFactory.detach(property).attach(Attachable.Method.get(vertex))))));
    g.V().forEachRemaining(vertex -> vertex.edges(Direction.OUT).forEachRemaining(edge -> TestHelper.validateEquality(edge, ReferenceFactory.detach(edge).attach(Attachable.Method.get(vertex)))));
    g.V().forEachRemaining(vertex -> vertex.edges(Direction.OUT).forEachRemaining(edge -> edge.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ReferenceFactory.detach(property).attach(Attachable.Method.get(vertex))))));

    // graph host
    g.V().forEachRemaining(vertex -> TestHelper.validateEquality(vertex, ReferenceFactory.detach(vertex).attach(Attachable.Method.get(graph))));
    g.V().forEachRemaining(vertex -> vertex.properties().forEachRemaining(vertexProperty -> TestHelper.validateEquality(vertexProperty, ReferenceFactory.detach(vertexProperty).attach(Attachable.Method.get(graph)))));
    g.V().forEachRemaining(vertex -> vertex.properties().forEachRemaining(vertexProperty -> vertexProperty.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ReferenceFactory.detach(property).attach(Attachable.Method.get(graph))))));
    g.V().forEachRemaining(vertex -> vertex.edges(Direction.OUT).forEachRemaining(edge -> TestHelper.validateEquality(edge, ReferenceFactory.detach(edge).attach(Attachable.Method.get(graph)))));
    g.V().forEachRemaining(vertex -> vertex.edges(Direction.OUT).forEachRemaining(edge -> edge.properties().forEachRemaining(property -> TestHelper.validateEquality(property, ReferenceFactory.detach(property).attach(Attachable.Method.get(graph))))));

}
 
Example #12
Source File: TinkerIoRegistryV3d0.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public TinkerGraph deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals("vertices")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedVertex v = (DetachedVertex) deserializationContext.readValue(jsonParser, Vertex.class);
                    v.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        } else if (jsonParser.getCurrentName().equals("edges")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedEdge e = (DetachedEdge) deserializationContext.readValue(jsonParser, Edge.class);
                    e.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        }
    }

    return graph;
}
 
Example #13
Source File: TinkerIoRegistryV2d0.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public TinkerGraph deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals("vertices")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedVertex v = (DetachedVertex) deserializationContext.readValue(jsonParser, Vertex.class);
                    v.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        } else if (jsonParser.getCurrentName().equals("edges")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedEdge e = (DetachedEdge) deserializationContext.readValue(jsonParser, Edge.class);
                    e.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        }
    }

    return graph;
}
 
Example #14
Source File: SparkExecutor.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static <M> JavaPairRDD<Object, VertexWritable> prepareFinalGraphRDD(
        final JavaPairRDD<Object, VertexWritable> graphRDD,
        final JavaPairRDD<Object, ViewIncomingPayload<M>> viewIncomingRDD,
        final Set<VertexComputeKey> vertexComputeKeys) {
    // the graphRDD and the viewRDD must have the same partitioner
    if (graphRDD.partitioner().isPresent())
        assert (graphRDD.partitioner().get().equals(viewIncomingRDD.partitioner().get()));
    final String[] vertexComputeKeysArray = VertexProgramHelper.vertexComputeKeysAsArray(vertexComputeKeys); // the compute keys as an array
    return graphRDD.leftOuterJoin(viewIncomingRDD)
            .mapValues(tuple -> {
                final StarGraph.StarVertex vertex = tuple._1().get();
                vertex.dropVertexProperties(vertexComputeKeysArray); // drop all existing compute keys
                // attach the final computed view to the cached graph
                final List<DetachedVertexProperty<Object>> view = tuple._2().isPresent() ? tuple._2().get().getView() : Collections.emptyList();
                for (final DetachedVertexProperty<Object> property : view) {
                    if (!VertexProgramHelper.isTransientVertexComputeKey(property.key(), vertexComputeKeys))
                        property.attach(Attachable.Method.create(vertex));
                }
                return tuple._1();
            });
}
 
Example #15
Source File: ReferenceVertexPropertyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldAttachToVertex() {
    final Vertex v = graph.addVertex();
    final VertexProperty toReference = v.property(VertexProperty.Cardinality.single, "test", "this");
    final ReferenceVertexProperty<?> rvp = ReferenceFactory.detach(toReference);
    final VertexProperty referenced = rvp.attach(Attachable.Method.get(v));

    assertEquals(toReference, referenced);
    assertEquals(toReference.getClass(), referenced.getClass());
    assertFalse(referenced instanceof ReferenceVertexProperty);
}
 
Example #16
Source File: DriverRemoteTraversal.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Traverser.Admin<E> next() {
    final Traverser.Admin<E> traverser = super.next();
    if (traverser.get() instanceof Attachable && !(traverser.get() instanceof Property))
        traverser.set((E) ((Attachable<Element>) traverser.get()).attach(Attachable.Method.get(graph)));
    return traverser;
}
 
Example #17
Source File: ReferenceVertexTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAttachToVertex() {
    final Vertex v = g.V(convertToVertexId("josh")).next();
    final ReferenceVertex referenceVertex = ReferenceFactory.detach(v);
    final Vertex attachedV = referenceVertex.attach(Attachable.Method.get(v));

    assertEquals(v, attachedV);
    assertFalse(attachedV instanceof ReferenceVertex);
}
 
Example #18
Source File: ReferenceVertexTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAttachToGraph() {
    final Vertex v = g.V(convertToVertexId("josh")).next();
    final ReferenceVertex referenceVertex = ReferenceFactory.detach(v);
    final Vertex attachedV = referenceVertex.attach(Attachable.Method.get(graph));

    assertEquals(v, attachedV);
    assertFalse(attachedV instanceof ReferenceVertex);
}
 
Example #19
Source File: ReferenceVertexPropertyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldAttachToGraph() {
    final Vertex v = graph.addVertex();
    final VertexProperty toReference = v.property(VertexProperty.Cardinality.single, "test", "this");
    final ReferenceVertexProperty<?> rvp = ReferenceFactory.detach(toReference);
    final VertexProperty referenced = rvp.attach(Attachable.Method.get(graph));

    assertEquals(toReference, referenced);
    assertFalse(referenced instanceof ReferenceVertexProperty);
}
 
Example #20
Source File: DetachedEdgeTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(GraphData.MODERN)
public void shouldAttachToGraph() {
    final Edge toDetach = g.E(convertToEdgeId("josh", "created", "lop")).next();
    final DetachedEdge detachedEdge = DetachedFactory.detach(toDetach, true);
    final Edge attached = detachedEdge.attach(Attachable.Method.get(graph));

    assertEquals(toDetach, attached);
    assertFalse(attached instanceof DetachedEdge);
}
 
Example #21
Source File: DetachedGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_PROPERTY)
public void testAttachableCreateMethod() {
    final Random random = TestHelper.RANDOM;
    StarGraph starGraph = StarGraph.open();
    Vertex starVertex = starGraph.addVertex(T.label, "person", "name", "stephen", "name", "spmallete");
    starVertex.property("acl", true, "timestamp", random.nextLong(), "creator", "marko");
    for (int i = 0; i < 100; i++) {
        starVertex.addEdge("knows", starGraph.addVertex("person", "name", new UUID(random.nextLong(), random.nextLong()), "since", random.nextLong()));
        starGraph.addVertex(T.label, "project").addEdge("developedBy", starVertex, "public", random.nextBoolean());
    }
    final DetachedVertex detachedVertex = DetachedFactory.detach(starGraph.getStarVertex(), true);
    final Vertex createdVertex = detachedVertex.attach(Attachable.Method.create(graph));
    TestHelper.validateVertexEquality(detachedVertex, createdVertex, false);
    TestHelper.validateVertexEquality(detachedVertex, starVertex, false);

    starGraph.getStarVertex().edges(Direction.BOTH).forEachRemaining(starEdge -> {
        final DetachedEdge detachedEdge = DetachedFactory.detach(starEdge, true);
        final Edge createdEdge = detachedEdge.attach(Attachable.Method.create(random.nextBoolean() ? graph : createdVertex));
        TestHelper.validateEdgeEquality(detachedEdge, starEdge);
        TestHelper.validateEdgeEquality(detachedEdge, createdEdge);
    });

}
 
Example #22
Source File: DetachedVertexPropertyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldAttachToVertex() {
    final Vertex v = graph.addVertex();
    final VertexProperty toDetach = v.property(VertexProperty.Cardinality.single, "test", "this");
    final DetachedVertexProperty<?> detached = DetachedFactory.detach(toDetach, true);
    final VertexProperty attached = detached.attach(Attachable.Method.get(v));

    assertEquals(toDetach, attached);
    assertEquals(toDetach.getClass(), attached.getClass());
    assertFalse(attached instanceof DetachedVertexProperty);
}
 
Example #23
Source File: DetachedVertexPropertyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldAttachToGraph() {
    final Vertex v = graph.addVertex();
    final VertexProperty toDetach = v.property(VertexProperty.Cardinality.single, "test", "this");
    final DetachedVertexProperty<?> detached = DetachedFactory.detach(toDetach, true);
    final VertexProperty attached = detached.attach(Attachable.Method.get(graph));

    assertEquals(toDetach, attached);
    assertFalse(attached instanceof DetachedVertexProperty);
}
 
Example #24
Source File: DetachedPropertyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAttachToVertex() {
    final Edge e = g.E(convertToEdgeId("josh", "created", "lop")).next();
    final Property toDetach = e.property("weight");
    final DetachedProperty<?> detachedProperty = DetachedFactory.detach(toDetach);
    final Property attached = detachedProperty.attach(Attachable.Method.get(e.outVertex()));

    assertEquals(toDetach, attached);
    assertFalse(attached instanceof DetachedProperty);
}
 
Example #25
Source File: DetachedPropertyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAttachToGraph() {
    final Edge e = g.E(convertToEdgeId("josh", "created", "lop")).next();
    final Property toDetach = e.properties("weight").next();
    final DetachedProperty<?> detachedProperty = DetachedFactory.detach(toDetach);
    final Property attached = detachedProperty.attach(Attachable.Method.get(graph));

    assertEquals(toDetach, attached);
    assertFalse(attached instanceof DetachedProperty);
}
 
Example #26
Source File: StarGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_PROPERTY)
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldCopyFromGraphAToGraphB() throws Exception {
    final List<StarGraph> starGraphs = IteratorUtils.stream(graph.vertices()).map(StarGraph::of).collect(Collectors.toList());

    // via vertices and then edges
    final Configuration g1Configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName(), null);
    Graph g1 = graphProvider.openTestGraph(g1Configuration);
    starGraphs.stream().map(StarGraph::getStarVertex).forEach(vertex -> vertex.attach(Attachable.Method.getOrCreate(g1)));
    starGraphs.stream().forEach(starGraph -> starGraph.edges().forEachRemaining(edge -> ((Attachable<Edge>) edge).attach(Attachable.Method.getOrCreate(g1))));
    assertEquals(IteratorUtils.count(graph.vertices()), IteratorUtils.count(g1.vertices()));
    assertEquals(IteratorUtils.count(graph.edges()), IteratorUtils.count(g1.edges()));
    graph.vertices().forEachRemaining(vertex -> TestHelper.validateVertexEquality(vertex, g1.vertices(vertex.id()).next(), true));
    graphProvider.clear(g1, g1Configuration);

    // via edges only
    final Configuration g2Configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName(), null);
    final Graph g2 = graphProvider.openTestGraph(g2Configuration);
    starGraphs.stream().forEach(starGraph -> starGraph.edges().forEachRemaining(edge -> ((Attachable<Edge>) edge).attach(Attachable.Method.getOrCreate(g2))));
    assertEquals(IteratorUtils.count(graph.vertices()), IteratorUtils.count(g2.vertices()));
    assertEquals(IteratorUtils.count(graph.edges()), IteratorUtils.count(g2.edges()));
    // TODO: you can't get adjacent labels -- graph.vertices().forEachRemaining(vertex -> TestHelper.validateVertexEquality(vertex, g1.vertices(vertex.id()).next(), true));
    graphProvider.clear(g2, g2Configuration);
}
 
Example #27
Source File: ComputerResultStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public Iterator<Traverser.Admin<S>> attach(final Iterator<Traverser.Admin<S>> iterator, final Graph graph) {
    return IteratorUtils.map(iterator, traverser -> {
        traverser.setSideEffects(this.getTraversal().getSideEffects());   // necessary to ensure no NPE
        if (this.attachElements && (traverser.get() instanceof Attachable) && !(traverser.get() instanceof Property))
            traverser.set((S) ((Attachable<Element>) traverser.get()).attach(Attachable.Method.get(graph)));
        return traverser;
    });
}
 
Example #28
Source File: AbstractTraverser.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public T attach(final Function<Attachable<T>, T> method) {
    // you do not want to attach a path because it will reference graph objects not at the current vertex
    if (this.t instanceof Attachable && !(((Attachable) this.t).get() instanceof Path))
        this.t = ((Attachable<T>) this.t).attach(method);
    return this.t;
}
 
Example #29
Source File: AddEdgeStartStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected Traverser.Admin<Edge> processNextStart() {
    if (this.first) {
        this.first = false;
        final TraverserGenerator generator = this.getTraversal().getTraverserGenerator();
        final Traverser.Admin traverser = generator.generate(1, (Step) this, 1); // a dead traverser to trigger the traversal
        Vertex toVertex = (Vertex) this.parameters.get(traverser, TO, Collections::emptyList).get(0);
        Vertex fromVertex = (Vertex) this.parameters.get(traverser, FROM, Collections::emptyList).get(0);
        if (toVertex instanceof Attachable)
            toVertex = ((Attachable<Vertex>) toVertex)
                    .attach(Attachable.Method.get(this.getTraversal().getGraph().orElse(EmptyGraph.instance())));
        if (fromVertex instanceof Attachable)
            fromVertex = ((Attachable<Vertex>) fromVertex)
                    .attach(Attachable.Method.get(this.getTraversal().getGraph().orElse(EmptyGraph.instance())));
        final String edgeLabel = (String) this.parameters.get(traverser, T.label, () -> Edge.DEFAULT_LABEL).get(0);
        final Edge edge = fromVertex.addEdge(edgeLabel, toVertex, this.parameters.getKeyValues(traverser, TO, FROM, T.label));
        if (callbackRegistry != null) {
            final EventStrategy eventStrategy = getTraversal().getStrategies().getStrategy(EventStrategy.class).get();
            final Event.EdgeAddedEvent vae = new Event.EdgeAddedEvent(eventStrategy.detach(edge));
            callbackRegistry.getCallbacks().forEach(c -> c.accept(vae));
        }
        return generator.generate(edge, this, 1L);
    } else
        throw FastNoSuchElementException.instance();


}
 
Example #30
Source File: GryoReader.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Read data into a {@link Graph} from output generated by any of the {@link GryoWriter} {@code writeVertex} or
 * {@code writeVertices} methods or by {@link GryoWriter#writeGraph(OutputStream, Graph)}.
 *
 * @param inputStream    a stream containing an entire graph of vertices and edges as defined by the accompanying
 *                       {@link GraphWriter#writeGraph(OutputStream, Graph)}.
 * @param graphToWriteTo the graph to write to when reading from the stream.
 * @throws IOException
 */
@Override
public void readGraph(final InputStream inputStream, final Graph graphToWriteTo) throws IOException {
    // dual pass - create all vertices and store to cache the ids.  then create edges.  as long as we don't
    // have vertex labels in the output we can't do this single pass
    final Map<StarGraph.StarVertex, Vertex> cache = new HashMap<>();
    final AtomicLong counter = new AtomicLong(0);

    final Graph.Features.EdgeFeatures edgeFeatures = graphToWriteTo.features().edge();
    final boolean supportsTx = graphToWriteTo.features().graph().supportsTransactions();

    IteratorUtils.iterate(new VertexInputIterator(new Input(inputStream), attachable -> {
        final Vertex v = cache.put((StarGraph.StarVertex) attachable.get(), attachable.attach(Attachable.Method.create(graphToWriteTo)));
        if (supportsTx && counter.incrementAndGet() % batchSize == 0)
            graphToWriteTo.tx().commit();
        return v;
    }, null, null));
    cache.entrySet().forEach(kv -> kv.getKey().edges(Direction.IN).forEachRemaining(e -> {
        // can't use a standard Attachable attach method here because we have to use the cache for those
        // graphs that don't support userSuppliedIds on edges. note that outVertex/inVertex methods return
        // StarAdjacentVertex whose equality should match StarVertex.
        final Vertex cachedOutV = cache.get(e.outVertex());
        final Vertex cachedInV = cache.get(e.inVertex());

        if (null == cachedOutV) throw new IllegalStateException(String.format("Could not find outV with id [%s] to create edge with id [%s]", e.outVertex().id(), e.id()));
        if (null == cachedInV) throw new IllegalStateException(String.format("Could not find inV with id [%s] to create edge with id [%s]", e.inVertex().id(), e.id()));

        final Edge newEdge = edgeFeatures.willAllowId(e.id()) ? cachedOutV.addEdge(e.label(), cachedInV, T.id, e.id()) : cachedOutV.addEdge(e.label(), cachedInV);
        e.properties().forEachRemaining(p -> newEdge.property(p.key(), p.value()));
        if (supportsTx && counter.incrementAndGet() % batchSize == 0)
            graphToWriteTo.tx().commit();
    }));

    if (supportsTx) graphToWriteTo.tx().commit();
}