org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge. 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: TestLoadEdge.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void shouldConstructDetachedEdge() {
    Graph g = this.sqlgGraph;
    loadModern();
    assertModernGraph(g, true, false);
    Edge e = g.traversal().E(convertToEdgeId("marko", "knows", "vadas")).next();
    e.property("year", 2002);
    g.tx().commit();
    e = g.traversal().E(convertToEdgeId("marko", "knows", "vadas")).next();
    final DetachedEdge detachedEdge = DetachedFactory.detach(e, true);
    Assert.assertEquals(convertToEdgeId("marko", "knows", "vadas"), detachedEdge.id());

    Assert.assertEquals("knows", detachedEdge.label());
    Assert.assertEquals(DetachedVertex.class, detachedEdge.vertices(Direction.OUT).next().getClass());
    Assert.assertEquals(convertToVertexId("marko"), detachedEdge.vertices(Direction.OUT).next().id());
    Assert.assertEquals("person", detachedEdge.vertices(Direction.IN).next().label());
    Assert.assertEquals(DetachedVertex.class, detachedEdge.vertices(Direction.IN).next().getClass());
    Assert.assertEquals(convertToVertexId("vadas"), detachedEdge.vertices(Direction.IN).next().id());
    Assert.assertEquals("person", detachedEdge.vertices(Direction.IN).next().label());

    Assert.assertEquals(2, IteratorUtils.count(detachedEdge.properties()));
    Assert.assertEquals(1, IteratorUtils.count(detachedEdge.properties("year")));
    Assert.assertEquals(0.5d, detachedEdge.properties("weight").next().value());
}
 
Example #2
Source File: HaltedTraverserStrategyTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnDetachedElements() {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.create(new MapConfiguration(new HashMap<String, Object>() {{
        put(HaltedTraverserStrategy.HALTED_TRAVERSER_FACTORY, DetachedFactory.class.getCanonicalName());
    }})));
    g.V().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(DetachedVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(DetachedEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(DetachedProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(DetachedPath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    // should handle nested collections
    g.V().out().fold().next().forEach(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
}
 
Example #3
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 #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: HaltedTraverserStrategyTest.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnDetachedElements() {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.create(new MapConfiguration(new HashMap<String, Object>() {{
        put(HaltedTraverserStrategy.HALTED_TRAVERSER_FACTORY, DetachedFactory.class.getCanonicalName());
    }})));
    g.V().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(DetachedVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(DetachedEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(DetachedProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(DetachedPath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    // should handle nested collections
    g.V().out().fold().next().forEach(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
}
 
Example #7
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 #8
Source File: GryoSerializersV3d0.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public <I extends InputShim> Edge read(final KryoShim<I, ?> kryo, final I input, final Class<Edge> edgeClass) {
    final DetachedEdge.Builder builder = DetachedEdge.build();
    builder.setId(kryo.readClassAndObject(input));
    builder.setLabel(input.readString());

    final DetachedVertex.Builder inV = DetachedVertex.build();
    inV.setId(kryo.readClassAndObject(input));
    inV.setLabel(input.readString());
    builder.setInV(inV.create());

    final DetachedVertex.Builder outV = DetachedVertex.build();
    outV.setId(kryo.readClassAndObject(input));
    outV.setLabel(input.readString());
    builder.setOutV(outV.create());

    while(input.readBoolean()) {
        builder.addProperty(new DetachedProperty<>(input.readString(), kryo.readClassAndObject(input)));
    }

    return builder.create();
}
 
Example #9
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 #10
Source File: SerializationTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeEdgeAsDetached() throws Exception {
    final GryoIo gryoIo = graph.io(GryoIo.build(GryoVersion.V1_0));
    final GryoWriter gryoWriter = gryoIo.writer().create();
    final GryoReader gryoReader = gryoIo.reader().create();

    final Edge e = g.E(convertToEdgeId("marko", "knows", "vadas")).next();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    gryoWriter.writeObject(outputStream, e);

    final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    final Edge detached = gryoReader.readObject(inputStream, DetachedEdge.class);
    assertNotNull(detached);
    assertEquals(e.label(), detached.label());
    assertEquals(e.id(), detached.id());
    assertEquals((Double) e.value("weight"), detached.value("weight"));
}
 
Example #11
Source File: SerializationTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeEdgeAsDetached() throws Exception {
    final GryoIo gryoIo = graph.io(GryoIo.build(GryoVersion.V3_0));
    final GryoWriter gryoWriter = gryoIo.writer().create();
    final GryoReader gryoReader = gryoIo.reader().create();

    final Edge e = g.E(convertToEdgeId("marko", "knows", "vadas")).next();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    gryoWriter.writeObject(outputStream, e);

    final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    final Edge detached = gryoReader.readObject(inputStream, DetachedEdge.class);
    assertNotNull(detached);
    assertEquals(e.label(), detached.label());
    assertEquals(e.id(), detached.id());
    assertEquals((Double) e.value("weight"), detached.value("weight"));
}
 
Example #12
Source File: GraphSONSerializersV2d0.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Edge deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final DetachedEdge.Builder e = DetachedEdge.build();
    final DetachedVertex.Builder inV = DetachedVertex.build();
    final DetachedVertex.Builder outV = DetachedVertex.build();
    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals(GraphSONTokens.ID)) {
            jsonParser.nextToken();
            e.setId(deserializationContext.readValue(jsonParser, Object.class));
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.LABEL)) {
            jsonParser.nextToken();
            e.setLabel(jsonParser.getText());
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.OUT)) {
            jsonParser.nextToken();
            outV.setId(deserializationContext.readValue(jsonParser, Object.class));
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.OUT_LABEL)) {
            jsonParser.nextToken();
            outV.setLabel(jsonParser.getText());
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.IN)) {
            jsonParser.nextToken();
            inV.setId(deserializationContext.readValue(jsonParser, Object.class));
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.IN_LABEL)) {
            jsonParser.nextToken();
            inV.setLabel(jsonParser.getText());
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.PROPERTIES)) {
            jsonParser.nextToken();
            while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
                jsonParser.nextToken();
                e.addProperty(deserializationContext.readValue(jsonParser, Property.class));
            }
        }
    }

    e.setInV(inV.create());
    e.setOutV(outV.create());

    return e.create();
}
 
Example #13
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldDetachEdgeWhenAdded() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final Object id = v.id();

    final MutationListener listener = new AbstractMutationListener() {
        @Override
        public void edgeAdded(final Edge element) {
            assertThat(element, instanceOf(DetachedEdge.class));
            assertEquals("self", element.label());
            assertEquals(id, element.inVertex().id());
            assertEquals(id, element.outVertex().id());
            assertEquals("there", element.value("here"));
            triggered.set(true);
        }
    };
    final EventStrategy.Builder builder = EventStrategy.build().addListener(listener);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();
    final GraphTraversalSource gts = create(eventStrategy);

    gts.V(v).as("a").addE("self").property("here", "there").from("a").to("a").iterate();
    tryCommit(graph);

    assertVertexEdgeCounts(graph, 1, 1);
    assertThat(triggered.get(), is(true));
}
 
Example #14
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldDetachEdgeWhenRemoved() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final Edge e = v.addEdge("self", v, "dropped", "yay!");
    final String label = e.label();
    final Object inId = v.id();
    final Object outId = v.id();

    final MutationListener listener = new AbstractMutationListener() {
        @Override
        public void edgeRemoved(final Edge element) {
            assertThat(element, instanceOf(DetachedEdge.class));
            assertEquals(label, element.label());
            assertEquals(inId, element.inVertex().id());
            assertEquals(outId, element.outVertex().id());
            triggered.set(true);
        }
    };
    final EventStrategy.Builder builder = EventStrategy.build().addListener(listener);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();
    final GraphTraversalSource gts = create(eventStrategy);

    gts.E(e).drop().iterate();
    tryCommit(graph);

    assertVertexEdgeCounts(graph, 1, 0);
    assertThat(triggered.get(), is(true));
}
 
Example #15
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldDetachPropertyOfEdgeWhenNew() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final Edge e = v.addEdge("self", v);
    final String label = e.label();
    final Object inId = v.id();
    final Object outId = v.id();
    e.property("to-change", "no!");

    final MutationListener listener = new AbstractMutationListener() {
        @Override
        public void edgePropertyChanged(final Edge element, final Property oldValue, final Object setValue) {
            assertThat(element, instanceOf(DetachedEdge.class));
            assertEquals(label, element.label());
            assertEquals(inId, element.inVertex().id());
            assertEquals(outId, element.outVertex().id());
            assertThat(oldValue, instanceOf(KeyedProperty.class));
            assertEquals("new", oldValue.key());
            assertEquals("yay!", setValue);
            triggered.set(true);
        }
    };
    final EventStrategy.Builder builder = EventStrategy.build().addListener(listener);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();
    final GraphTraversalSource gts = create(eventStrategy);

    gts.E(e).property("new","yay!").iterate();
    tryCommit(graph);

    assertEquals(2, IteratorUtils.count(g.E(e).properties()));
    assertThat(triggered.get(), is(true));
}
 
Example #16
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldDetachPropertyOfEdgeWhenChanged() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final Edge e = v.addEdge("self", v);
    final String label = e.label();
    final Object inId = v.id();
    final Object outId = v.id();
    e.property("to-change", "no!");

    final MutationListener listener = new AbstractMutationListener() {
        @Override
        public void edgePropertyChanged(final Edge element, final Property oldValue, final Object setValue) {
            assertThat(element, instanceOf(DetachedEdge.class));
            assertEquals(label, element.label());
            assertEquals(inId, element.inVertex().id());
            assertEquals(outId, element.outVertex().id());
            assertEquals("no!", oldValue.value());
            assertEquals("to-change", oldValue.key());
            assertEquals("yay!", setValue);
            triggered.set(true);
        }
    };
    final EventStrategy.Builder builder = EventStrategy.build().addListener(listener);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();
    final GraphTraversalSource gts = create(eventStrategy);

    gts.E(e).property("to-change","yay!").iterate();
    tryCommit(graph);

    assertEquals(1, IteratorUtils.count(g.E(e).properties()));
    assertThat(triggered.get(), is(true));
}
 
Example #17
Source File: ActGraphTest.java    From act-platform with ISC License 5 votes vote down vote up
@Test
public void testIterateEdgesWithUuidIdSupportUsingDetachedEdge() {
  Edge edge1 = createEdge();
  Edge edge2 = getActGraph().edges(DetachedFactory.detach(edge1, true)).next();
  assertEquals(edge1.id(), edge2.id());
  assertFalse(edge2 instanceof DetachedEdge);
}
 
Example #18
Source File: GraphSONSerializersV3d0.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Edge deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final DetachedEdge.Builder e = DetachedEdge.build();
    final DetachedVertex.Builder inV = DetachedVertex.build();
    final DetachedVertex.Builder outV = DetachedVertex.build();
    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals(GraphSONTokens.ID)) {
            jsonParser.nextToken();
            e.setId(deserializationContext.readValue(jsonParser, Object.class));
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.LABEL)) {
            jsonParser.nextToken();
            e.setLabel(jsonParser.getText());
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.OUT)) {
            jsonParser.nextToken();
            outV.setId(deserializationContext.readValue(jsonParser, Object.class));
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.OUT_LABEL)) {
            jsonParser.nextToken();
            outV.setLabel(jsonParser.getText());
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.IN)) {
            jsonParser.nextToken();
            inV.setId(deserializationContext.readValue(jsonParser, Object.class));
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.IN_LABEL)) {
            jsonParser.nextToken();
            inV.setLabel(jsonParser.getText());
        } else if (jsonParser.getCurrentName().equals(GraphSONTokens.PROPERTIES)) {
            jsonParser.nextToken();
            while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
                jsonParser.nextToken();
                e.addProperty(deserializationContext.readValue(jsonParser, Property.class));
            }
        }
    }

    e.setInV(inV.create());
    e.setOutV(outV.create());

    return e.create();
}
 
Example #19
Source File: GryoClassResolverV3d0.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Class coerceType(final Class clazz) {
    // force all instances of Vertex, Edge, VertexProperty, etc. to their respective interface
    final Class type;
    if (!ReferenceVertex.class.isAssignableFrom(clazz) && !DetachedVertex.class.isAssignableFrom(clazz) && Vertex.class.isAssignableFrom(clazz))
        type = Vertex.class;
    else if (!ReferenceEdge.class.isAssignableFrom(clazz) && !DetachedEdge.class.isAssignableFrom(clazz) && Edge.class.isAssignableFrom(clazz))
        type = Edge.class;
    else if (!ReferenceVertexProperty.class.isAssignableFrom(clazz) && !DetachedVertexProperty.class.isAssignableFrom(clazz) && VertexProperty.class.isAssignableFrom(clazz))
        type = VertexProperty.class;
    else if (!ReferenceProperty.class.isAssignableFrom(clazz) && !DetachedProperty.class.isAssignableFrom(clazz) && !DetachedVertexProperty.class.isAssignableFrom(clazz) && !ReferenceVertexProperty.class.isAssignableFrom(clazz) && Property.class.isAssignableFrom(clazz))
        type = Property.class;
    else if (!ReferencePath.class.isAssignableFrom(clazz) && !DetachedPath.class.isAssignableFrom(clazz) && Path.class.isAssignableFrom(clazz))
        type = Path.class;
    else if (Lambda.class.isAssignableFrom(clazz))
        type = Lambda.class;
    else if (ByteBuffer.class.isAssignableFrom(clazz))
        type = ByteBuffer.class;
    else if (Class.class.isAssignableFrom(clazz))
        type = Class.class;
    else if (InetAddress.class.isAssignableFrom(clazz))
        type = InetAddress.class;
    else if (ConnectiveP.class.isAssignableFrom(clazz))
        type = P.class;
    else if (Metrics.class.isAssignableFrom(clazz))
        type = Metrics.class;
    else if (TraversalMetrics.class.isAssignableFrom(clazz))
        type = TraversalMetrics.class;
    else
        type = clazz;

    return type;
}
 
Example #20
Source File: GryoClassResolverV1d0.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Class coerceType(final Class clazz) {
    // force all instances of Vertex, Edge, VertexProperty, etc. to their respective interface
    final Class type;
    if (!ReferenceVertex.class.isAssignableFrom(clazz) && !DetachedVertex.class.isAssignableFrom(clazz) && Vertex.class.isAssignableFrom(clazz))
        type = Vertex.class;
    else if (!ReferenceEdge.class.isAssignableFrom(clazz) && !DetachedEdge.class.isAssignableFrom(clazz) && Edge.class.isAssignableFrom(clazz))
        type = Edge.class;
    else if (!ReferenceVertexProperty.class.isAssignableFrom(clazz) && !DetachedVertexProperty.class.isAssignableFrom(clazz) && VertexProperty.class.isAssignableFrom(clazz))
        type = VertexProperty.class;
    else if (!ReferenceProperty.class.isAssignableFrom(clazz) && !DetachedProperty.class.isAssignableFrom(clazz) && !DetachedVertexProperty.class.isAssignableFrom(clazz) && !ReferenceVertexProperty.class.isAssignableFrom(clazz) && Property.class.isAssignableFrom(clazz))
        type = Property.class;
    else if (!ReferencePath.class.isAssignableFrom(clazz) && !DetachedPath.class.isAssignableFrom(clazz) && Path.class.isAssignableFrom(clazz))
        type = Path.class;
    else if (Lambda.class.isAssignableFrom(clazz))
        type = Lambda.class;
    else if (ByteBuffer.class.isAssignableFrom(clazz))
        type = ByteBuffer.class;
    else if (Class.class.isAssignableFrom(clazz))
        type = Class.class;
    else if (InetAddress.class.isAssignableFrom(clazz))
        type = InetAddress.class;
    else if (ConnectiveP.class.isAssignableFrom(clazz))
        type = P.class;
    else
        type = clazz;

    return type;
}
 
Example #21
Source File: ParserTest.java    From gremlin-ogm with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsEdge() {
  assertEquals(develops, as(new DetachedEdge(
      null, Label.of(Develops.class), new HashMap<String, Object>() {
        {
          put("since", develops.since());
        }
      }, null, null, null, null), Develops.class));
}
 
Example #22
Source File: EdgeGraphTest.java    From gremlin-ogm with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  super.setUp();
  marko = mock(Vertex.class);
  vadas = mock(Vertex.class);
  when(marko.id()).thenReturn(1);
  when(vadas.id()).thenReturn(2);
  query = mock(Query.class);
  edgeGraph = new EdgeGraph(graph, query, g);
  when(traversal.next()).thenReturn(
      new DetachedEdge(null, Label.of(Develops.class), null,
          null, null, null, null));
}
 
Example #23
Source File: ActGraphTest.java    From act-platform with ISC License 5 votes vote down vote up
@Test
public void testIterateEdgesWithUuidIdSupportUsingDetachedEdge() {
  Edge edge1 = createEdge();
  Edge edge2 = getActGraph().edges(DetachedFactory.detach(edge1, true)).next();
  assertEquals(edge1.id(), edge2.id());
  assertFalse(edge2 instanceof DetachedEdge);
}
 
Example #24
Source File: ParameterizedGroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldHandleVertexAndEdge() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();

    final Object id1 = "customer:10:foo\u0020bar\u0020\u0024100#90"; // customer:10:foo bar $100#90
    final Vertex vertex1 = DetachedVertex.build().setLabel("customer").setId(id1)
            .create();
    final Script script1 = GroovyTranslator.of("g", true).translate(g.inject(vertex1).asAdmin().getBytecode());
    Bindings bindings = new SimpleBindings();
    script1.getParameters().ifPresent(bindings::putAll);
    assertEquals(2, bindings.size());
    assertEquals(id1, bindings.get("_args_0"));
    assertEquals("customer", bindings.get("_args_1"));
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(_args_0,_args_1, Collections.emptyMap()))", script1.getScript());
    final Script standard1 = GroovyTranslator.of("g").translate(g.inject(vertex1).asAdmin().getBytecode());
    bindings.put("g", g);
    // TinkerGraph not support string id
    assertParameterizedScriptOk(standard1.getScript(), script1.getScript(), bindings, false);
    bindings.clear();

    final Object id2 = "user:20:foo\\u0020bar\\u005c\\u0022mr\\u005c\\u0022\\u00241000#50"; // user:20:foo\u0020bar\u005c\u0022mr\u005c\u0022\u00241000#50
    final Vertex vertex2 = DetachedVertex.build().setLabel("user").setId(id2)
            .create();
    final Script script2 = GroovyTranslator.of("g", true).translate(g.inject(vertex2).asAdmin().getBytecode());
    script2.getParameters().ifPresent(bindings::putAll);
    assertEquals(2, bindings.size());
    assertEquals(id2, bindings.get("_args_0"));
    assertEquals("user", bindings.get("_args_1"));
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(_args_0,_args_1, Collections.emptyMap()))", script2.getScript());
    final Script standard2 = GroovyTranslator.of("g").translate(g.inject(vertex2).asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard2.getScript(), script2.getScript(), bindings, false);
    bindings.clear();

    final Object id3 = "knows:30:foo\u0020bar\u0020\u0024100:\\u0020\\u0024500#70";
    final Edge edge = DetachedEdge.build().setLabel("knows").setId(id3)
            .setOutV((DetachedVertex) vertex1)
            .setInV((DetachedVertex) vertex2)
            .create();
    final Script script3 = GroovyTranslator.of("g", true).translate(g.inject(edge).asAdmin().getBytecode());
    script3.getParameters().ifPresent(bindings::putAll);
    assertEquals(6, bindings.size());
    assertEquals(id3, bindings.get("_args_0"));
    assertEquals("knows", bindings.get("_args_1"));
    assertEquals(id1, bindings.get("_args_2"));
    assertEquals("customer", bindings.get("_args_3"));
    assertEquals(id2, bindings.get("_args_4"));
    assertEquals("user", bindings.get("_args_5"));
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge(_args_0,_args_1,Collections.emptyMap(),_args_2,_args_3,_args_4,_args_5))", script3.getScript());
    final Script standard3 = GroovyTranslator.of("g").translate(g.inject(edge).asAdmin().getBytecode());
    bindings.put("g", g);
    assertParameterizedScriptOk(standard3.getScript(), script3.getScript(), bindings, false);
    bindings.clear();

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

    final Script script5 = GroovyTranslator.of("g", true).translate(g.V().has("age").asAdmin().getBytecode());
    script5.getParameters().ifPresent(bindings::putAll);
    assertEquals(1, bindings.size());
    assertEquals("age", bindings.get("_args_0"));
    assertEquals("g.V().has(_args_0)", script5.getScript());
    final Script standard5 = GroovyTranslator.of("g").translate(g.V().has("age").asAdmin().getBytecode());
    bindings.put("g", g);
    // Ok, here we checking all the result
    assertParameterizedScriptOk(standard5.getScript(), script5.getScript(), bindings, true);
    bindings.clear();
}
 
Example #25
Source File: GroovyTranslatorTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldHandleVertexAndEdge() {
    final TinkerGraph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();

    final Object id1 = "customer:10:foo\u0020bar\u0020\u0024100#90"; // customer:10:foo bar $100#90
    final Vertex vertex1 = DetachedVertex.build().setLabel("customer").setId(id1)
            .create();
    final String script1 = GroovyTranslator.of("g").translate(g.inject(vertex1).asAdmin().getBytecode()).getScript();
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(" +
                    "\"customer:10:foo bar \\$100#90\"," +
                    "\"customer\", Collections.emptyMap()))",
            script1);
    assertThatScriptOk(script1, "g", g);

    final Object id2 = "user:20:foo\\u0020bar\\u005c\\u0022mr\\u005c\\u0022\\u00241000#50"; // user:20:foo\u0020bar\u005c\u0022mr\u005c\u0022\u00241000#50
    final Vertex vertex2 = DetachedVertex.build().setLabel("user").setId(id2)
            .create();
    final String script2 = GroovyTranslator.of("g").translate(g.inject(vertex2).asAdmin().getBytecode()).getScript();
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(" +
                    "\"user:20:foo\\\\u0020bar\\\\u005c\\\\u0022mr\\\\u005c\\\\u0022\\\\u00241000#50\"," +
                    "\"user\", Collections.emptyMap()))",
            script2);
    assertThatScriptOk(script2, "g", g);

    final Object id3 = "knows:30:foo\u0020bar\u0020\u0024100:\\u0020\\u0024500#70";
    final Edge edge = DetachedEdge.build().setLabel("knows").setId(id3)
            .setOutV((DetachedVertex) vertex1)
            .setInV((DetachedVertex) vertex2)
            .create();
    final String script3 = GroovyTranslator.of("g").translate(g.inject(edge).asAdmin().getBytecode()).getScript();
    assertEquals("g.inject(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge(" +
                    "\"knows:30:foo bar \\$100:\\\\u0020\\\\u0024500#70\"," +
                    "\"knows\",Collections.emptyMap()," +
                    "\"customer:10:foo bar \\$100#90\",\"customer\"," +
                    "\"user:20:foo\\\\u0020bar\\\\u005c\\\\u0022mr\\\\u005c\\\\u0022\\\\u00241000#50\",\"user\"))",
            script3);
    assertThatScriptOk(script3, "g", g);

    final String script4 = GroovyTranslator.of("g").translate(
            g.addE("knows").from(vertex1).to(vertex2).property("when", "2018/09/21")
                    .asAdmin().getBytecode()).getScript();
    assertEquals("g.addE(\"knows\")" +
                    ".from(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(\"customer:10:foo bar \\$100#90\",\"customer\", Collections.emptyMap()))" +
                    ".to(new org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex(\"user:20:foo\\\\u0020bar\\\\u005c\\\\u0022mr\\\\u005c\\\\u0022\\\\u00241000#50\",\"user\", Collections.emptyMap()))" +
                    ".property(\"when\",\"2018/09/21\")",
            script4);
}
 
Example #26
Source File: GryoReader.java    From tinkerpop with Apache License 2.0 3 votes vote down vote up
/**
 * Read an {@link Edge} from output generated by {@link GryoWriter#writeEdge(OutputStream, Edge)} or via
 * an {@link Edge} passed to {@link GryoWriter#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 {
    final Input input = new Input(inputStream);
    readHeader(input);
    final Attachable<Edge> attachable = kryo.readObject(input, DetachedEdge.class);
    return edgeAttachMethod.apply(attachable);
}