Java Code Examples for com.tinkerpop.blueprints.Edge

The following are top voted examples for showing how to use com.tinkerpop.blueprints.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: semtool   File: GsonWriterTest.java   View source code 6 votes vote down vote up
@Test
public void testGetGraphRelsOnly() {
	LoadingSheetData rels
			= LoadingSheetData.relsheet( "Human Being", "Car", "Purchased" );
	rels.addProperties( Arrays.asList( "Price", "Date" ) );
	ValueFactory vf = new ValueFactoryImpl();
	Map<String, Value> props = new HashMap<>();
	props.put( "Price", vf.createLiteral( "3000 USD" ) );
	rels.add( "Yuri", "Yugo", props );
	rels.add( "Yuri", "Pinto" );

	Graph g = GsonWriter.getGraph( data );
	int vsize = 0;
	int esize = 0;
	for ( Vertex v : g.getVertices() ) {
		vsize++;
	}
	for ( Edge e : g.getEdges() ) {
		esize++;
	}

	assertEquals( 3, vsize );
	assertEquals( 2, esize );
}
 
Example 2
Project: mesh   File: EdgeIndexPerformanceTest.java   View source code 6 votes vote down vote up
@Test
public void testEdgeIndexViaRootGetEdgesWithoutTarget() throws Exception {
	OrientGraph g = factory.getTx();
	try {
		long start = System.currentTimeMillis();
		for (int i = 0; i < nChecks; i++) {
			OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
			Iterable<Edge> edges = root.getEdges(Direction.OUT, "HAS_ITEM");
			boolean found = false;
			for (Edge edge : edges) {
				if (edge.getVertex(Direction.IN).equals(randomDocument)) {
					found = true;
					break;
				}
			}
			assertTrue(found);
		}
		long dur = System.currentTimeMillis() - start;
		System.out.println("[root.getEdges - iterating] Duration: " + dur);
		System.out.println("[root.getEdges - iterating] Duration per lookup: " + ((double) dur / (double) nChecks));
	} finally {
		g.shutdown();
	}
}
 
Example 3
Project: mesh   File: EdgeIndexPerformanceTest.java   View source code 6 votes vote down vote up
@Test
public void testEdgeIndexViaRootGetEdges() throws Exception {
	OrientGraph g = factory.getTx();
	try {
		long start = System.currentTimeMillis();
		for (int i = 0; i < nChecks; i++) {
			OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
			Iterable<Edge> edges = root.getEdges(randomDocument, Direction.OUT, "HAS_ITEM");
			assertTrue(edges.iterator().hasNext());
		}
		long dur = System.currentTimeMillis() - start;
		System.out.println("[root.getEdges] Duration: " + dur);
		System.out.println("[root.getEdges] Duration per lookup: " + ((double) dur / (double) nChecks));
	} finally {
		g.shutdown();
	}
}
 
Example 4
Project: mesh   File: RemoveBogusWebrootProperty.java   View source code 6 votes vote down vote up
private void migrateContainer(Vertex container) {

		boolean isPublished = false;
		Iterable<Edge> edges = container.getEdges(Direction.IN, "HAS_FIELD_CONTAINER");

		// Check whether the container is published
		for (Edge edge : edges) {
			String type = edge.getProperty("edgeType");
			if ("P".equals(type)) {
				isPublished = true;
			}
		}

		// The container is not published anywhere. Remove the bogus publish webroot info which otherwise causes publish webroot conflicts with new versions.
		if (!isPublished) {
			if (container.getProperty(WEBROOT_PUB) != null) {
				log.info("Found inconsistency on container {" + container.getProperty("uuid") + "}");
				container.removeProperty(WEBROOT_PUB);
				log.info("Inconsistency fixed");
			}
		}
	}
 
Example 5
Project: mesh   File: RootVertex.java   View source code 6 votes vote down vote up
/**
 * Find the element with the given uuid.
 * 
 * @param uuid
 *            Uuid of the element to be located
 * @return Found element or null if the element could not be located
 */
default public T findByUuid(String uuid) {
	FramedGraph graph = Tx.getActive().getGraph();
	// 1. Find the element with given uuid within the whole graph
	Iterator<Vertex> it = database().getVertices(getPersistanceClass(), new String[] { MeshVertex.UUID_KEY }, new String[] { uuid });
	if (it.hasNext()) {
		Vertex potentialElement = it.next();
		// 2. Use the edge index to determine whether the element is part of this root vertex
		Iterable<Edge> edges = graph.getEdges("e." + getRootLabel().toLowerCase() + "_inout", database().createComposedIndexKey(potentialElement
				.getId(), getId()));
		if (edges.iterator().hasNext()) {
			return graph.frameElementExplicit(potentialElement, getPersistanceClass());
		}
	}
	return null;
}
 
Example 6
Project: mesh   File: JobRootImpl.java   View source code 6 votes vote down vote up
/**
 * Find the element with the given uuid.
 * 
 * @param uuid
 *            Uuid of the element to be located
 * @return Found element or null if the element could not be located
 */
public Job findByUuid(String uuid) {
	FramedGraph graph = Tx.getActive().getGraph();
	// 1. Find the element with given uuid within the whole graph
	Iterator<Vertex> it = database().getVertices(MeshVertexImpl.class, new String[] { "uuid" }, new String[] { uuid });
	if (it.hasNext()) {
		Vertex potentialElement = it.next();
		// 2. Use the edge index to determine whether the element is part of this root vertex
		Iterable<Edge> edges = graph.getEdges("e." + getRootLabel().toLowerCase() + "_inout",
				database().createComposedIndexKey(potentialElement.getId(), getId()));
		if (edges.iterator().hasNext()) {
			// Don't frame explicitly since multiple types can be returned
			return graph.frameElement(potentialElement, getPersistanceClass());
		}
	}
	return null;
}
 
Example 7
Project: mesh   File: AbstractGenericFieldContainerVertex.java   View source code 6 votes vote down vote up
/**
 * Locate the field container using the provided information.
 * 
 * @param languageTag
 *            Language tag of the field container
 * @param releaseUuid
 *            Optional release to search within
 * @param type
 *            Optional type of the field container (published, draft)
 * @param classOfU
 * @return
 */
protected <U extends BasicFieldContainer> U getGraphFieldContainer(String languageTag, String releaseUuid, ContainerType type,
		Class<U> classOfU) {

	Database db = MeshInternal.get().database();
	FramedGraph graph = Tx.getActive().getGraph();
	Iterable<Edge> edges = graph.getEdges("e." + HAS_FIELD_CONTAINER.toLowerCase() + "_release_type_lang", db.createComposedIndexKey(getId(),
			releaseUuid, type.getCode(), languageTag));
	Iterator<Edge> it = edges.iterator();
	if (it.hasNext()) {
		Vertex in = it.next().getVertex(IN);
		return graph.frameElementExplicit(in, classOfU);
	} else {
		return null;
	}

}
 
Example 8
Project: mesh   File: BinaryRootImpl.java   View source code 6 votes vote down vote up
@Override
public Binary findByHash(String hash) {

	FramedGraph graph = Tx.getActive().getGraph();
	// 1. Find the element with given uuid within the whole graph
	Iterator<Vertex> it = database().getVertices(getPersistanceClass(), new String[] { Binary.SHA512SUM_KEY }, new String[] { hash });
	if (it.hasNext()) {
		Vertex potentialElement = it.next();
		// 2. Use the edge index to determine whether the element is part of this root vertex
		Iterable<Edge> edges = graph.getEdges("e." + getRootLabel().toLowerCase() + "_inout", database().createComposedIndexKey(potentialElement
				.getId(), getId()));
		if (edges.iterator().hasNext()) {
			return graph.frameElementExplicit(potentialElement, getPersistanceClass());
		}
	}
	return null;
	// TODO use index
	// return out(HAS_BINARY).has(Binary.SHA512SUM_KEY, hash).nextOrDefaultExplicit(BinaryImpl.class, null);
}
 
Example 9
Project: titan0.5.4-hbase1.1.1-custom   File: VerticesMapTest.java   View source code 6 votes vote down vote up
public void testVerticesWithPaths() throws Exception {
    Configuration config = new Configuration();
    config.setBoolean(Tokens.TITAN_HADOOP_PIPELINE_TRACK_PATHS, true);

    mapReduceDriver.withConfiguration(config);

    Map<Long, FaunusVertex> graph = runWithGraph(generateGraph(BaseTest.ExampleGraph.TINKERGRAPH, config), mapReduceDriver);

    assertEquals(graph.size(), 6);
    for (FaunusVertex vertex : graph.values()) {
        assertEquals(vertex.pathCount(), 1);
        assertEquals(vertex.getPaths().get(0).size(), 1);
        assertEquals(vertex.getPaths().get(0).get(0).getId(), vertex.getLongId());
        for (Edge edge : vertex.getEdges(Direction.BOTH)) {
            assertEquals(((StandardFaunusEdge) edge).pathCount(), 0);
        }
    }

    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, VerticesMap.Counters.EDGES_PROCESSED), 12);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, VerticesMap.Counters.VERTICES_PROCESSED), 6);

    identicalStructure(graph, ExampleGraph.TINKERGRAPH);
}
 
Example 10
Project: HBaseTinkerGraph   File: HbaseGraph.java   View source code 6 votes vote down vote up
public Iterable<Edge> getEdges(String key, Object value) {
	try {
		Scan scan = new Scan(Bytes.toBytes(this.graphName+"_"+key), this.getEndKey(Bytes.toBytes(this.graphName+"_"+key)));
		scan.addFamily(Bytes.toBytes("edge"));
		scan.setFilter(new ValueFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes(String.valueOf(value)))));

		return new HbaseIterable<Edge>(scan, HbaseGraphUtils.PROPERTIESTABLENAME, hbaseConf) {
			@Override
			public Edge next(Result result) {			
				for(Cell cell : result.listCells()) {
					String id = Bytes.toString(CellUtil.cloneQualifier(cell));
					return new HbaseEdge(id, graphName, hbaseConf);
				}
				return null;
			}
		};		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	}
}
 
Example 11
Project: titan0.5.4-hbase1.1.1-custom   File: BaseTestNG.java   View source code 6 votes vote down vote up
public static Map<Long, FaunusVertex> startPath(final Map<Long, FaunusVertex> graph, final Class<? extends Element> klass, final long... ids) {
    if (ids.length == 0) {
        for (FaunusVertex vertex : graph.values()) {
            if (klass.equals(Vertex.class)) {
                vertex.startPath();
            } else if (klass.equals(Edge.class)) {
                for (Edge edge : vertex.getEdges(Direction.BOTH)) {
                    ((StandardFaunusEdge) edge).startPath();
                }
            } else {
                throw new IllegalArgumentException("It can only be either edge or vertex, not both");
            }
        }
    } else {
        if (klass.equals(Edge.class))
            throw new IllegalArgumentException("Currently no support for starting a path on a particular set of edges (only all edges)");

        for (long id : ids) {
            if (graph.get(id).hasPaths())
                graph.get(id).incrPath(1);
            else
                graph.get(id).startPath();
        }
    }
    return graph;
}
 
Example 12
Project: titan0.5.4-hbase1.1.1-custom   File: EdgeCopyMapReduce.java   View source code 6 votes vote down vote up
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, LongWritable, Holder<FaunusVertex>>.Context context) throws IOException, InterruptedException {
    long edgesInverted = 0;

    for (final Edge edge : value.getEdges(this.direction)) {
        final long id = (Long) edge.getVertex(this.direction.opposite()).getId();
        final FaunusVertex shellVertex = new FaunusVertex(faunusConf, id);
        this.longWritable.set(id);
        shellVertex.addEdge(this.direction.opposite(), (StandardFaunusEdge) edge);
        context.write(this.longWritable, this.vertexHolder.set('s', shellVertex));
        edgesInverted++;
    }
    this.longWritable.set(value.getLongId());
    context.write(this.longWritable, this.vertexHolder.set('r', value));
    DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_COPIED, edgesInverted);
}
 
Example 13
Project: bjoern   File: BjoernEdgeIterable.java   View source code 6 votes vote down vote up
@Override
public Iterator<Edge> iterator()
{
	return new Iterator<Edge>()
	{
		final Iterator<Edge> baseIterable = iterable.iterator();

		@Override
		public boolean hasNext()
		{
			return baseIterable.hasNext();
		}

		@Override
		public Edge next()
		{
			return new BjoernEdge(baseIterable.next());
		}
	};
}
 
Example 14
Project: bjoern   File: DataDependencePlugin.java   View source code 6 votes vote down vote up
public static Set<ReachingDefinitionAnalyser.Definition> killedDefinitions(
		final Vertex vertex) {
	Set<ReachingDefinitionAnalyser.Definition> killSet = new HashSet<>();
	GremlinPipeline<Vertex, Edge> pipe = new GremlinPipeline<>();
	pipe.start(vertex)
	    .out("WRITE")
	    .out("BELONGS_TO")
	    .in("BELONGS_TO")
	    .inE("WRITE");
	for (Edge writeEdge : pipe) {
		Vertex genVertex = writeEdge.getVertex(Direction.OUT);
		Vertex aloc = writeEdge.getVertex(Direction.IN);
		GremlinPipeline<Vertex, Object> pipe2 = new
				GremlinPipeline<>();
		pipe2.start(aloc)
		     .out("BELONGS_TO")
		     .in("BELONGS_TO")
		     .property("name");
		for (Object identifier : pipe2) {
			killSet.add(new ReachingDefinitionAnalyser.Definition(
					genVertex, identifier));
		}
	}
	return killSet;
}
 
Example 15
Project: bjoern   File: FunctionExportPlugin.java   View source code 6 votes vote down vote up
private static void copyEdge(Graph graph, Edge edge)
{
	Object id = edge.getId();
	if (graph.getEdge(id) != null)
	{
		return;
	}
	Vertex src = graph.getVertex(edge.getVertex(Direction.OUT).getId());
	Vertex dst = graph.getVertex(edge.getVertex(Direction.IN).getId());
	if (src != null && dst != null)
	{
		Edge e = GraphHelper.addEdge(graph, id, src, dst, edge.getLabel());
		if (e != null)
		{
			ElementHelper.copyProperties(edge, e);
		}
	}
}
 
Example 16
Project: bjoern   File: DotWriter.java   View source code 6 votes vote down vote up
public void outputGraph(
		final OutputStream dotOutputStream) throws IOException
{

	writer = new BufferedWriter(new OutputStreamWriter(dotOutputStream));

	writer.write(DotTokens.DIGRAPH);
	writer.write(" {");
	writer.write(DotTokens.NEWLINE);

	for (Vertex vertex : graph.getVertices())
	{
		writeVertex(vertex);
	}

	for (Edge edge : graph.getEdges())
	{
		writeEdge(edge);
	}

	writer.write("}");
	writer.write(DotTokens.NEWLINE);
	writer.flush();
}
 
Example 17
Project: poi-visio-graph   File: VisioPageParser.java   View source code 6 votes vote down vote up
protected void createEdge(ShapeData sd1, ShapeData sd2, String edgeType, Double x, Double y) {

	// note: visio doesn't always support direction, and neither do we. So, to
	//       save time, and make sure we don't accidentally create duplicate 
	//       edges, we sort by id
	
	ShapeData from = sd1;
	ShapeData to = sd2;
	
	if (sd1.shapeId > sd2.shapeId) {
		from = sd2;
		to = sd1;
	}
	
	String eId = getConnId(from, to);
	
	Edge edge = graph.getEdge(eId);
	if (edge == null) {
		edge = graph.addEdge(eId, from.vertex, to.vertex, edgeType);
		
		if (x != null && y != null) {
			edge.setProperty("x", x);
			edge.setProperty("y", y);
		}
	}
}
 
Example 18
Project: titan0.5.4-hbase1.1.1-custom   File: VerticesMapTest.java   View source code 6 votes vote down vote up
public void testVerticesWithNoPaths() throws Exception {
    Configuration config = new Configuration();
    mapReduceDriver.withConfiguration(config);

    Map<Long, FaunusVertex> graph = runWithGraph(generateGraph(BaseTest.ExampleGraph.TINKERGRAPH, config), mapReduceDriver);

    assertEquals(graph.size(), 6);
    for (FaunusVertex vertex : graph.values()) {
        assertEquals(vertex.pathCount(), 1);
        for (Edge edge : vertex.getEdges(Direction.BOTH)) {
            assertEquals(((StandardFaunusEdge) edge).pathCount(), 0);
        }

        try {
            vertex.getPaths();
            assertTrue(false);
        } catch (IllegalStateException e) {
            assertTrue(true);
        }
    }

    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, VerticesMap.Counters.EDGES_PROCESSED), 12);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, VerticesMap.Counters.VERTICES_PROCESSED), 6);

    identicalStructure(graph, ExampleGraph.TINKERGRAPH);
}
 
Example 19
Project: hybridbpm   File: DocumentAPI.java   View source code 6 votes vote down vote up
public Map<Document, List<Permission.PERMISSION>> getMyDocuments(String parentId) {
    String documentRequest = parentId != null
            ? "SELECT FROM Document WHERE @rid IN "
            + "(SELECT in FROM PERMISSION WHERE [email protected] = 'Document' AND permissions IN ('VIEW') "
            + "AND out in (SELECT FROM Role WHERE @rid IN (SELECT out('UserGroup').in('RoleGroup') FROM User WHERE @rid = " + user.getId() + "))) "
            + " AND parent = " + parentId
            : "SELECT FROM Document WHERE @rid IN "
            + "(SELECT in FROM PERMISSION WHERE [email protected] = 'Document' AND permissions IN ('VIEW') "
            + "AND out in (SELECT FROM Role WHERE @rid IN (SELECT out('UserGroup').in('RoleGroup') FROM User WHERE @rid = " + user.getId() + ")))"
             + " AND parent IS NULL ";
    try (OObjectDatabaseTx database = getOObjectDatabaseTx()) {
        List<Document> documents = database.query(new OSQLSynchQuery<Document>(documentRequest));
        documents = detachList(documents);
        Map<Document, List<Permission.PERMISSION>> result = new HashMap<>(documents.size());
        for (Document doc : documents) {
            Edge edge = getOrientGraph().getVertex(doc.getId()).getEdges(Direction.IN, "Permission").iterator().next();
            Permission p = getOObjectDatabaseTx().load(new ORecordId(edge.getId().toString()));
            result.put(doc, p.getPermissions());
        }
        return result;
    }
}
 
Example 20
Project: titan0.5.4-hbase1.1.1-custom   File: CommitEdgesMapTest.java   View source code 6 votes vote down vote up
public void testDropAllEdges() throws Exception {
    Configuration config = CommitEdgesMap.createConfiguration(Tokens.Action.DROP);
    mapReduceDriver.withConfiguration(config);

    Map<Long, FaunusVertex> graph = runWithGraph(startPath(generateGraph(BaseTest.ExampleGraph.TINKERGRAPH, config), Edge.class), mapReduceDriver);
    assertEquals(graph.size(), 6);
    assertEquals(graph.get(1l).pathCount(), 0);
    assertEquals(graph.get(2l).pathCount(), 0);
    assertEquals(graph.get(3l).pathCount(), 0);
    assertEquals(graph.get(4l).pathCount(), 0);
    assertEquals(graph.get(5l).pathCount(), 0);
    assertEquals(graph.get(6l).pathCount(), 0);

    for (FaunusVertex vertex : graph.values()) {
        assertFalse(vertex.getEdges(Direction.BOTH).iterator().hasNext());
    }

    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, CommitEdgesMap.Counters.OUT_EDGES_DROPPED), 6);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, CommitEdgesMap.Counters.OUT_EDGES_KEPT), 0);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, CommitEdgesMap.Counters.IN_EDGES_DROPPED), 6);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, CommitEdgesMap.Counters.IN_EDGES_KEPT), 0);
}
 
Example 21
Project: titan0.5.4-hbase1.1.1-custom   File: IntervalFilterMap.java   View source code 6 votes vote down vote up
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
    if (this.isVertex) {
        if (value.hasPaths() && !(this.startChecker.isLegal(value) && this.endChecker.isLegal(value))) {
            value.clearPaths();
            DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_FILTERED, 1L);
        }
    } else {
        long counter = 0;
        for (final Edge e : value.getEdges(Direction.BOTH)) {
            final StandardFaunusEdge edge = (StandardFaunusEdge) e;
            if (edge.hasPaths() && !(this.startChecker.isLegal(edge) && this.endChecker.isLegal(edge))) {
                edge.clearPaths();
                counter++;
            }
        }
        DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_FILTERED, counter);
    }
    context.write(NullWritable.get(), value);
}
 
Example 22
Project: incubator-atlas   File: AtlasEntityTagQuery.java   View source code 6 votes vote down vote up
@Override
protected Pipe getQueryPipe() {
    GremlinPipeline p;
    if (guid.equals("*")) {
        p = new GremlinPipeline().has(Constants.ENTITY_TEXT_PROPERTY_KEY).
                hasNot(Constants.ENTITY_TYPE_PROPERTY_KEY, "Taxonomy").outE();
    } else {
        p = new GremlinPipeline().has(Constants.GUID_PROPERTY_KEY, guid).outE();
    }
    //todo: this is basically the same pipeline used in TagRelation.asPipe()
    p.add(new FilterFunctionPipe<>(new PipeFunction<Edge, Boolean>() {
        @Override
        public Boolean compute(Edge edge) {
            String type = edge.getVertex(Direction.OUT).getProperty(Constants.ENTITY_TYPE_PROPERTY_KEY);
            VertexWrapper v = new TermVertexWrapper(edge.getVertex(Direction.IN));
            return edge.getLabel().startsWith(type) && v.getPropertyKeys().contains("available_as_tag");
        }
    }));

    return p.inV();
}
 
Example 23
Project: titan0.5.4-hbase1.1.1-custom   File: EdgesVerticesMapTest.java   View source code 6 votes vote down vote up
public void testOutVertices() throws Exception {
    Configuration config = EdgesVerticesMap.createConfiguration(Direction.OUT);

    mapReduceDriver.withConfiguration(config);

    Map<Long, FaunusVertex> graph = runWithGraph(startPath(generateGraph(BaseTest.ExampleGraph.TINKERGRAPH, config), Edge.class), mapReduceDriver);

    assertEquals(graph.size(), 6);
    assertEquals(graph.get(1l).pathCount(), 3);
    assertEquals(graph.get(2l).pathCount(), 0);
    assertEquals(graph.get(3l).pathCount(), 0);
    assertEquals(graph.get(4l).pathCount(), 2);
    assertEquals(graph.get(5l).pathCount(), 0);
    assertEquals(graph.get(6l).pathCount(), 1);


    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, EdgesVerticesMap.Counters.OUT_EDGES_PROCESSED), 6);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, EdgesVerticesMap.Counters.IN_EDGES_PROCESSED), 0);

    noPaths(graph, Edge.class);
    identicalStructure(graph, BaseTest.ExampleGraph.TINKERGRAPH);
}
 
Example 24
Project: titan0.5.4-hbase1.1.1-custom   File: VertexQueryFilter.java   View source code 6 votes vote down vote up
public void defaultFilter(final FaunusVertex vertex) {
    if (!this.doesFilter) return;
    vertex.removeEdges(Tokens.Action.KEEP, this.direction, this.labels);
    Iterator<Edge> itty;
    Edge edge;
    if (this.hasContainers.size() > 0) {
        itty = vertex.getEdges(this.direction).iterator();
        while (itty.hasNext()) {
            edge = itty.next();
            for (final HasContainer hasContainer : this.hasContainers) {
                if (!hasContainer.isLegal(edge))
                    itty.remove();
            }
        }
    }
    if (this.limit != Long.MAX_VALUE) {
        itty = vertex.getEdges(this.direction).iterator();
        long counter = 0;
        while (itty.hasNext()) {
            itty.next();
            if (++counter > this.limit)
                itty.remove();
        }
    }
}
 
Example 25
Project: titan0.5.4-hbase1.1.1-custom   File: GroupCountMapReduceTest.java   View source code 6 votes vote down vote up
public void testEdgeDistribution() throws Exception {
    Configuration config = GroupCountMapReduce.createConfiguration(Edge.class, null, null);
    this.mapReduceDriver.withConfiguration(config);
    final Map<Long, FaunusVertex> graph = generateGraph(ExampleGraph.GRAPH_OF_THE_GODS, config);
    final List<Pair<Text, LongWritable>> results = runWithGraphNoIndex(startPath(graph, Edge.class), this.mapReduceDriver);
    //System.out.println(results);
    assertEquals(results.size(), 17);
    for (final Pair<Text, LongWritable> result : results) {
        assertTrue(result.getFirst().toString().startsWith("e["));
        assertEquals(result.getSecond().get(), 1);
    }

    identicalStructure(graph, ExampleGraph.GRAPH_OF_THE_GODS);
    assertEquals(0, DEFAULT_COMPAT.getCounter(mapReduceDriver, GroupCountMapReduce.Counters.VERTICES_PROCESSED));
    assertEquals(17, DEFAULT_COMPAT.getCounter(mapReduceDriver, GroupCountMapReduce.Counters.OUT_EDGES_PROCESSED));

}
 
Example 26
Project: jarvisCli   File: OSQLFunctionDijkstraWithWeightMax.java   View source code 6 votes vote down vote up
protected float getDistance(final OrientVertex node, final OrientVertex target) {
  final Iterator<Edge> edges = node.getEdges(target, paramDirection).iterator();
  if (edges.hasNext()) {
    final Edge e = edges.next();
    if (e != null && e.getLabel().equals("Frameshift") 
            && e.getProperty(paramWeightFieldName) != null 
            && ((double)e.getProperty(paramWeightFieldName) <=  paramWeightLimit)) {
 
      final Object fieldValue = e.getProperty(paramWeightFieldName);
      if (fieldValue != null) {
        if (fieldValue instanceof Float) {
          return (Float) fieldValue;
        } else if (fieldValue instanceof Number) {
          return ((Number) fieldValue).floatValue();
        }
      }
    }
    return Float.MAX_VALUE;
  }
  return Float.MAX_VALUE;
}
 
Example 27
Project: titan0.5.4-hbase1.1.1-custom   File: GraphGenerator.java   View source code 6 votes vote down vote up
/**
 * As in {@code vertexAnnotator} above, choose a sequence of
 * contiguously-stored property names with a random offset and length.
 * However, omit the initial {@link Schema#getEdgeLabels()} property
 * keys from consideration. These keys are used by sort keys.
 * <p>
 * In addition to the preceding, lookup the sort key for the edge's
 * label and set that to a randomly chosen value.
 */
@Override
public void annotate(Edge edge) {
    // Set sort key edge property
    edge.setProperty(schema.getSortKeyForLabel(edge.getLabel()),
            random.nextInt(schema.getMaxEdgePropVal()));

    // Set additional (non-sort-key) edge properties
    if (0 >= schema.getEdgePropKeys() - schema.getEdgeLabels())
        return;

    int eligible = schema.getEdgePropKeys() - schema.getEdgeLabels();
    Preconditions.checkArgument(0 < eligible);
    int count = random.nextInt(eligible);
    int offset = random.nextInt(eligible);
    int length = schema.getEdgePropKeys();
    Preconditions.checkArgument(length == eligible + schema.getEdgeLabels());
    Preconditions.checkArgument(length >= count + schema.getEdgeLabels());

    for (int i = 0; i < count; i++) {
        String key = schema.getEdgePropertyName(schema.getEdgeLabels() + ((offset + i) % eligible));
        edge.setProperty(key, random.nextInt(schema.getMaxEdgePropVal()));
    }
}
 
Example 28
Project: jarvisCli   File: StationService.java   View source code 6 votes vote down vote up
public int clearStationOfExchangesOrientDb(Station station) {
    int edgesRemoved = 0;
    OrientGraph graph = null;
    try {
        graph = orientDbService.getFactory().getTx();
        OrientVertex vertexStation = (OrientVertex) graph.getVertexByKey("Station.name", station.getName());
        for (Edge exchange: vertexStation.getEdges(Direction.OUT, "Exchange")) {
            exchange.remove();
            edgesRemoved++;
        };
        
    } catch (Exception e) {
        graph.rollback();
    }
    return edgesRemoved;
}
 
Example 29
Project: jarvisCli   File: StationService.java   View source code 6 votes vote down vote up
public Station vertexToStation(Vertex stationVertex) {
	Station out = new Station();
    out.setName(stationVertex.getProperty("name"));
    
    Boolean blackMarket = stationVertex.getProperty("blackMarket") != null ? stationVertex.getProperty("blackMarket") : Boolean.FALSE;
    out.setBlackMarket(blackMarket);
    
    Vertex systemVertex = getSystemVertexForStationVertex(stationVertex);
    out.setSystem(systemVertex.getProperty("name"));
    
    for (Edge exchange: stationVertex.getEdges(Direction.OUT, "Exchange")) {
        out.setDate(exchange.getProperty("date"));
        break;
    }
    
    return out;
}
 
Example 30
Project: titan0.5.4-hbase1.1.1-custom   File: ValueGroupCountMapReduceTest.java   View source code 6 votes vote down vote up
public void testEdgeLabelDistribution2() throws Exception {
    Configuration config = ValueGroupCountMapReduce.createConfiguration(Edge.class, "label", Text.class);
    this.mapReduceDriver.withConfiguration(config);
    final List<Pair<Text, LongWritable>> results = runWithGraphNoIndex(startPath(generateGraph(ExampleGraph.GRAPH_OF_THE_GODS, config), Edge.class), this.mapReduceDriver);
    assertEquals(results.size(), 6);
    for (final Pair<Text, LongWritable> result : results) {
        if (result.getFirst().toString().equals("lives")) {
            assertEquals(result.getSecond().get(), 4l);
        } else if (result.getFirst().toString().equals("battled")) {
            assertEquals(result.getSecond().get(), 3l);
        } else if (result.getFirst().toString().equals("brother")) {
            assertEquals(result.getSecond().get(), 6l);
        } else if (result.getFirst().toString().equals("pet")) {
            assertEquals(result.getSecond().get(), 1l);
        } else if (result.getFirst().toString().equals("mother")) {
            assertEquals(result.getSecond().get(), 1l);
        } else if (result.getFirst().toString().equals("father")) {
            assertEquals(result.getSecond().get(), 2l);
        } else {
            assertTrue(false);
        }
    }

    assertEquals(17, DEFAULT_COMPAT.getCounter(mapReduceDriver, ValueGroupCountMapReduce.Counters.PROPERTIES_COUNTED));
}
 
Example 31
Project: titan0.5.4-hbase1.1.1-custom   File: PropertyFilterMap.java   View source code 6 votes vote down vote up
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {

    if (this.isVertex) {
        if (value.hasPaths() && !this.elementChecker.isLegal(value)) {
            value.clearPaths();
            DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_FILTERED, 1L);
        }
    } else {
        long edgesFiltered = 0;
        for (Edge e : value.getEdges(Direction.BOTH)) {
            final StandardFaunusEdge edge = (StandardFaunusEdge) e;
            if (edge.hasPaths() && !this.elementChecker.isLegal(edge)) {
                edge.clearPaths();
                edgesFiltered++;
            }
        }
        DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_FILTERED, edgesFiltered);
    }

    context.write(NullWritable.get(), value);
}
 
Example 32
Project: titan0.5.4-hbase1.1.1-custom   File: IdentityMapTest.java   View source code 6 votes vote down vote up
public void testIdentityNoPaths() throws Exception {
    mapReduceDriver.withConfiguration(new Configuration());

    Map<Long, FaunusVertex> graph = runWithGraph(generateGraph(BaseTest.ExampleGraph.TINKERGRAPH, new Configuration()), mapReduceDriver);

    assertEquals(graph.size(), 6);
    for (FaunusVertex vertex : graph.values()) {
        assertEquals(vertex.pathCount(), 0);
        assertFalse(vertex.hasPaths());
        for (Edge edge : vertex.getEdges(Direction.BOTH)) {
            assertEquals(((StandardFaunusEdge) edge).pathCount(), 0);
            assertFalse(((StandardFaunusEdge) edge).hasPaths());
        }
    }

    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, IdentityMap.Counters.VERTEX_COUNT), 6);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, IdentityMap.Counters.OUT_EDGE_COUNT), 6);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, IdentityMap.Counters.IN_EDGE_COUNT), 6);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, IdentityMap.Counters.VERTEX_PROPERTY_COUNT), 12);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, IdentityMap.Counters.OUT_EDGE_PROPERTY_COUNT), 6);
    assertEquals(DEFAULT_COMPAT.getCounter(mapReduceDriver, IdentityMap.Counters.IN_EDGE_PROPERTY_COUNT), 6);

    identicalStructure(graph, BaseTest.ExampleGraph.TINKERGRAPH);
}
 
Example 33
Project: odbogm   File: VertexUtils.java   View source code 5 votes vote down vote up
/**
 * Check if two vertex are conected
 *
 * @param v1 first vertex
 * @param v2 second vertex
 * @param edgeLabel etiqueta del edge
 * @return true if any conection exist
 */
public static boolean areConected(OrientVertex v1, OrientVertex v2, String edgeLabel) {
    boolean connected = false;
    if ((v1 != null)&&(v2 != null)) {
        Iterable<Edge> result = v1.getEdges(v2, Direction.BOTH, edgeLabel==null?"E":edgeLabel);
        for (Edge e : result) {
            connected = true;
            break;
        }
    }
    return connected;
}
 
Example 34
Project: odbogm   File: VertexUtils.java   View source code 5 votes vote down vote up
/**
 * Check if v1 is conected to (out) v2
 *
 * @param v1 source vertex
 * @param v2 target vertex
 * @param edgeLabel edge label to test. Null to test any label.
 * @return true if a conection exist
 */
public static boolean isConectedTo(OrientVertex v1, OrientVertex v2, String edgeLabel) {
    boolean connected = false;
    LOGGER.log(Level.FINER, "Verificando edges entre "+v1.getId()+" y "+v2.getId()+ " a través de la realción "+edgeLabel);
    if ((v1 != null)&&(v2 != null)) {
        Iterable<Edge> result = v1.getEdges(v2, Direction.OUT, edgeLabel==null?"E":edgeLabel);
        for (Edge e : result) {
            LOGGER.log(Level.FINER, "Conectados por el edge: "+e.getId());
            connected = true;
            break;
        }
    }
    return connected;
}
 
Example 35
Project: semtool   File: GsonWriterTest.java   View source code 5 votes vote down vote up
@Test
public void testGetGraph1() {
	Graph g = GsonWriter.getGraph( data );
	int vsize = 0;
	int esize = 0;
	for ( Vertex v : g.getVertices() ) {
		vsize++;
	}
	for ( Edge e : g.getEdges() ) {
		esize++;
	}

	assertEquals( 3, vsize );
	assertEquals( 2, esize );
}
 
Example 36
Project: wildfly-swarm   File: TestPeopleDao.java   View source code 5 votes vote down vote up
public List<Edge> getFriends() {
    List<Edge> edges = new LinkedList<>();
    OrientGraph database = new OrientGraph(databasePool);
    try {
        database.getEdges().forEach(edges::add);
    } finally {
        database.shutdown();
    }

    return edges;
}
 
Example 37
Project: wildfly-swarm   File: OrientDBArquillianTest.java   View source code 5 votes vote down vote up
@Test
public void shouldAddAFriendshipToTheGraph() {
    String firstName = "test-name-" + LocalTime.now();
    String secondName = "test-name-" + LocalTime.now();
    OrientEdge edge = statefulTestBean.addFriend(firstName, secondName);
    assertEquals(firstName, edge.getVertex(Direction.OUT).getProperty("name"));
    assertEquals(secondName, edge.getVertex(Direction.IN).getProperty("name"));
    assertEquals("knows", edge.getLabel());

    List<Edge> edges = statefulTestBean.getFriends();
    assertEquals(1, edges.size());
    assertEquals(edge, edges.get(0));
}
 
Example 38
Project: mesh   File: EdgeIndexPerformanceTest.java   View source code 5 votes vote down vote up
@Test
public void testEdgeIndexViaGraphGetEdges() throws Exception {
	OrientGraph g = factory.getTx();
	try {
		for (OIndex<?> index : g.getRawGraph().getMetadata().getIndexManager().getIndexes()) {

			System.out.println(index.getName() + " size: " + index.getSize());
		}
		// OIndex<?> index = g.getRawGraph().getMetadata().getIndexManager().getIndex("edge.has_item");
		// assertNotNull("Index could not be found", index);
	} finally {
		g.shutdown();
	}

	double total = 0;
	int nRuns = 20;
	for (int e = 0; e < nRuns; e++) {
		g = factory.getTx();
		try {
			long start = System.currentTimeMillis();
			for (int i = 0; i < nChecks; i++) {
				OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
				Iterable<Edge> edges = g.getEdges("e.has_item", new OCompositeKey(root.getId(), randomDocument.getId()));
				assertTrue(edges.iterator().hasNext());
			}
			long dur = System.currentTimeMillis() - start;
			System.out.println("[graph.getEdges] Duration: " + dur);
			double perCheck = ((double) dur / (double) nChecks);
			total += perCheck;
			System.out.println("[graph.getEdges] Duration per lookup: " + perCheck);
		} finally {
			g.shutdown();
		}
	}
	System.out.println("Average: " + (total / (double) nRuns));
}
 
Example 39
Project: mesh   File: BinaryStorageMigration.java   View source code 5 votes vote down vote up
private Edge createNewFieldEdge(Vertex container, Vertex binary, String fileName, String contentType, String dominantColor, String fieldKey) {
	Edge edge = getGraph().addEdge("class:BinaryGraphFieldImpl", container, binary, "HAS_FIELD");
	edge.setProperty("ferma_type", "BinaryGraphFieldImpl");
	edge.setProperty("uuid", randomUUID());
	edge.setProperty(BINARY_FILENAME_PROPERTY_KEY, fileName);
	edge.setProperty(BINARY_CONTENT_TYPE_PROPERTY_KEY, contentType);
	if (dominantColor != null) {
		edge.setProperty(BINARY_IMAGE_DOMINANT_COLOR_PROPERTY_KEY, dominantColor);
	}
	edge.setProperty(FIELD_KEY_PROPERTY_KEY, fieldKey);
	return null;
}
 
Example 40
Project: mesh   File: ChangeAddVersioning.java   View source code 5 votes vote down vote up
/**
 * Migrate the basenode and create a new NodeGraphFieldContainer for it.
 * 
 * @param baseNode
 * @param admin
 */
private void migrateBaseNode(Vertex baseNode, Vertex admin) {

	log.info("Migrating basenode {" + baseNode.getProperty("uuid") + "}");
	Vertex schemaContainer = baseNode.getVertices(Direction.OUT, "HAS_SCHEMA_CONTAINER").iterator().next();
	Vertex schemaVersion = schemaContainer.getVertices(Direction.OUT, "HAS_LATEST_VERSION").iterator().next();

	Vertex english = findEnglish();
	Iterator<Edge> it = baseNode.getEdges(Direction.OUT, "HAS_FIELD_CONTAINER").iterator();

	// The base node has no field containers. Lets create the default one
	if (!it.hasNext()) {
		Vertex container = getGraph().addVertex("class:NodeGraphFieldContainerImpl");
		container.setProperty("ferma_type", "NodeGraphFieldContainerImpl");
		container.setProperty("uuid", randomUUID());

		// Fields
		container.setProperty("name-field", "name");
		container.setProperty("name-string", "");

		// field container edge which will later be migrated
		Edge edge = baseNode.addEdge("HAS_FIELD_CONTAINER", container);
		edge.setProperty("ferma_type", "GraphFieldContainerEdgeImpl");
		edge.setProperty("languageTag", "en");
		container.addEdge("HAS_SCHEMA_CONTAINER_VERSION", schemaVersion);
		container.addEdge("HAS_LANGUAGE", english);
	}

}