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

The following are top voted examples for showing how to use org.apache.tinkerpop.gremlin.structure.Edge. 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: hdt-gremlin   File: HDTVertexQuery.java   View source code 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 2
Project: act-platform   File: FactEdgeTest.java   View source code 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 3
Project: hdt-gremlin   File: HDTtoGremlin.java   View source code 6 votes vote down vote up
public static void smallTest(Graph graph) {
	Iterator<Vertex> it = graph.vertices();
	int i=0;
	while(i<100 && it.hasNext()) {
		Vertex v = it.next();
		System.out.println(v.id()+"/"+v.property("node"));
		i++;

	}
	
	// Iterate over Edges
	Iterator<Edge> it2 = graph.edges();
	i=0;
	while(i<100 && it2.hasNext()) {
		Edge e = it2.next();
		System.out.println(e);
		i++;
	}
}
 
Example 4
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 6 votes vote down vote up
/**
 * An empty private constructor that initializes {@link TinkerGraph}.
 */
private TinkerGraph(final Configuration configuration, boolean usesSpecializedElements) {
    this.configuration = configuration;
    this.usesSpecializedElements = usesSpecializedElements;
    vertexIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, Vertex.class);
    edgeIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, Edge.class);
    vertexPropertyIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, VertexProperty.class);
    defaultVertexPropertyCardinality = VertexProperty.Cardinality.valueOf(
            configuration.getString(GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.single.name()));

    graphLocation = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_LOCATION, null);
    graphFormat = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_FORMAT, null);

    if ((graphLocation != null && null == graphFormat) || (null == graphLocation && graphFormat != null))
        throw new IllegalStateException(String.format("The %s and %s must both be specified if either is present",
                GREMLIN_TINKERGRAPH_GRAPH_LOCATION, GREMLIN_TINKERGRAPH_GRAPH_FORMAT));

    if (graphLocation != null) loadGraph();
}
 
Example 5
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 6 votes vote down vote up
private <T extends Element> Iterator<T> createElementIterator(final Class<T> clazz, final Map<Object, T> elements,
                                                              final IdManager idManager,
                                                              final Object... ids) {
    final Iterator<T> iterator;
    if (0 == ids.length) {
        iterator = elements.values().iterator();
    } else {
        final List<Object> idList = Arrays.asList(ids);
        validateHomogenousIds(idList);

        // if the type is of Element - have to look each up because it might be an Attachable instance or
        // other implementation. the assumption is that id conversion is not required for detached
        // stuff - doesn't seem likely someone would detach a Titan vertex then try to expect that
        // vertex to be findable in OrientDB
        return clazz.isAssignableFrom(ids[0].getClass()) ?
                IteratorUtils.filter(IteratorUtils.map(idList, id -> elements.get(clazz.cast(id).id())).iterator(), Objects::nonNull)
                : IteratorUtils.filter(IteratorUtils.map(idList, id -> elements.get(idManager.convert(id))).iterator(), Objects::nonNull);
    }
    return TinkerHelper.inComputerMode(this) ?
            (Iterator<T>) (clazz.equals(Vertex.class) ?
                    IteratorUtils.filter((Iterator<Vertex>) iterator, t -> this.graphComputerView.legalVertex(t)) :
                    IteratorUtils.filter((Iterator<Edge>) iterator, t -> this.graphComputerView.legalEdge(t.outVertex(), t))) :
            iterator;
}
 
Example 6
Project: tinkergraph-gremlin   File: TinkerHelper.java   View source code 6 votes vote down vote up
protected static Edge addEdge(final TinkerGraph graph, final TinkerVertex outVertex, final TinkerVertex inVertex, final String label, final Object... keyValues) {
    ElementHelper.validateLabel(label);
    ElementHelper.legalPropertyKeyValueArray(keyValues);

    Object idValue = graph.edgeIdManager.convert(ElementHelper.getIdValue(keyValues).orElse(null));

    final Edge edge;
    if (null != idValue) {
        if (graph.edges.containsKey(idValue))
            throw Graph.Exceptions.edgeWithIdAlreadyExists(idValue);
    } else {
        idValue = graph.edgeIdManager.getNextId(graph);
    }

    edge = new TinkerEdge(idValue, outVertex, label, inVertex);
    ElementHelper.attachProperties(edge, keyValues);
    graph.edges.put(edge.id(), edge);
    TinkerHelper.addOutEdge(outVertex, label, edge);
    TinkerHelper.addInEdge(inVertex, label, edge);
    return edge;

}
 
Example 7
Project: tinkergraph-gremlin   File: TinkerHelper.java   View source code 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 8
Project: bitsy   File: BitsyGraph.java   View source code 6 votes vote down vote up
/** 
 * Constructor with a Configuration object with String dbPath, boolean allowFullGraphScans, long txLogThreshold and double reorgFactor 
 */
public BitsyGraph(Configuration configuration) {
	this(Paths.get(configuration.getString(DB_PATH_KEY)),
		configuration.getBoolean(ALLOW_FULL_GRAPH_SCANS_KEY, Boolean.TRUE),
		configuration.getLong(TX_LOG_THRESHOLD_KEY, DEFAULT_TX_LOG_THRESHOLD),
		configuration.getDouble(REORG_FACTOR_KEY, DEFAULT_REORG_FACTOR),
		configuration.getBoolean(CREATE_DIR_IF_MISSING_KEY, false));
	String isoLevelStr = configuration.getString(DEFAULT_ISOLATION_LEVEL_KEY);
	if (isoLevelStr != null) {
		setDefaultIsolationLevel(BitsyIsolationLevel.valueOf(isoLevelStr));
	}
	String vertexIndices = configuration.getString(VERTEX_INDICES_KEY);
	if (vertexIndices != null) {
		createIndices(Vertex.class, vertexIndices);
	}
	String edgeIndices = configuration.getString(EDGE_INDICES_KEY);
	if (edgeIndices != null) {
		createIndices(Edge.class, edgeIndices);
	}
	this.origConfig = configuration;
}
 
Example 9
Project: tinkergraph-gremlin   File: TinkerIoRegistryV2d0.java   View source code 6 votes vote down vote up
@Override
public void serialize(final TinkerGraph graph, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
        throws IOException {
    jsonGenerator.writeStartObject();
    jsonGenerator.writeFieldName(GraphSONTokens.VERTICES);
    jsonGenerator.writeStartArray();

    final Iterator<Vertex> vertices = graph.vertices();
    while (vertices.hasNext()) {
        serializerProvider.defaultSerializeValue(vertices.next(), jsonGenerator);
    }

    jsonGenerator.writeEndArray();
    jsonGenerator.writeFieldName(GraphSONTokens.EDGES);
    jsonGenerator.writeStartArray();

    final Iterator<Edge> edges = graph.edges();
    while (edges.hasNext()) {
        serializerProvider.defaultSerializeValue(edges.next(), jsonGenerator);
    }

    jsonGenerator.writeEndArray();
    jsonGenerator.writeEndObject();
}
 
Example 10
Project: tinkergraph-gremlin   File: TinkerIoRegistryV2d0.java   View source code 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 11
Project: bitsy   File: BitsyGraph.java   View source code 6 votes vote down vote up
private Edge getEdge(Object id) {
    if (id == null) {
        throw new IllegalArgumentException("The edge ID passed to getEdge() is null");
    }
    
    if (id instanceof UUID) {
        return getTx().getEdge((UUID)id);
    } else if (id instanceof String) {
        // Get the UUID from the string representation -- may fail
        UUID uuid;
        try {
            uuid = UUID.fromString((String)id);
        } catch (IllegalArgumentException e) {
            // Decoding failed
            return null;
        }
        
        return getTx().getEdge(uuid);
    } else if (id instanceof Edge) {
		return getTx().getEdge((UUID)((Edge)id).id());
    } else {
        // Wrong type
        return null;
    }
}
 
Example 12
Project: tinkergraph-gremlin   File: TinkerGraphGraphSONSerializerV2d0Test.java   View source code 6 votes vote down vote up
@Test
public void deserializersTestsEdge() {
    final TinkerGraph tg = TinkerGraph.open();

    final Vertex v = tg.addVertex("vertexTest");
    final Vertex v2 = tg.addVertex("vertexTest");

    final Edge ed = v.addEdge("knows", v2, "time", LocalDateTime.now());

    final GraphWriter writer = getWriter(defaultMapperV2d0);
    final GraphReader reader = getReader(defaultMapperV2d0);

    try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        writer.writeObject(out, ed);
        final String json = out.toString();

        // Object works, because there's a type in the payload now
        // Edge.class would work as well
        // Anything else would not because we check the type in param here with what's in the JSON, for safety.
        final Edge eRead = (Edge)reader.readObject(new ByteArrayInputStream(json.getBytes()), Object.class);
        assertEquals(ed, eRead);
    } catch (IOException e) {
        e.printStackTrace();
        fail("Should not have thrown exception: " + e.getMessage());
    }
}
 
Example 13
Project: bitsy   File: MemoryGraphStore.java   View source code 6 votes vote down vote up
@Override
public <T extends Element> void createKeyIndex(String key, Class<T> elementType) {
    beginWrite();

    try {
        if (elementType == null) {
            throw new IllegalArgumentException("Element type in createKeyIndex() can not be null");
        } else if (elementType.equals(Vertex.class)) {
            vIndexMap.createKeyIndex(key, getAllVertices().iterator());
        } else if (elementType.equals(Edge.class)) {
            eIndexMap.createKeyIndex(key, getAllEdges().iterator());
        } else {
            throw new BitsyException(BitsyErrorCodes.UNSUPPORTED_INDEX_TYPE, "Encountered index type: " + elementType);
        }
    } finally {
        endWrite();
    }
}
 
Example 14
Project: bitsy   File: MemoryGraphStore.java   View source code 6 votes vote down vote up
@Override
public <T extends Element> void dropKeyIndex(String key, Class<T> elementType) {
    beginWrite();

    try {
        if (elementType == null) {
            throw new IllegalArgumentException("Element type in dropKeyIndex() can not be null");
        } else if (elementType.equals(Vertex.class)) {
            vIndexMap.dropKeyIndex(key);
        } else if (elementType.equals(Edge.class)) {
            eIndexMap.dropKeyIndex(key);
        } else {
            throw new BitsyException(BitsyErrorCodes.UNSUPPORTED_INDEX_TYPE, "Encountered index type: " + elementType);
        }
    } finally {
        endWrite();
    }
}
 
Example 15
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   View source code 6 votes vote down vote up
@Test
public void shouldRemoveEdgeFromAnIndex() {
    final TinkerGraph g = TinkerGraph.open();
    g.createIndex("oid", Edge.class);

    final Vertex v = g.addVertex();
    v.addEdge("friend", v, "oid", "1", "weight", 0.5f);
    final Edge e = v.addEdge("friend", v, "oid", "1", "weight", 0.5f);
    v.addEdge("friend", v, "oid", "2", "weight", 0.6f);

    // a tricky way to evaluate if indices are actually being used is to pass a fake BiPredicate to has()
    // to get into the Pipeline and evaluate what's going through it.  in this case, we know that at index
    // is used because only oid 1 should pass through the pipeline due to the inclusion of the
    // key index lookup on "oid".  If there's an weight of something other than 0.5f in the pipeline being
    // evaluated then something is wrong.
    assertEquals(new Long(2), g.traversal().E().has("weight", P.test((t, u) -> {
        assertEquals(0.5f, t);
        return true;
    }, 0.5)).has("oid", "1").count().next());

    e.remove();
    assertEquals(new Long(1), g.traversal().E().has("weight", P.test((t, u) -> {
        assertEquals(0.5f, t);
        return true;
    }, 0.5)).has("oid", "1").count().next());
}
 
Example 16
Project: act-platform   File: ElementFactory.java   View source code 5 votes vote down vote up
/**
 * Create edges based on a binding between an Object and a Fact.
 * <p>
 * It will fetch the Fact and create edges between the Object and other Objects bound to the Fact. If only the given
 * Object is bound to the Fact a loop edge is created. If the Fact is bound to multiple Objects an edge for each
 * binding is created where applicable (taking the binding directions into account).
 * <p>
 * Created edges are cached for later retrieval by {@link ElementFactory#getEdge(UUID)}.
 *
 * @param inBinding Binding between an Object and a Fact (incoming vertex).
 * @return Created edges.
 */
public Set<Edge> createEdges(ObjectFactBindingEntity inBinding) {
  ObjectUtils.notNull(inBinding, "'inBinding' is null!");

  FactEntity fact = owner.getFactManager().getFact(inBinding.getFactID());
  // Only create edges if user has access to Fact.
  if (fact == null || !owner.hasFactAccess(fact)) {
    return new HashSet<>();
  }

  // If the Fact is only bound to the 'inBinding' Object then this needs to be represented as a loop in the graph.
  if (CollectionUtils.size(fact.getBindings()) == 1 && Objects.equals(fact.getBindings().get(0).getObjectID(), inBinding.getObjectID())) {
    return SetUtils.set(createAndCache(inBinding.getFactID(), inBinding.getObjectID(), inBinding.getObjectID()));
  }

  Set<Edge> edges = new HashSet<>();
  for (FactEntity.FactObjectBinding outBinding : ListUtils.list(fact.getBindings())) {
    // Skip bindings to 'inBinding' Object.
    if (Objects.equals(outBinding.getObjectID(), inBinding.getObjectID())) continue;

    // For all other bindings create an edge where the objectID of the binding is the outgoing vertex.
    // But only if the directions fit together!
    if ((inBinding.getDirection() == Direction.None && outBinding.getDirection() == Direction.None) ||
            (inBinding.getDirection() == Direction.BiDirectional && outBinding.getDirection() == Direction.BiDirectional) ||
            (inBinding.getDirection() == Direction.FactIsDestination && outBinding.getDirection() == Direction.FactIsSource)) {
      edges.add(createAndCache(inBinding.getFactID(), inBinding.getObjectID(), outBinding.getObjectID()));
    }

    // In this case need to swap 'inBinding' and 'outBinding' in order to have the correct edge direction.
    if (inBinding.getDirection() == Direction.FactIsSource && outBinding.getDirection() == Direction.FactIsDestination) {
      edges.add(createAndCache(inBinding.getFactID(), outBinding.getObjectID(), inBinding.getObjectID()));
    }
  }

  return edges;
}
 
Example 17
Project: act-platform   File: FactEdgeTest.java   View source code 5 votes vote down vote up
@Test
public void testCreateEdgeFromFact() {
  Edge edge = createEdge();
  assertNotNull(edge.id());
  assertEquals("type", edge.label());
  assertSame(getActGraph(), edge.graph());
}
 
Example 18
Project: act-platform   File: FactEdgeTest.java   View source code 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 19
Project: bitsy   File: IndexBean.java   View source code 5 votes vote down vote up
@JsonIgnore
public Class getIndexClass() {
    if (type == 0) {
        return Vertex.class;
    } else if (type == 1) {
        return Edge.class;
    } else {
        throw new BitsyException(BitsyErrorCodes.DATABASE_IS_CORRUPT, "Unrecognized index type " + type);
    }
}
 
Example 20
Project: act-platform   File: FactEdgeTest.java   View source code 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 21
Project: act-platform   File: FactEdgeTest.java   View source code 5 votes vote down vote up
@Test
public void testValidateEquality() {
  Edge edge1 = createEdge();
  Edge edge2 = createEdge();

  assertEquals(edge1, edge1);
  assertEquals(edge2, edge2);
  assertNotEquals(edge1, edge2);
}
 
Example 22
Project: act-platform   File: FactEdgeTest.java   View source code 5 votes vote down vote up
@Test
public void testValidateIdEquality() {
  Edge edge1 = createEdge();
  Edge edge2 = createEdge();

  assertEquals(edge1.id(), edge1.id());
  assertEquals(edge2.id(), edge2.id());
  assertNotEquals(edge1.id(), edge2.id());
}
 
Example 23
Project: hdt-gremlin   File: HDTGraph.java   View source code 5 votes vote down vote up
@Override
public Iterator<Edge> edges(Object... edgeIds) {
	if(edgeIds==null || edgeIds.length==0) {
		return new HDTEdgeIterable(this).iterator();
	}
	return Iter.map(Arrays.asList(edgeIds), a->getEdge(a));
}
 
Example 24
Project: bitsy   File: BitsyAutoReloadingEdge.java   View source code 5 votes vote down vote up
public Edge getBaseEdge() {
    if (((BitsyTransaction)edge.getTransaction()).isStopped()) {
        edge = (BitsyEdge)graph.edges(edge.id()).next();
    }
    
    return edge;
}
 
Example 25
Project: act-platform   File: FactEdgeTest.java   View source code 5 votes vote down vote up
@Test
public void testGetPropertyKeysOnEdge() {
  UUID factID = mockFact(null);
  Edge edge = new FactEdge(getActGraph(), factID, mockObject(), mockObject());

  // Test that the following properties exists on the edge.
  Map<String, Object> expected = MapUtils.map(
          T("factID", factID),
          T("value", "value"),
          T("inReferenceToID", UUID.fromString("00000000-0000-0000-0000-000000000001")),
          T("organizationID", UUID.fromString("00000000-0000-0000-0000-000000000002")),
          T("sourceID", UUID.fromString("00000000-0000-0000-0000-000000000003")),
          T("accessMode", AccessMode.Public),
          T("timestamp", 123456789L),
          T("lastSeenTimestamp", 987654321L)
  );

  Set<String> keys = edge.keys();
  Set<Property<Object>> properties = SetUtils.set(edge.properties());

  assertEquals(expected.size(), keys.size());
  assertEquals(expected.size(), properties.size());

  for (Map.Entry<String, Object> entry : expected.entrySet()) {
    assertTrue(keys.contains(entry.getKey()));

    Property<Object> property = edge.property(entry.getKey());
    assertEquals(entry.getValue(), property.value());
    assertEquals(StringFactory.propertyString(property), property.toString());
    assertSame(edge, property.element());
  }
}
 
Example 26
Project: act-platform   File: ElementFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void testCreateEdgesReturnsLoop() {
  ObjectFactBindingEntity inBinding = createInBinding(Direction.None);
  FactEntity.FactObjectBinding outBinding = new FactEntity.FactObjectBinding()
          .setObjectID(inBinding.getObjectID())
          .setDirection(inBinding.getDirection());
  mockObject(inBinding);
  mockFact(inBinding.getFactID(), outBinding);

  Edge edge = elementFactory.createEdges(inBinding).iterator().next();
  assertSame(edge.inVertex(), edge.outVertex());
}
 
Example 27
Project: bitsy   File: BitsyGraphIT.java   View source code 5 votes vote down vote up
private Edge getEdge(Graph graph, Object id) {
	Iterator<Edge> iter = graph.edges(id);
	if (iter.hasNext()) {
		return iter.next();
	} else {
		return null;
	}
}
 
Example 28
Project: act-platform   File: ElementFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void testCreateEdgesWithDirectionBiDirectional() {
  ObjectFactBindingEntity inBinding = createInBinding(Direction.BiDirectional);
  FactEntity.FactObjectBinding outBinding = createOutBinding(Direction.BiDirectional);

  Edge edge = mockAndRunCreateEdges(inBinding, outBinding);

  assertEquals(inBinding.getObjectID(), edge.inVertex().id());
  assertEquals(outBinding.getObjectID(), edge.outVertex().id());
}
 
Example 29
Project: act-platform   File: ElementFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void testCreateEdgesWithDirectionFactIsDestination() {
  ObjectFactBindingEntity inBinding = createInBinding(Direction.FactIsDestination);
  FactEntity.FactObjectBinding outBinding = createOutBinding(Direction.FactIsSource);

  Edge edge = mockAndRunCreateEdges(inBinding, outBinding);

  assertEquals(inBinding.getObjectID(), edge.inVertex().id());
  assertEquals(outBinding.getObjectID(), edge.outVertex().id());
}
 
Example 30
Project: act-platform   File: ElementFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void testCreateEdgesExecutedTwice() {
  ObjectFactBindingEntity inBinding = createInBinding(Direction.None);
  FactEntity.FactObjectBinding outBinding = createOutBinding(Direction.None);

  Edge first = mockAndRunCreateEdges(inBinding, outBinding);
  Edge second = mockAndRunCreateEdges(inBinding, outBinding);

  assertSame(first, second);
}
 
Example 31
Project: hdt-gremlin   File: EdgeToVertex.java   View source code 5 votes vote down vote up
@Override
public Vertex convert(Edge item) {
	Iterator<Vertex> vertices = item.vertices(direction);
	if(vertices.hasNext()) {
		return vertices.next();
	}
	return null;
}
 
Example 32
Project: act-platform   File: ElementFactoryTest.java   View source code 5 votes vote down vote up
private Edge mockAndRunCreateEdges(ObjectFactBindingEntity inBinding, FactEntity.FactObjectBinding outBinding) {
  mockObject(inBinding);
  mockObject(outBinding.getObjectID());
  mockFact(inBinding.getFactID(), outBinding);

  return elementFactory.createEdges(inBinding).iterator().next();
}
 
Example 33
Project: act-platform   File: ActGraphTest.java   View source code 5 votes vote down vote up
@Test
public void testFetchingEdgesWithId() {
  ObjectFactBindingEntity inBinding = mockFactWithObject();
  Set<Edge> expected = getActGraph().getElementFactory().createEdges(inBinding);
  Set<Edge> actual = SetUtils.set(getActGraph().edges(expected.iterator().next().id()));
  assertEquals(expected, actual);
}
 
Example 34
Project: act-platform   File: ActGraphTest.java   View source code 5 votes vote down vote up
@Test
public void testFetchingEdgesWithEdge() {
  ObjectFactBindingEntity binding = mockFactWithObject();
  Set<Edge> expected = getActGraph().getElementFactory().createEdges(binding);
  Set<Edge> actual = SetUtils.set(getActGraph().edges(expected.iterator().next()));
  assertEquals(expected, actual);
}
 
Example 35
Project: act-platform   File: ActGraphTest.java   View source code 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 36
Project: act-platform   File: ActGraphTest.java   View source code 5 votes vote down vote up
@Test
public void testIterateEdgesWithUuidIdSupportUsingReferenceEdge() {
  Edge edge1 = createEdge();
  Edge edge2 = getActGraph().edges(ReferenceFactory.detach(edge1)).next();
  assertEquals(edge1.id(), edge2.id());
  assertFalse(edge2 instanceof ReferenceEdge);
}
 
Example 37
Project: janusgraph_tutorial   File: ComputeWeightVertexProgram.java   View source code 5 votes vote down vote up
/**
 * Execute this marvelous code, going from the Content to Users.
 *
 * Internally uses the RecommendationForNewUser class to build the recommendation as we want, pretty and
 * simple.
 *
 * @param vertex
 * @param messenger
 * @param memory
 */
@Override
public void execute(Vertex vertex, Messenger<Tuple> messenger, Memory memory) {
  try {
    HadoopQueryRunner runner = new HadoopQueryRunner(g, vertex.value(Schema.USER_NAME));
    GraphTraversal<Vertex, Edge> t = g.V(vertex.id()).inE(Schema.FOLLOWS);

    while(t.hasNext()) {
      Edge followsEdge = t.next();

      long commonFollowedUsers = runner.countCommonFollowedUsers(followsEdge.outVertex());
      long postsPerDaySince = runner.countPostsPerDaySince(sevenDaysAgo);
      long weight = (3 * commonFollowedUsers + postsPerDaySince) / 4;
      if(min == -10 || min > weight) {
        min = (int) weight;
      }
      if(max < weight) {
        max = (int) weight;
      }
      count++;

      followsEdge.property(CreateWeightIndex.WEIGHT, weight);
    }
  } catch (Exception e){
    e.printStackTrace();
    LOGGER.error("while processing " + vertex.id() + ": " + e.getClass().toString() + "(" + e.getMessage() + ")");
    return;
  }
}
 
Example 38
Project: hdt-gremlin   File: HDTEdgeIterable.java   View source code 5 votes vote down vote up
@Override
public Iterator<Edge> iterator() {
	Iterator<TripleID> it = this.graph.getBaseGraph().getTriples().search(pattern);
	
	// Filter literals
	if(pattern.getObject()==0) {
		it = Iter.filter(it, new Filter<TripleID>() {
			@Override
			public boolean accept(TripleID triple) {
				return !graph.isLiteral(triple.getObject());
			}
		});
	}

	// Filter properties
	if(filter!=null) {
		it = Iter.filter(it, filter);
	}

	// Limit number of results
	if(limit!=Integer.MAX_VALUE && limit>0) {
		it = Iter.limit(it, limit);
	}
	
	// Convert to edges.
	return Iter.map(it, new TripleIDtoEdge(graph));
}
 
Example 39
Project: tinkergraph-gremlin   File: TinkerHelper.java   View source code 5 votes vote down vote up
protected static void addInEdge(final TinkerVertex vertex, final String label, final Edge edge) {
    if (null == vertex.inEdges) vertex.inEdges = new HashMap<>();
    Set<Edge> edges = vertex.inEdges.get(label);
    if (null == edges) {
        edges = new HashSet<>();
        vertex.inEdges.put(label, edges);
    }
    edges.add(edge);
}
 
Example 40
Project: tinkergraph-gremlin   File: TinkerEdge.java   View source code 5 votes vote down vote up
@Override
public <V> Property<V> property(final String key, final V value) {
    if (this.removed) throw elementAlreadyRemoved(Edge.class, id);
    ElementHelper.validateProperty(key, value);
    final Property oldProperty = super.property(key);
    final Property<V> newProperty = new TinkerProperty<>(this, key, value);
    if (null == this.properties) this.properties = new HashMap<>();
    this.properties.put(key, newProperty);
    TinkerHelper.autoUpdateIndex(this, key, value, oldProperty.isPresent() ? oldProperty.value() : null);
    return newProperty;

}