Java Code Examples for org.apache.tinkerpop.gremlin.structure.Direction

The following are top voted examples for showing how to use org.apache.tinkerpop.gremlin.structure.Direction. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: act-platform   File: FactEdgeTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testReturnOutThenInOnVertexIterator() {
  UUID factID = mockFact(null);
  UUID inVertexObjectID = mockObject();
  UUID outVertexObjectID = mockObject();
  Edge edge = new FactEdge(getActGraph(), factID, inVertexObjectID, outVertexObjectID);

  assertEquals(outVertexObjectID, edge.outVertex().id());
  assertEquals(inVertexObjectID, edge.inVertex().id());

  Iterator<Vertex> vertices = edge.vertices(Direction.BOTH);
  assertTrue(vertices.hasNext());
  assertEquals(outVertexObjectID, vertices.next().id());
  assertTrue(vertices.hasNext());
  assertEquals(inVertexObjectID, vertices.next().id());
  assertFalse(vertices.hasNext());
}
 
Example 2
Project: gremlin-ogm   File: EdgeGraph.java   Source Code and License 6 votes vote down vote up
/**
 * Add the given edge, from the given gremlin vertex, to the vertices selected by the given {@link
 * AnyTraversal}.
 */
public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from,
    AnyTraversal anyTraversal) {
  if (from == null) {
    throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from);
  }
  List<Vertex> tos = query.by(anyTraversal).list(Vertex.class);
  if (tos == null || tos.isEmpty()) {
    throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, anyTraversal);
  }
  tos.forEach(to -> {
    edge.to(to);
    addEdge(edge, from, to.delegate());
  });
  return edge;
}
 
Example 3
Project: gremlin-ogm   File: EdgeGraph.java   Source Code and License 6 votes vote down vote up
/**
 * Add the given edge, from the given gremlin vertex, to the vertices selected by the given {@link
 * SubTraversal}s.
 */
public <E extends Edge> Edge addEdge(E edge, org.apache.tinkerpop.gremlin.structure.Vertex from,
    SubTraversal... subTraversals) {
  if (from == null) {
    throw Edge.Exceptions.missingEdgeVertex(Direction.OUT, edge, from);
  }
  List<Vertex> tos = query.by(subTraversals).list(Vertex.class);
  if (tos == null || tos.isEmpty()) {
    throw Edge.Exceptions.missingEdgeVertex(Direction.IN, edge, subTraversals);
  }
  tos.forEach(to -> {
    edge.to(to);
    addEdge(edge, from, to.delegate());
  });
  return edge;
}
 
Example 4
Project: tinkergraph-gremlin   File: TinkerHelper.java   Source Code and License 6 votes vote down vote up
public static Iterator<TinkerEdge> getEdges(final TinkerVertex vertex, final Direction direction, final String... edgeLabels) {
    final List<Edge> edges = new ArrayList<>();
    if (direction.equals(Direction.OUT) || direction.equals(Direction.BOTH)) {
        if (vertex.outEdges != null) {
            if (edgeLabels.length == 0)
                vertex.outEdges.values().forEach(edges::addAll);
            else if (edgeLabels.length == 1)
                edges.addAll(vertex.outEdges.getOrDefault(edgeLabels[0], Collections.emptySet()));
            else
                Stream.of(edgeLabels).map(vertex.outEdges::get).filter(Objects::nonNull).forEach(edges::addAll);
        }
    }
    if (direction.equals(Direction.IN) || direction.equals(Direction.BOTH)) {
        if (vertex.inEdges != null) {
            if (edgeLabels.length == 0)
                vertex.inEdges.values().forEach(edges::addAll);
            else if (edgeLabels.length == 1)
                edges.addAll(vertex.inEdges.getOrDefault(edgeLabels[0], Collections.emptySet()));
            else
                Stream.of(edgeLabels).map(vertex.inEdges::get).filter(Objects::nonNull).forEach(edges::addAll);
        }
    }
    return (Iterator) edges.iterator();
}
 
Example 5
Project: tinkergraph-gremlin   File: TinkerHelper.java   Source Code and License 6 votes vote down vote up
public static Iterator<TinkerVertex> getVertices(final TinkerVertex vertex, final Direction direction, final String... edgeLabels) {
    final List<Vertex> vertices = new ArrayList<>();
    if (direction.equals(Direction.OUT) || direction.equals(Direction.BOTH)) {
        if (vertex.outEdges != null) {
            if (edgeLabels.length == 0)
                vertex.outEdges.values().forEach(set -> set.forEach(edge -> vertices.add(((TinkerEdge) edge).inVertex)));
            else if (edgeLabels.length == 1)
                vertex.outEdges.getOrDefault(edgeLabels[0], Collections.emptySet()).forEach(edge -> vertices.add(((TinkerEdge) edge).inVertex));
            else
                Stream.of(edgeLabels).map(vertex.outEdges::get).filter(Objects::nonNull).flatMap(Set::stream).forEach(edge -> vertices.add(((TinkerEdge) edge).inVertex));
        }
    }
    if (direction.equals(Direction.IN) || direction.equals(Direction.BOTH)) {
        if (vertex.inEdges != null) {
            if (edgeLabels.length == 0)
                vertex.inEdges.values().forEach(set -> set.forEach(edge -> vertices.add(((TinkerEdge) edge).outVertex)));
            else if (edgeLabels.length == 1)
                vertex.inEdges.getOrDefault(edgeLabels[0], Collections.emptySet()).forEach(edge -> vertices.add(((TinkerEdge) edge).outVertex));
            else
                Stream.of(edgeLabels).map(vertex.inEdges::get).filter(Objects::nonNull).flatMap(Set::stream).forEach(edge -> vertices.add(((TinkerEdge) edge).outVertex));
        }
    }
    return (Iterator) vertices.iterator();
}
 
Example 6
Project: tinkergraph-gremlin   File: Artist.java   Source Code and License 6 votes vote down vote up
@Override
protected Iterator<Edge> specificEdges(Direction direction, String... edgeLabels) {
    List<Iterator<?>> iterators = new LinkedList<>();
    if (edgeLabels.length == 0) {
        edgeLabels = ALL_EDGES;
    }
    for (String label : edgeLabels) {
        if (label == WrittenBy.label) {
            if (direction == Direction.IN || direction == Direction.BOTH) {
                iterators.add(getWrittenByIn().iterator());
            }
        } else if (label == SungBy.label) {
            if (direction == Direction.IN || direction == Direction.BOTH) {
                iterators.add(getSungByIn().iterator());
            }
        }
    }

    Iterator<Edge>[] iteratorsArray = iterators.toArray(new Iterator[iterators.size()]);
    return IteratorUtils.concat(iteratorsArray);
}
 
Example 7
Project: bitsy   File: MemoryGraphStore.java   Source Code and License 6 votes vote down vote up
public List<EdgeBean> getEdges(UUID vertexId, Direction dir, String[] edgeLabels) {
    RetryDetails retryDetails = new RetryDetails();
    List<EdgeBean> ans;

    try {
        do {
            beginRead(retryDetails, true);
            VertexBean vBean = vertices.get(vertexId);

            ans = adjMap.getEdges(vBean, dir, edgeLabels);
        } while (shouldRetryRead(retryDetails));
    } finally {
        endRead(retryDetails);
    }
    
    return ans;
}
 
Example 8
Project: keti   File: GraphGenericRepository.java   Source Code and License 6 votes vote down vote up
public Set<Parent> getParents(final Vertex vertex, final String identifierKey) {
    Set<Parent> parentSet = new HashSet<>();
    vertex.edges(Direction.OUT, PARENT_EDGE_LABEL).forEachRemaining(edge -> {
        String parentIdentifier = getPropertyOrFail(edge.inVertex(), identifierKey);
        Attribute scope;
        Parent parent;
        try {
            scope = JSON_UTILS.deserialize((String) edge.property(SCOPE_PROPERTY_KEY).value(), Attribute.class);
            // use ParentEntity ?
            parent = new Parent(parentIdentifier, Sets.newHashSet(scope));
        } catch (Exception e) {
            LOGGER.debug("Error deserializing attribute", e);
            parent = new Parent(parentIdentifier);
        }
        parentSet.add(parent);

    });
    return parentSet;
}
 
Example 9
Project: hdt-gremlin   File: HDTVertexQuery.java   Source Code and License 6 votes vote down vote up
public Iterable<Edge> edges() {
	Iterable<Edge> in = null;
	Iterable<Edge> out = null;

	if(direction==Direction.IN || direction==Direction.BOTH) {
		if(vertex.getRole()==TripleComponentRole.OBJECT || vertex.getInternalId()<=vertex.getHDTGraph().getBaseGraph().getDictionary().getNshared()) {
			in = getEdges(new TripleID(0,0,vertex.getInternalId()));
		}
	}
	
	if(direction==Direction.OUT || direction==Direction.BOTH) {
		if(vertex.getRole()==TripleComponentRole.SUBJECT || vertex.getInternalId()<=vertex.getHDTGraph().getBaseGraph().getDictionary().getNshared()) {
			out = getEdges(new TripleID(vertex.getInternalId(),0,0));
		}
	}

	if(in!=null && out!=null) {
		return IteratorConcat.concat(in, out);
	} else if(in!=null) {
		return in;
	} else if(out!=null){
		return out;
	}
	return Collections.emptySet();
}
 
Example 10
Project: hdt-gremlin   File: HDTVertexQuery.java   Source Code and License 6 votes vote down vote up
public Iterable<Vertex> vertices() {
	Iterable<Vertex> in = null;
	Iterable<Vertex> out = null;

	if(direction==Direction.IN || direction==Direction.BOTH) {
		if(vertex.getRole()==TripleComponentRole.OBJECT || vertex.getInternalId()<=vertex.getHDTGraph().getBaseGraph().getDictionary().getNshared()) {
			in = Iter.mapIterable(getEdges(new TripleID(0,0,vertex.getInternalId())), new EdgeToVertex(Direction.OUT));
		}
	}

	if(direction==Direction.OUT || direction==Direction.BOTH) {
		if(vertex.getRole()==TripleComponentRole.SUBJECT || vertex.getInternalId()<=vertex.getHDTGraph().getBaseGraph().getDictionary().getNshared()) {
			out = Iter.mapIterable(getEdges(new TripleID(vertex.getInternalId(),0,0)), new EdgeToVertex(Direction.IN));
		}
	}

	if(in!=null && out!=null) {
		return IteratorConcat.concat(in, out);
	} else if(in!=null) {
		return in;
	} else if(out!=null){
		return out;
	}
	return Collections.emptySet();
}
 
Example 11
Project: tinkerpop3   File: SparqlGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * @see {@link Templates#EDGES_FROM_VERTEX}
 */
String edgesFromVertex(final BlazeVertex src, final Direction dir,
        final List<URI> edgeLabels) {
    final URI id = src.rdfId();
    final StringBuilder vc = buildValuesClause(
            new StringBuilder(), "?src", asList(id));
    if (!edgeLabels.isEmpty()) {
        buildValuesClause(vc, "?label", edgeLabels);
    }
    final String queryStr;
    if (dir == Direction.BOTH) {
        queryStr = EDGES_FROM_VERTEX_BOTH.replace(Templates.VALUES, vc.toString());
    } else {
        final String DIRECTION = dir == Direction.OUT ? FORWARD : REVERSE;
        queryStr = EDGES_FROM_VERTEX.replace(Templates.VALUES, vc.toString())
                                    .replace(Templates.DIRECTION, DIRECTION);
    }
    return queryStr;
}
 
Example 12
Project: LiteGraph   File: DetachedEdgeTest.java   Source Code and License 6 votes vote down vote up
@Test
@LoadGraphWith(GraphData.MODERN)
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
@FeatureRequirement(featureClass = Graph.Features.EdgePropertyFeatures.class, feature = Graph.Features.EdgePropertyFeatures.FEATURE_DOUBLE_VALUES)
public void shouldConstructDetachedEdgeAsReference() {
    g.E(convertToEdgeId("marko", "knows", "vadas")).next().property("year", 2002);
    final DetachedEdge detachedEdge = DetachedFactory.detach(g.E(convertToEdgeId("marko", "knows", "vadas")).next(), false);
    assertEquals(convertToEdgeId("marko", "knows", "vadas"), detachedEdge.id());
    assertEquals("knows", detachedEdge.label());
    assertEquals(DetachedVertex.class, detachedEdge.vertices(Direction.OUT).next().getClass());
    assertEquals(convertToVertexId("marko"), detachedEdge.vertices(Direction.OUT).next().id());
    assertEquals("person", detachedEdge.vertices(Direction.IN).next().label());
    assertEquals(DetachedVertex.class, detachedEdge.vertices(Direction.IN).next().getClass());
    assertEquals(convertToVertexId("vadas"), detachedEdge.vertices(Direction.IN).next().id());
    assertEquals("person", detachedEdge.vertices(Direction.IN).next().label());

    assertEquals(0, IteratorUtils.count(detachedEdge.properties()));
}
 
Example 13
Project: grakn   File: OutRolePlayerFragment.java   Source Code and License 6 votes vote down vote up
private GraphTraversal<Element, Vertex> edgeRelationTraversal(
        GraknTx graph, Direction direction, Schema.EdgeProperty roleProperty, Collection<Var> vars) {
    GraphTraversal<Element, Edge> edgeTraversal = Fragments.isEdge(__.identity());

    // Filter by any provided type labels
    applyLabelsToTraversal(edgeTraversal, roleProperty, roleLabels(), graph);
    applyLabelsToTraversal(edgeTraversal, RELATIONSHIP_TYPE_LABEL_ID, relationTypeLabels(), graph);

    traverseToRole(edgeTraversal, role(), roleProperty, vars);

    // Identify the relation - role-player pair by combining the relationship edge and direction into a map
    edgeTraversal.as(RELATION_EDGE.name()).constant(direction).as(RELATION_DIRECTION.name());
    edgeTraversal.select(Pop.last, RELATION_EDGE.name(), RELATION_DIRECTION.name()).as(edge().name()).select(RELATION_EDGE.name());

    return edgeTraversal.toV(direction);
}
 
Example 14
Project: LiteGraph   File: StarGraphTest.java   Source Code and License 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 15
Project: grakn   File: InRolePlayerFragment.java   Source Code and License 6 votes vote down vote up
private GraphTraversal<Vertex, Edge> edgeRelationTraversal(
        GraknTx graph, Direction direction, Schema.EdgeProperty roleProperty, Collection<Var> vars) {

    GraphTraversal<Vertex, Edge> edgeTraversal = __.toE(direction, Schema.EdgeLabel.ATTRIBUTE.getLabel());

    // Identify the relation - role-player pair by combining the relationship edge and direction into a map
    edgeTraversal.as(RELATION_EDGE.name()).constant(direction).as(RELATION_DIRECTION.name());
    edgeTraversal.select(Pop.last, RELATION_EDGE.name(), RELATION_DIRECTION.name()).as(edge().name()).select(RELATION_EDGE.name());

    // Filter by any provided type labels
    applyLabelsToTraversal(edgeTraversal, roleProperty, roleLabels(), graph);
    applyLabelsToTraversal(edgeTraversal, RELATIONSHIP_TYPE_LABEL_ID, relationTypeLabels(), graph);

    traverseToRole(edgeTraversal, role(), roleProperty, vars);

    return edgeTraversal;
}
 
Example 16
Project: LiteGraph   File: GraphSONWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Writes a list of vertices in adjacency list format where vertices are written with edges from both
 * directions.  Under this serialization model, edges are grouped by label.
 *
 * @param outputStream the stream to write to.
 * @param vertexIterator    a traversal that returns a list of vertices.
 * @param direction    if direction is null then no edges are written.
 */
@Override
public void writeVertices(final OutputStream outputStream, final Iterator<Vertex> vertexIterator, final Direction direction) throws IOException {
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        if (wrapAdjacencyList) writer.write("{\"" + GraphSONTokens.VERTICES + "\":[");
        while (vertexIterator.hasNext()) {
            writeVertex(baos, vertexIterator.next(), direction);
            writer.write(new String(baos.toByteArray()));
            if (wrapAdjacencyList) {
                if (vertexIterator.hasNext())
                    writer.write(",");
            } else {
                writer.newLine();
            }
            baos.reset();
        }
        if (wrapAdjacencyList) writer.write("]}");
    }

    writer.flush();
}
 
Example 17
Project: LiteGraph   File: StarGraphTest.java   Source Code and License 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 18
Project: LiteGraph   File: StarGraphTest.java   Source Code and License 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 = new Random(234335l);
    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 19
Project: LiteGraph   File: ReferenceGraphTest.java   Source Code and License 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 20
Project: grakn   File: RelationshipTypeImpl.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param role The {@link Role} to delete from this {@link RelationshipType}.
 * @return The {@link Relationship} Type itself.
 */
@Override
public RelationshipType deleteRelates(Role role) {
    checkSchemaMutationAllowed();
    deleteEdge(Direction.OUT, Schema.EdgeLabel.RELATES, (Concept) role);

    RoleImpl roleTypeImpl = (RoleImpl) role;
    //Add roleplayers of role to make sure relations are still valid
    roleTypeImpl.rolePlayers().forEach(rolePlayer -> vertex().tx().txCache().trackForValidation(rolePlayer));


    //Add the Role Type itself
    vertex().tx().txCache().trackForValidation(roleTypeImpl);

    //Add the Relationship Type
    vertex().tx().txCache().trackForValidation(roleTypeImpl);

    //Remove from internal cache
    cachedRelates.ifPresent(set -> set.remove(role));

    //Remove from roleTypeCache
    ((RoleImpl) role).deleteCachedRelationType(this);

    return this;
}
 
Example 21
Project: LiteGraph   File: TinkerHelper.java   Source Code and License 6 votes vote down vote up
public static Iterator<TinkerEdge> getEdges(final TinkerVertex vertex, final Direction direction, final String... edgeLabels) {
    final List<Edge> edges = new ArrayList<>();
    if (direction.equals(Direction.OUT) || direction.equals(Direction.BOTH)) {
        if (vertex.outEdges != null) {
            if (edgeLabels.length == 0)
                vertex.outEdges.values().forEach(edges::addAll);
            else if (edgeLabels.length == 1)
                edges.addAll(vertex.outEdges.getOrDefault(edgeLabels[0], Collections.emptySet()));
            else
                Stream.of(edgeLabels).map(vertex.outEdges::get).filter(Objects::nonNull).forEach(edges::addAll);
        }
    }
    if (direction.equals(Direction.IN) || direction.equals(Direction.BOTH)) {
        if (vertex.inEdges != null) {
            if (edgeLabels.length == 0)
                vertex.inEdges.values().forEach(edges::addAll);
            else if (edgeLabels.length == 1)
                edges.addAll(vertex.inEdges.getOrDefault(edgeLabels[0], Collections.emptySet()));
            else
                Stream.of(edgeLabels).map(vertex.inEdges::get).filter(Objects::nonNull).forEach(edges::addAll);
        }
    }
    return (Iterator) edges.iterator();
}
 
Example 22
Project: LiteGraph   File: GraphTraversal.java   Source Code and License 6 votes vote down vote up
/**
 * @deprecated As of release 3.1.0, replaced by {@link #addE(String)}
 */
@Deprecated
public default GraphTraversal<S, Edge> addE(final Direction direction, final String firstVertexKeyOrEdgeLabel, final String edgeLabelOrSecondVertexKey, final Object... propertyKeyValues) {
    if (propertyKeyValues.length % 2 == 0) {
        // addOutE("createdBy", "a")
        this.addE(firstVertexKeyOrEdgeLabel);
        if (direction.equals(Direction.OUT))
            this.to(edgeLabelOrSecondVertexKey);
        else
            this.from(edgeLabelOrSecondVertexKey);
        ((Mutating) this.asAdmin().getEndStep()).addPropertyMutations(propertyKeyValues);
        return (GraphTraversal<S, Edge>) this;
    } else {
        // addInE("a", "codeveloper", "b", "year", 2009)
        this.addE(edgeLabelOrSecondVertexKey);
        if (direction.equals(Direction.OUT))
            this.from(firstVertexKeyOrEdgeLabel).to((String) propertyKeyValues[0]);
        else
            this.to(firstVertexKeyOrEdgeLabel).from((String) propertyKeyValues[0]);
        ((Mutating) this.asAdmin().getEndStep()).addPropertyMutations(Arrays.copyOfRange(propertyKeyValues, 1, propertyKeyValues.length));
        return (GraphTraversal<S, Edge>) this;
    }
}
 
Example 23
Project: LiteGraph   File: ScaleIterator.java   Source Code and License 6 votes vote down vote up
public Iterator<Edge> returnEdges(TinkerVertex outVertex, Direction direction, final String... edgeLabels) {
    ScaleIterator scaleIterator = this;
    Iterator<Edge> iterator = new Iterator<Edge>() {
        @Override
        public boolean hasNext() {
            return scaleIterator.hasNext();
        }

        @Override
        public Edge next() {
            Object obj = scaleIterator.next();
            String[] temp = split(obj.toString());

            String pre = temp[0];
            String label = temp[1];
            String Eid = temp[2];
            String inV = temp[3];
            TinkerVertex inVertex ;//= new TinkerVertex(inV, null);
            TinkerEdge edge = null; //= new TinkerEdge(Eid, outVertex, label, inVertex, false);
            return edge;
        }
    };
    return iterator;
}
 
Example 24
Project: LiteGraph   File: TinkerHelper.java   Source Code and License 6 votes vote down vote up
public static Iterator<TinkerVertex> getVertices(final TinkerVertex vertex, final Direction direction, final String... edgeLabels) {
    final List<Vertex> vertices = new ArrayList<>();
    if (direction.equals(Direction.OUT) || direction.equals(Direction.BOTH)) {
        if (vertex.outEdges != null) {
            if (edgeLabels.length == 0)
                vertex.outEdges.values().forEach(set -> set.forEach(edge -> vertices.add(((TinkerEdge) edge).inVertex)));
            else if (edgeLabels.length == 1)
                vertex.outEdges.getOrDefault(edgeLabels[0], Collections.emptySet()).forEach(edge -> vertices.add(((TinkerEdge) edge).inVertex));
            else
                Stream.of(edgeLabels).map(vertex.outEdges::get).filter(Objects::nonNull).flatMap(Set::stream).forEach(edge -> vertices.add(((TinkerEdge) edge).inVertex));
        }
    }
    if (direction.equals(Direction.IN) || direction.equals(Direction.BOTH)) {
        if (vertex.inEdges != null) {
            if (edgeLabels.length == 0)
                vertex.inEdges.values().forEach(set -> set.forEach(edge -> vertices.add(((TinkerEdge) edge).outVertex)));
            else if (edgeLabels.length == 1)
                vertex.inEdges.getOrDefault(edgeLabels[0], Collections.emptySet()).forEach(edge -> vertices.add(((TinkerEdge) edge).outVertex));
            else
                Stream.of(edgeLabels).map(vertex.inEdges::get).filter(Objects::nonNull).flatMap(Set::stream).forEach(edge -> vertices.add(((TinkerEdge) edge).outVertex));
        }
    }
    return (Iterator) vertices.iterator();
}
 
Example 25
Project: hgraphdb   File: EdgeIndexModel.java   Source Code and License 6 votes vote down vote up
public byte[] serializeForWrite(Edge edge, Direction direction, boolean isUnique, String key) {
    Object inVertexId = edge.inVertex().id();
    Object outVertexId = edge.outVertex().id();
    PositionedByteRange buffer = new SimplePositionedMutableByteRange(4096);
    ValueUtils.serializeWithSalt(buffer, direction == Direction.IN ? inVertexId : outVertexId);
    OrderedBytes.encodeInt8(buffer, direction == Direction.IN ? (byte) 1 : (byte) 0, Order.ASCENDING);
    OrderedBytes.encodeInt8(buffer, isUnique ? (byte) 1 : (byte) 0, Order.ASCENDING);
    OrderedBytes.encodeString(buffer, key, Order.ASCENDING);
    OrderedBytes.encodeString(buffer, edge.label(), Order.ASCENDING);
    if (key.equals(Constants.CREATED_AT)) {
        ValueUtils.serialize(buffer, ((HBaseEdge) edge).createdAt());
    } else {
        ValueUtils.serialize(buffer, edge.value(key));
    }
    if (!isUnique) {
        ValueUtils.serialize(buffer, direction == Direction.IN ? outVertexId : inVertexId);
        ValueUtils.serialize(buffer, edge.id());
    }
    buffer.setLength(buffer.getPosition());
    buffer.setPosition(0);
    byte[] bytes = new byte[buffer.getRemaining()];
    buffer.get(bytes);
    return bytes;
}
 
Example 26
Project: hgraphdb   File: HBaseVertex.java   Source Code and License 6 votes vote down vote up
@Override
public void remove() {
    // Remove edges incident to this vertex.
    edges(Direction.BOTH).forEachRemaining(edge -> {
        try {
            edge.remove();
        } catch (HBaseGraphNotFoundException e) {
            // ignore
        }
    });

    // Get rid of the vertex.
    deleteFromModel();
    deleteFromIndexModel();

    setDeleted(true);
    if (!isCached()) {
        HBaseVertex cachedVertex = (HBaseVertex) graph.findVertex(id, false);
        if (cachedVertex != null) cachedVertex.setDeleted(true);
    }
}
 
Example 27
Project: LiteGraph   File: GraphSONReader.java   Source Code and License 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 {
    final Map<String, Object> vertexData = mapper.readValue(inputStream, mapTypeReference);
    final StarGraph starGraph = StarGraphGraphSONSerializer.readStarGraphVertex(vertexData);
    if (vertexAttachMethod != null) vertexAttachMethod.apply(starGraph.getStarVertex());

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

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

    return starGraph.getStarVertex();
}
 
Example 28
Project: hgraphdb   File: CustomTest.java   Source Code and License 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 29
Project: LiteGraph   File: DetachedEdgeTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldConstructDetachedEdgeFromParts() {
    final Map<String, Object> properties = new HashMap<>();
    properties.put("x", "a");
    properties.put("y", "b");

    final DetachedEdge de = new DetachedEdge(10, "bought", properties, Pair.with(1, "person"), Pair.with(2, "product"));

    assertEquals(10, de.id());
    assertEquals("bought", de.label());
    assertEquals("person", de.vertices(Direction.OUT).next().label());
    assertEquals(1, de.vertices(Direction.OUT).next().id());
    assertEquals("product", de.vertices(Direction.IN).next().label());
    assertEquals(2, de.vertices(Direction.IN).next().id());

    assertEquals("a", de.properties("x").next().value());
    assertEquals(1, IteratorUtils.count(de.properties("x")));

    assertEquals("a", de.property("x").value());
    assertEquals("x", de.property("x").key());

    assertEquals("b", de.property("y").value());
    assertEquals("y", de.property("y").key());
}
 
Example 30
Project: LiteGraph   File: HadoopEdgeIterator.java   Source Code and License 6 votes vote down vote up
@Override
public Edge next() {
    try {
        while (true) {
            if (this.edgeIterator.hasNext())
                return new HadoopEdge(this.edgeIterator.next(), this.graph);
            if (this.readers.isEmpty())
                throw FastNoSuchElementException.instance();
            if (this.readers.peek().nextKeyValue()) {
                this.edgeIterator = this.readers.peek().getCurrentValue().get().edges(Direction.OUT);
            } else {
                this.readers.remove().close();
            }
        }
    } catch (final Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example 31
Project: LiteGraph   File: StarGraph.java   Source Code and License 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 32
Project: act-platform   File: FactEdgeTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testVerticesWithDirectionIn() {
  UUID factID = mockFact(null);
  UUID inVertexObjectID = mockObject();
  UUID outVertexObjectID = mockObject();
  Edge edge = new FactEdge(getActGraph(), factID, inVertexObjectID, outVertexObjectID);

  Iterator<Vertex> vertices = edge.vertices(Direction.IN);
  assertSame(inVertexObjectID, vertices.next().id());
  assertFalse(vertices.hasNext());
}
 
Example 33
Project: act-platform   File: FactEdgeTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testVerticesWithDirectionOut() {
  UUID factID = mockFact(null);
  UUID inVertexObjectID = mockObject();
  UUID outVertexObjectID = mockObject();
  Edge edge = new FactEdge(getActGraph(), factID, inVertexObjectID, outVertexObjectID);

  Iterator<Vertex> vertices = edge.vertices(Direction.OUT);
  assertSame(outVertexObjectID, vertices.next().id());
  assertFalse(vertices.hasNext());
}
 
Example 34
Project: act-platform   File: FactEdgeTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testVerticesWithDirectionBoth() {
  UUID factID = mockFact(null);
  UUID inVertexObjectID = mockObject();
  UUID outVertexObjectID = mockObject();
  Edge edge = new FactEdge(getActGraph(), factID, inVertexObjectID, outVertexObjectID);

  Iterator<Vertex> vertices = edge.vertices(Direction.BOTH);
  assertSame(outVertexObjectID, vertices.next().id());
  assertSame(inVertexObjectID, vertices.next().id());
  assertFalse(vertices.hasNext());
}
 
Example 35
Project: gremlin-ogm   File: Edge.java   Source Code and License 5 votes vote down vote up
public static IllegalStateException missingEdgeVertex(Direction direction, Edge edge,
    String vertexString) {
  return new IllegalStateException(
      String.format("%s vertex (%s) doesn't exist for edge %s",
          direction.equals(Direction.OUT) ? "Outgoing" : "Incoming", vertexString,
          edge));
}
 
Example 36
Project: debattons   File: ReactionService.java   Source Code and License 5 votes vote down vote up
public Reaction findByIdLoadingReactedToDepth(final String id, final int reactedToDepth) throws Exception {
  return graphUtils.doInGraphTransaction(graph -> {
    Vertex reactionVertex = createReactionTraversalById(id, graph).next();
    Reaction reaction = Reaction.fromVertex(reactionVertex, graphUtils);
    loadReactedToByOriginalReactionAndVertexAndDepth(reaction, reactionVertex, reactedToDepth, graph);
    Iterator<Vertex> reactedFromIt = reactionVertex.vertices(Direction.IN, "reactedTo");
    if (reactedFromIt.hasNext()) {
      reaction.setReactedFrom(Reaction.fromVertex(reactedFromIt.next(), graphUtils));
    }
    return reaction;
  });
}
 
Example 37
Project: debattons   File: ReactionService.java   Source Code and License 5 votes vote down vote up
private void loadReactedToByOriginalReactionAndVertexAndDepth(final Reaction originalReaction, Vertex originalVertex, final int depth, Graph graph) throws Exception {
  if (depth > 0) {
    Set<Reaction> reactedTo = new LinkedHashSet<>();
    originalReaction.setReactedTo(reactedTo);

    for (Iterator<Vertex> reactedToVertices = originalVertex.vertices(Direction.OUT, "reactedTo"); reactedToVertices.hasNext(); ) {
      Vertex reactedToVertex = reactedToVertices.next();
      Reaction reactedToReaction = Reaction.fromVertex(reactedToVertex, graphUtils);
      reactedTo.add(reactedToReaction);
      if (depth > 1) {
        loadReactedToByOriginalReactionAndVertexAndDepth(reactedToReaction, reactedToVertex, depth - 1, graph);
      }
    }
  }
}
 
Example 38
Project: tinkergraph-gremlin   File: TinkerEdge.java   Source Code and License 5 votes vote down vote up
@Override
public Iterator<Vertex> vertices(final Direction direction) {
    if (removed) return Collections.emptyIterator();
    switch (direction) {
        case OUT:
            return IteratorUtils.of(this.outVertex);
        case IN:
            return IteratorUtils.of(this.inVertex);
        default:
            return IteratorUtils.of(this.outVertex, this.inVertex);
    }
}
 
Example 39
Project: tinkergraph-gremlin   File: TinkerVertex.java   Source Code and License 5 votes vote down vote up
@Override
public void remove() {
    final List<Edge> edges = new ArrayList<>();
    this.edges(Direction.BOTH).forEachRemaining(edges::add);
    edges.stream().filter(edge -> !((TinkerEdge) edge).removed).forEach(Edge::remove);
    this.properties = null;
    TinkerHelper.removeElementIndex(this);
    this.graph.vertices.remove(this.id);
    this.removed = true;
}
 
Example 40
Project: tinkergraph-gremlin   File: TinkerVertex.java   Source Code and License 5 votes vote down vote up
@Override
public Iterator<Edge> edges(final Direction direction, final String... edgeLabels) {
    final Iterator<Edge> edgeIterator = (Iterator) TinkerHelper.getEdges(this, direction, edgeLabels);
    return TinkerHelper.inComputerMode(this.graph) ?
            IteratorUtils.filter(edgeIterator, edge -> this.graph.graphComputerView.legalEdge(this, edge)) :
            edgeIterator;
}