org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils. 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: SystemUtilTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLoadSystemProperties() {
    System.setProperty("blah.aa", "1");
    System.setProperty("blah.b", "true");
    System.setProperty("blah.c", "three");
    System.setProperty("bleep.d", "false");
    Configuration configuration = SystemUtil.getSystemPropertiesConfiguration("blah", false);
    assertEquals(3, IteratorUtils.count(configuration.getKeys()));
    assertEquals(1, configuration.getInt("blah.aa"));
    assertTrue(configuration.getBoolean("blah.b"));
    assertEquals("three", configuration.getProperty("blah.c"));
    assertFalse(configuration.containsKey("d") || configuration.containsKey("bleep.d"));
    System.clearProperty("blah.aa");
    System.clearProperty("blah.b");
    System.clearProperty("blah.c");
    System.clearProperty("bleep.d");
}
 
Example #2
Source File: DistributionGeneratorTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
@FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_INTEGER_VALUES)
public void shouldProcessEdges() {
    final Distribution dist = new NormalDistribution(2);
    final DistributionGenerator generator = DistributionGenerator.build(graph)
            .label("knows")
            .edgeProcessor(e -> e.<String>property("data", "test"))
            .outDistribution(dist)
            .inDistribution(dist)
            .expectedNumEdges(100).create();
    final int edgesGenerated = generator.generate();
    assertTrue(edgesGenerated > 0);
    tryCommit(graph, g -> {
        assertEquals(new Long(edgesGenerated), new Long(IteratorUtils.count(g.edges())));
        assertTrue(g.traversal().V().count().next() > 0);
        assertTrue(IteratorUtils.stream(g.edges()).allMatch(e -> e.value("data").equals("test")));
    });
}
 
Example #3
Source File: HugeTraverser.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
public double jaccardSimilarity(Id vertex, Id other, Directions dir,
                                String label, long degree) {
    E.checkNotNull(vertex, "vertex id");
    E.checkNotNull(other, "the other vertex id");
    E.checkNotNull(dir, "direction");
    checkDegree(degree);

    Id labelId = this.getEdgeLabelId(label);

    Set<Id> sourceNeighbors = IteratorUtils.set(this.adjacentVertices(
                              vertex, dir, labelId, degree));
    Set<Id> targetNeighbors = IteratorUtils.set(this.adjacentVertices(
                              other, dir, labelId, degree));
    int interNum = CollectionUtil.intersect(sourceNeighbors,
                                            targetNeighbors).size();
    int unionNum = CollectionUtil.union(sourceNeighbors,
                                        targetNeighbors).size();
    return (double) interNum / unionNum;
}
 
Example #4
Source File: AddEdgeTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
public void g_V_asXaX_outXcreatedX_inXcreatedX_whereXneqXaXX_asXbX_addEXcodeveloperX_fromXaX_toXbX_propertyXyear_2009X() {
    final Traversal<Vertex, Edge> traversal = get_g_V_asXaX_outXcreatedX_inXcreatedX_whereXneqXaXX_asXbX_addEXcodeveloperX_fromXaX_toXbX_propertyXyear_2009X();
    printTraversalForm(traversal);
    int count = 0;
    while (traversal.hasNext()) {
        final Edge edge = traversal.next();
        assertEquals("codeveloper", edge.label());
        assertEquals(2009, g.E(edge).values("year").next());
        assertEquals(1, g.E(edge).properties().count().next().intValue());
        assertEquals("person", g.E(edge).inV().label().next());
        assertEquals("person", g.E(edge).outV().label().next());
        assertFalse(g.E(edge).inV().values("name").next().equals("vadas"));
        assertFalse(g.E(edge).outV().values("name").next().equals("vadas"));
        assertFalse(g.E(edge).inV().next().equals(g.E(edge).outV().next()));
        count++;

    }
    assertEquals(6, count);
    assertEquals(12, IteratorUtils.count(g.E()));
    assertEquals(6, IteratorUtils.count(g.V()));
}
 
Example #5
Source File: MaxComputationWithGraphOutputTest.java    From hgraphdb with Apache License 2.0 6 votes vote down vote up
@Test
public void testMax() throws Exception {
    HBaseGraphConfiguration hconf = graph.configuration();

    GiraphConfiguration conf = new GiraphConfiguration(hconf.toHBaseConfiguration());
    conf.setComputationClass(MaxComputation.class);
    conf.setEdgeInputFormatClass(HBaseEdgeInputFormat.class);
    conf.setVertexInputFormatClass(HBaseVertexInputFormat.class);
    conf.setEdgeOutputFormatClass(CreateEdgeOutputFormat.class);
    conf.setVertexOutputFormatClass(MaxPropertyVertexOutputFormat.class);

    Vertex v1 = graph.addVertex(T.id, 1, T.label, "hi");
    Vertex v2 = graph.addVertex(T.id, 2, T.label, "world");
    Vertex v5 = graph.addVertex(T.id, 5, T.label, "bye");
    v5.addEdge("e", v1);
    v1.addEdge("e", v5);
    v1.addEdge("e", v2);
    v2.addEdge("e", v5);

    InternalHBaseVertexRunner.run(conf);

    graph.vertices().forEachRemaining(v -> assertEquals(5, v.property("max").value()));
    assertEquals(4, IteratorUtils.count(IteratorUtils.filter(graph.edges(), e -> e.label().equals("e2"))));
}
 
Example #6
Source File: VertexProgramStrategy.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static VertexProgramStrategy create(final Configuration configuration) {
    try {
        final VertexProgramStrategy.Builder builder = VertexProgramStrategy.build();
        for (final String key : (List<String>) IteratorUtils.asList(configuration.getKeys())) {
            if (key.equals(GRAPH_COMPUTER))
                builder.graphComputer((Class) Class.forName(configuration.getString(key)));
            else if (key.equals(WORKERS))
                builder.workers(configuration.getInt(key));
            else if (key.equals(PERSIST))
                builder.persist(GraphComputer.Persist.valueOf(configuration.getString(key)));
            else if (key.equals(RESULT))
                builder.result(GraphComputer.ResultGraph.valueOf(configuration.getString(key)));
            else if (key.equals(VERTICES))
                builder.vertices((Traversal) configuration.getProperty(key));
            else if (key.equals(EDGES))
                builder.edges((Traversal) configuration.getProperty(key));
            else
                builder.configure(key, configuration.getProperty(key));
        }
        return builder.create();
    } catch (final ClassNotFoundException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}
 
Example #7
Source File: RepeatStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected Iterator<Traverser.Admin<S>> computerAlgorithm() throws NoSuchElementException {
    final RepeatStep<S> repeatStep = (RepeatStep<S>) this.getTraversal().getParent();
    final Traverser.Admin<S> start = this.starts.next();
    start.incrLoops();
    if (repeatStep.doUntil(start, false)) {
        start.resetLoops();
        start.setStepId(repeatStep.getNextStep().getId());
        start.addLabels(repeatStep.labels);
        return IteratorUtils.of(start);
    } else {
        start.setStepId(repeatStep.getId());
        if (repeatStep.doEmit(start, false)) {
            final Traverser.Admin<S> emitSplit = start.split();
            emitSplit.resetLoops();
            emitSplit.setStepId(repeatStep.getNextStep().getId());
            emitSplit.addLabels(repeatStep.labels);
            return IteratorUtils.of(start, emitSplit);
        }
        return IteratorUtils.of(start);
    }
}
 
Example #8
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if the traversal has any of the supplied steps of an assignable class in the current {@link Traversal}
 * and its {@link Scope} child traversals.
 *
 * @param scope       whether to check global or local children (null for both).
 * @param stepClasses the step classes to look for
 * @param traversal   the traversal in which to look for the given step classes
 * @return <code>true</code> if any step in the given traversal (and its child traversals) is an instance of a class
 * provided in <code>stepClasses</code>, otherwise <code>false</code>.
 */
public static boolean hasStepOfAssignableClassRecursively(final Scope scope, final Collection<Class> stepClasses, final Traversal.Admin<?, ?> traversal) {
    if (stepClasses.size() == 1)
        return hasStepOfAssignableClassRecursively(stepClasses.iterator().next(), traversal);
    for (final Step<?, ?> step : traversal.getSteps()) {
        if (IteratorUtils.anyMatch(stepClasses.iterator(), stepClass -> stepClass.isAssignableFrom(step.getClass()))) {
            return true;
        }
        if (step instanceof TraversalParent) {
            if (null == scope || Scope.local.equals(scope)) {
                for (final Traversal.Admin<?, ?> localChild : ((TraversalParent) step).getLocalChildren()) {
                    if (hasStepOfAssignableClassRecursively(stepClasses, localChild)) return true;
                }
            }
            if (null == scope || Scope.global.equals(scope)) {
                for (final Traversal.Admin<?, ?> globalChild : ((TraversalParent) step).getGlobalChildren()) {
                    if (hasStepOfAssignableClassRecursively(stepClasses, globalChild)) return true;
                }
            }
        }
    }
    return false;
}
 
Example #9
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_REMOVE_PROPERTY)
public void shouldTriggerRemoveEdgeProperty() {
    final StubMutationListener listener1 = new StubMutationListener();
    final StubMutationListener listener2 = new StubMutationListener();
    final EventStrategy.Builder builder = EventStrategy.build()
            .addListener(listener1)
            .addListener(listener2);

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

    final EventStrategy eventStrategy = builder.create();

    final Vertex v = graph.addVertex();
    v.addEdge("self", v, "some", "thing");
    final GraphTraversalSource gts = create(eventStrategy);
    gts.E().properties().drop().iterate();

    tryCommit(graph, g -> assertEquals(0, IteratorUtils.count(gts.E().properties())));

    assertEquals(1, listener1.edgePropertyRemovedEventRecorded());
    assertEquals(1, listener2.edgePropertyRemovedEventRecorded());
}
 
Example #10
Source File: StarGraph.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<Edge> edges(final Direction direction, final String... edgeLabels) {
    if (direction.equals(Direction.OUT)) {
        return null == this.outEdges ? Collections.emptyIterator() : edgeLabels.length == 0 ?
                IteratorUtils.flatMap(this.outEdges.values().iterator(), List::iterator) :
                this.outEdges.entrySet().stream()
                        .filter(entry -> ElementHelper.keyExists(entry.getKey(), edgeLabels))
                        .map(Map.Entry::getValue)
                        .flatMap(List::stream)
                        .iterator();
    } else if (direction.equals(Direction.IN)) {
        return null == this.inEdges ? Collections.emptyIterator() : edgeLabels.length == 0 ?
                IteratorUtils.flatMap(this.inEdges.values().iterator(), List::iterator) :
                this.inEdges.entrySet().stream()
                        .filter(entry -> ElementHelper.keyExists(entry.getKey(), edgeLabels))
                        .map(Map.Entry::getValue)
                        .flatMap(List::stream)
                        .iterator();
    } else
        return IteratorUtils.concat(this.edges(Direction.IN, edgeLabels), this.edges(Direction.OUT, edgeLabels));
}
 
Example #11
Source File: DocumentGraphFactoryTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testDocumentGraphWithRelationsAsLinks() throws UIMAException {

  DocumentGraphOptions options =
      DocumentGraphOptions.builder().withRelationsAsLinks(true).build();
  DocumentGraphFactory factory = createfactory(options);

  JCas jCas = JCasFactory.createJCas();
  JCasTestGraphUtil.populateJcas(jCas);

  Graph graph = factory.create(jCas);

  assertEquals(3, graph.traversal().V().hasLabel(REFERENCE_TARGET).count().next().intValue());
  assertEquals(1, graph.traversal().V().hasLabel(EVENT).count().next().intValue());
  assertEquals(4, graph.traversal().V().hasLabel(MENTION).count().next().intValue());
  assertEquals(4, graph.traversal().E().hasLabel(MENTION_OF).count().next().intValue());
  assertEquals(2, graph.traversal().E().hasLabel(RELATION).count().next().intValue());
  assertEquals(2, graph.traversal().E().hasLabel(PARTICIPANT_IN).count().next().intValue());

  assertNoDocumentNode(graph);
  assertRelationsNotRerified(graph);

  assertEquals(8, IteratorUtils.count(graph.vertices()));
  assertEquals(8, IteratorUtils.count(graph.edges()));
}
 
Example #12
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 #13
Source File: FusiformSimilarityTraverser.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
private boolean matchMinNeighborCount(HugeVertex vertex,
                                      Directions direction,
                                      EdgeLabel edgeLabel,
                                      int minNeighbors,
                                      long degree) {
    Iterator<Edge> edges;
    long neighborCount;
    Id labelId = edgeLabel == null ? null : edgeLabel.id();
    if (edgeLabel != null && edgeLabel.frequency() == Frequency.SINGLE) {
        edges = this.edgesOfVertex(vertex.id(), direction,
                                   labelId, minNeighbors);
        neighborCount = IteratorUtils.count(edges);
    } else {
        edges = this.edgesOfVertex(vertex.id(), direction, labelId, degree);
        Set<Id> neighbors = new HashSet<>();
        while (edges.hasNext()) {
            Id target = ((HugeEdge) edges.next()).id().otherVertexId();
            neighbors.add(target);
            if (neighbors.size() >= minNeighbors) {
                break;
            }
        }
        neighborCount = neighbors.size();
    }
    return neighborCount >= minNeighbors;
}
 
Example #14
Source File: AddVertexTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@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)
public void g_V_hasXname_markoX_propertyXfriendWeight_outEXknowsX_weight_sum__acl_privateX() {
    final Traversal<Vertex, Vertex> traversal = get_g_V_hasXname_markoX_propertyXfriendWeight_outEXknowsX_weight_sum__acl_privateX();
    printTraversalForm(traversal);
    final Vertex marko = traversal.next();
    assertFalse(traversal.hasNext());
    assertEquals("person", marko.label());
    assertEquals("marko", marko.value("name"));
    assertEquals(1.5, marko.value("friendWeight"), 0.01);
    assertEquals("private", marko.property("friendWeight").value("acl"));
    assertEquals(3, IteratorUtils.count(marko.properties()));
    assertEquals(1, IteratorUtils.count(marko.property("friendWeight").properties()));
}
 
Example #15
Source File: GryoLiteMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

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

    final Map<Vertex, Integer> deserializedMap = (Map<Vertex, Integer>) response.getResult().getData();
    assertEquals(1, deserializedMap.size());

    final Vertex deserializedMarko = deserializedMap.keySet().iterator().next();
    assertEquals(0, IteratorUtils.count(deserializedMarko.properties()));
    assertEquals(1, deserializedMarko.id());
    assertEquals(Vertex.DEFAULT_LABEL, deserializedMarko.label());

    assertEquals(new Integer(1000), deserializedMap.values().iterator().next());
}
 
Example #16
Source File: DetachedVertexPropertyTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void shouldDetachMultiPropertiesAndMetaProperties() {
    final Vertex v1 = convertToVertex(graph, "marko");
    v1.properties("location").forEachRemaining(vp -> {
        final DetachedVertexProperty detached = DetachedFactory.detach(vp, true);
        if (detached.value().equals("san diego")) {
            assertEquals(1997, (int) detached.value("startTime"));
            assertEquals(2001, (int) detached.value("endTime"));
            assertEquals(2, (int) IteratorUtils.count(detached.properties()));
        } else if (vp.value().equals("santa cruz")) {
            assertEquals(2001, (int) detached.value("startTime"));
            assertEquals(2004, (int) detached.value("endTime"));
            assertEquals(2, (int) IteratorUtils.count(detached.properties()));
        } else if (detached.value().equals("brussels")) {
            assertEquals(2004, (int) vp.value("startTime"));
            assertEquals(2005, (int) vp.value("endTime"));
            assertEquals(2, (int) IteratorUtils.count(detached.properties()));
        } else if (detached.value().equals("santa fe")) {
            assertEquals(2005, (int) detached.value("startTime"));
            assertEquals(1, (int) IteratorUtils.count(detached.properties()));
        } else {
            fail("Found a value that should be there");
        }
    });
}
 
Example #17
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldTriggerAddVertexWithPropertyThenPropertyAdded() {
    final StubMutationListener listener1 = new StubMutationListener();
    final StubMutationListener listener2 = new StubMutationListener();
    final EventStrategy.Builder builder = EventStrategy.build()
            .addListener(listener1)
            .addListener(listener2);

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

    final EventStrategy eventStrategy = builder.create();

    final Vertex vSome = graph.addVertex("some", "thing");
    vSome.property(VertexProperty.Cardinality.single, "that", "thing");
    final GraphTraversalSource gts = create(eventStrategy);
    gts.V().addV().property("any", "thing").property(VertexProperty.Cardinality.single, "this", "thing").next();

    tryCommit(graph, g -> assertEquals(1, IteratorUtils.count(gts.V().has("this", "thing"))));

    assertEquals(1, listener1.addVertexEventRecorded());
    assertEquals(1, listener2.addVertexEventRecorded());
    assertEquals(1, listener2.vertexPropertyChangedEventRecorded());
    assertEquals(1, listener1.vertexPropertyChangedEventRecorded());
}
 
Example #18
Source File: CustomTest.java    From hgraphdb with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void shouldNotHaveAConcurrentModificationExceptionWhenIteratingAndRemovingAddingEdges() {
    final Vertex v1 = graph.addVertex("name", "marko");
    final Vertex v2 = graph.addVertex("name", "puppy");
    v1.addEdge("knows", v2, "since", 2010);
    v1.addEdge("pets", v2);
    v1.addEdge("walks", v2, "location", "arroyo");
    v2.addEdge("knows", v1, "since", 2010);
    assertEquals(4L, IteratorUtils.count(v1.edges(Direction.BOTH)));
    assertEquals(4L, IteratorUtils.count(v2.edges(Direction.BOTH)));
    v1.edges(Direction.BOTH).forEachRemaining(edge -> {
        v1.addEdge("livesWith", v2);
        v1.addEdge("walks", v2, "location", "river");
        edge.remove();
    });
    v1.edges(Direction.BOTH).forEachRemaining(Edge::remove);
    assertEquals(0, IteratorUtils.count(v1.edges(Direction.BOTH)));
    assertEquals(0, IteratorUtils.count(v2.edges(Direction.BOTH)));
}
 
Example #19
Source File: GraphSerializer.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected void writeValue(final Graph value, final Buffer buffer, final GraphBinaryWriter context) throws IOException {
    // this kinda looks scary memory-wise, but GraphBinary is about network derser so we are dealing with a
    // graph instance that should live in memory already - not expecting "big" stuff here.
    final List<Vertex> vertexList = IteratorUtils.list(value.vertices());
    final List<Edge> edgeList = IteratorUtils.list(value.edges());

    context.writeValue(vertexList.size(), buffer, false);

    for (Vertex v : vertexList) {
        writeVertex(buffer, context, v);
    }

    context.writeValue(edgeList.size(), buffer, false);

    for (Edge e : edgeList) {
        writeEdge(buffer, context, e);
    }
}
 
Example #20
Source File: RepeatStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected Iterator<Traverser.Admin<S>> standardAlgorithm() throws NoSuchElementException {
    final RepeatStep<S> repeatStep = (RepeatStep<S>) this.getTraversal().getParent();
    while (true) {
        final Traverser.Admin<S> start = this.starts.next();
        start.incrLoops();
        if (repeatStep.doUntil(start, false)) {
            start.resetLoops();
            return IteratorUtils.of(start);
        } else {
            if (!repeatStep.untilFirst && !repeatStep.emitFirst)
                repeatStep.repeatTraversal.addStart(start);
            else
                repeatStep.addStart(start);
            if (repeatStep.doEmit(start, false)) {
                final Traverser.Admin<S> emitSplit = start.split();
                emitSplit.resetLoops();
                return IteratorUtils.of(emitSplit);
            }
        }
    }
}
 
Example #21
Source File: StarGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void shouldHashAndEqualsCorrectly() {
    final Vertex gremlin = g.V(convertToVertexId("gremlin")).next();
    final StarGraph gremlinStarGraph = StarGraph.of(gremlin);
    final StarGraph.StarVertex gremlinStar = gremlinStarGraph.getStarVertex();

    final Vertex marko = g.V(convertToVertexId("marko")).next();
    final StarGraph markoStarGraph = StarGraph.of(marko);
    final StarGraph.StarAdjacentVertex gremlinStarAdjacentGraph = (StarGraph.StarAdjacentVertex) IteratorUtils.filter(markoStarGraph.getStarVertex().edges(Direction.OUT, "uses"), x -> x.inVertex().id().equals(convertToVertexId("gremlin"))).next().inVertex();

    final Set<Vertex> set = new HashSet<>();
    for (int i = 0; i < 100; i++) {
        set.add(gremlin);
        set.add(gremlinStar);
        set.add(gremlinStarAdjacentGraph);
    }
    assertEquals(1, set.size());
}
 
Example #22
Source File: GraphConstructionTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * A {@link Graph} should maintain the original {@code Configuration} object passed to it via {@link GraphFactory}.
 */
@Test
public void shouldMaintainOriginalConfigurationObjectGivenToFactory() throws Exception {
    final Configuration originalConfig = graphProvider.newGraphConfiguration("temp2", this.getClass(), name.getMethodName(), null);
    final Graph createdGraph = GraphFactory.open(originalConfig);

    final Configuration configInGraph = createdGraph.configuration();
    final AtomicInteger keyCount = new AtomicInteger(0);
    originalConfig.getKeys().forEachRemaining(k -> {
        assertTrue(configInGraph.containsKey(k));
        keyCount.incrementAndGet();
    });

    // need some keys in the originalConfig for this test to be meaningful
    assertTrue(keyCount.get() > 0);
    assertEquals(keyCount.get(), IteratorUtils.count(configInGraph.getKeys()));

    graphProvider.clear(createdGraph, originalConfig);
}
 
Example #23
Source File: GraphSONSerializersV2d0.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private void writeProperties(final Edge edge, final JsonGenerator jsonGenerator) throws IOException {
    final Iterator<Property<Object>> elementProperties = normalize ?
            IteratorUtils.list(edge.properties(), Comparators.PROPERTY_COMPARATOR).iterator() : edge.properties();
    if (elementProperties.hasNext()) {
        jsonGenerator.writeFieldName(GraphSONTokens.PROPERTIES);

        jsonGenerator.writeStartObject();
        elementProperties.forEachRemaining(prop -> safeWriteObjectField(jsonGenerator, prop.key(), prop));
        jsonGenerator.writeEndObject();
    }
}
 
Example #24
Source File: GraphSONMessageSerializerGremlinV1d0Test.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<Map<String, Object>> edgeList = (List<Map<String, Object>>) response.getResult().getData();
    assertEquals(1, edgeList.size());

    final Map<String, Object> deserializedEdge = edgeList.get(0);
    assertEquals(e.id(), deserializedEdge.get(GraphSONTokens.ID));
    assertEquals(v1.id(), deserializedEdge.get(GraphSONTokens.OUT));
    assertEquals(v2.id(), deserializedEdge.get(GraphSONTokens.IN));
    assertEquals(v1.label(), deserializedEdge.get(GraphSONTokens.OUT_LABEL));
    assertEquals(v2.label(), deserializedEdge.get(GraphSONTokens.IN_LABEL));
    assertEquals(e.label(), deserializedEdge.get(GraphSONTokens.LABEL));
    assertEquals(GraphSONTokens.EDGE, deserializedEdge.get(GraphSONTokens.TYPE));

    final Map<String, Object> properties = (Map<String, Object>) deserializedEdge.get(GraphSONTokens.PROPERTIES);
    assertNotNull(properties);
    assertEquals(123, properties.get("abc"));

}
 
Example #25
Source File: TinkerVertex.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<Vertex> vertices(final Direction direction, final String... edgeLabels) {
    return TinkerHelper.inComputerMode(this.graph) ?
            direction.equals(Direction.BOTH) ?
                    IteratorUtils.concat(
                            IteratorUtils.map(this.edges(Direction.OUT, edgeLabels), Edge::inVertex),
                            IteratorUtils.map(this.edges(Direction.IN, edgeLabels), Edge::outVertex)) :
                    IteratorUtils.map(this.edges(direction, edgeLabels), edge -> edge.vertices(direction.opposite()).next()) :
            (Iterator) TinkerHelper.getVertices(this, direction, edgeLabels);
}
 
Example #26
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldTriggerEdgePropertyChanged() {
    final StubMutationListener listener1 = new StubMutationListener();
    final StubMutationListener listener2 = new StubMutationListener();
    final EventStrategy.Builder builder = EventStrategy.build()
            .addListener(listener1)
            .addListener(listener2);

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

    final EventStrategy eventStrategy = builder.create();

    final Vertex v = graph.addVertex();
    final Edge e = v.addEdge("self", v);
    e.property("some", "thing");

    final GraphTraversalSource gts = create(eventStrategy);
    gts.E(e).property("some", "other thing").next();

    tryCommit(graph, g -> assertEquals(1, IteratorUtils.count(gts.E().has("some", "other thing"))));

    assertEquals(0, listener1.addVertexEventRecorded());
    assertEquals(0, listener2.addVertexEventRecorded());

    assertEquals(0, listener1.addEdgeEventRecorded());
    assertEquals(0, listener2.addEdgeEventRecorded());

    assertEquals(1, listener2.edgePropertyChangedEventRecorded());
    assertEquals(1, listener1.edgePropertyChangedEventRecorded());
}
 
Example #27
Source File: TinkerGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeWithColorClassResolverToTinkerGraph() throws Exception {
    final Map<String,Color> colors = new HashMap<>();
    colors.put("red", Color.RED);
    colors.put("green", Color.GREEN);

    final ArrayList<Color> colorList = new ArrayList<>(Arrays.asList(Color.RED, Color.GREEN));

    final Supplier<ClassResolver> classResolver = new CustomClassResolverSupplier();
    final GryoMapper mapper = GryoMapper.build().version(GryoVersion.V3_0).addRegistry(TinkerIoRegistryV3d0.instance()).classResolver(classResolver).create();
    final Kryo kryo = mapper.createMapper();
    try (final ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        final Output out = new Output(stream);

        kryo.writeObject(out, colorList);
        out.flush();
        final byte[] b = stream.toByteArray();

        try (final InputStream inputStream = new ByteArrayInputStream(b)) {
            final Input input = new Input(inputStream);
            final List m = kryo.readObject(input, ArrayList.class);
            final TinkerGraph readX = (TinkerGraph) m.get(0);
            assertEquals(104, IteratorUtils.count(readX.vertices()));
            assertEquals(102, IteratorUtils.count(readX.edges()));
        }
    }
}
 
Example #28
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 #29
Source File: GraphTest.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_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_NUMERIC_IDS)
public void shouldIterateEdgesWithNumericIdSupportUsingStringRepresentations() {
    // if the graph supports id assigned, it should allow it.  if the graph does not, it will generate one
    final Vertex v = graph.addVertex();
    final Edge e1 = graph.features().edge().supportsUserSuppliedIds() ? v.addEdge("self", v, T.id, 1l) : v.addEdge("self", v);
    final Edge e2 = graph.features().edge().supportsUserSuppliedIds() ? v.addEdge("self", v, T.id, 2l) : v.addEdge("self", v);
    v.addEdge("self", v);
    tryCommit(graph, graph -> {
        assertEquals(2, IteratorUtils.count(graph.edges(e1.id().toString(), e2.id().toString())));
    });
}
 
Example #30
Source File: Song.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
protected <V> Iterator<VertexProperty<V>> specificProperties(String key) {
    final VertexProperty<V> ret;
    if (NAME.equals(key) && name != null) {
        return IteratorUtils.of(new SpecializedVertexProperty(this, key, name));
    } else if (key == SONG_TYPE && songType != null) {
        return IteratorUtils.of(new SpecializedVertexProperty(this, key, songType));
    } else if (key == PERFORMANCES && performances != null) {
        return IteratorUtils.of(new SpecializedVertexProperty(this, key, performances));
    } else if (key == TEST_PROP && testProp != null) {
        return IteratorUtils.of(new SpecializedVertexProperty(this, key, testProp));
    } else {
        return Collections.emptyIterator();
    }
}