com.tinkerpop.blueprints.Vertex Java Examples

The following examples show how to use com.tinkerpop.blueprints.Vertex. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IncidenceAnnotationHandler.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
public Object processVertex(final Incidence incidence, final Method method, final Object[] arguments, final FramedGraph framedGraph, final Vertex element) {
    if (ClassUtilities.isGetMethod(method)) {
        return new FramedEdgeIterable(framedGraph, element.getEdges(incidence.direction(), incidence.label()), incidence.direction(), ClassUtilities.getGenericClass(method));
    } else if (ClassUtilities.isAddMethod(method)) {
        
        switch(incidence.direction()) {
        case OUT:
            return framedGraph.addEdge(null, element, ((VertexFrame) arguments[0]).asVertex(), incidence.label(), Direction.OUT, method.getReturnType());
        case IN:
            return framedGraph.addEdge(null, ((VertexFrame) arguments[0]).asVertex(), element, incidence.label(), Direction.IN, method.getReturnType());
        case BOTH:
            throw new UnsupportedOperationException("Direction.BOTH it not supported on 'add' or 'set' methods");
        }
            
    } else if (ClassUtilities.isRemoveMethod(method)) {
        framedGraph.removeEdge(((EdgeFrame) arguments[0]).asEdge());
        return null;
    }

    return null;
}
 
Example #2
Source File: AutoIndexTest.java    From AccumuloGraph with Apache License 2.0 6 votes vote down vote up
@Test
public void testEdgeNoAutoIndex() throws Exception {
  AccumuloGraph graph = (AccumuloGraph) GraphFactory.open(AccumuloGraphTestUtils
      .generateGraphConfig("EdgeNoAutoIndexTest").getConfiguration());
  String id1 = "A";
  String id2 = "B";
  String eid = "X";
  String key = "name";
  String value = "bananaman";

  Vertex v1 = graph.addVertex(id1);
  Vertex v2 = graph.addVertex(id2);
  Edge e = graph.addEdge(eid, v1, v2, "edge");
  e.setProperty(key, value);

  Iterable<Element> elements = graph.getGlobals()
      .getEdgeKeyIndexWrapper().readElementsFromIndex(key, value);
  assertEquals(0, count(elements));
}
 
Example #3
Source File: DotWriter.java    From bjoern with GNU General Public License v3.0 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 #4
Source File: AbstractUserRule.java    From light with Apache License 2.0 6 votes vote down vote up
boolean checkRefreshToken(Vertex credential, String clientId, String refreshToken) throws Exception {
    boolean result = false;
    if(credential != null && refreshToken != null) {
        Map clientRefreshTokens = credential.getProperty("clientRefreshTokens");
        if(clientRefreshTokens != null) {
            List<String> refreshTokens = (List)clientRefreshTokens.get(clientId);
            if(refreshTokens != null) {
                String hashedRefreshToken = HashUtil.md5(refreshToken);
                for(String token: refreshTokens) {
                    if(hashedRefreshToken.equals(token)) {
                        result = true;
                        break;
                    }
                }
            }
        } else {
            logger.error("There is no refresh tokens");
        }
    }
    return result;
}
 
Example #5
Source File: AbstractPaymentRule.java    From light with Apache License 2.0 6 votes vote down vote up
/**
 * To save the customer transaction into database.
 *
 * @param data
 * @throws Exception
 */
protected void addSubscription(Map<String, Object> data) throws Exception {
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        Vertex user = graph.getVertexByKey("User.userId", data.remove("createUserId"));
        Vertex order = graph.getVertexByKey("Order.orderId", data.get("orderId"));
        if(order != null) {
            order.setProperty("paymentStatus", 1);  // update payment status to paid.
            List<Map<String, Object>> subscriptions = (List<Map<String, Object>>)data.get("subscriptions");
            order.setProperty("subscriptions", subscriptions);
            //order.setProperty
        }
        user.addEdge("Update", order);
        graph.commit();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example #6
Source File: OrientGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 6 votes vote down vote up
@Override
public Set<Integer> getCommunitiesConnectedToNodeCommunities(int nodeCommunities)
{
    Set<Integer> communities = new HashSet<Integer>();
    Iterable<Vertex> vertices = graph.getVertices(NODE_COMMUNITY, nodeCommunities);
    for (Vertex vertex : vertices)
    {
        for (Vertex v : vertex.getVertices(Direction.OUT, SIMILAR))
        {
            int community = v.getProperty(COMMUNITY);
            if (!communities.contains(community))
            {
                communities.add(community);
            }
        }
    }
    return communities;
}
 
Example #7
Source File: DElementStore.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
@Override
public Edge addEdge(final Object id) {
	Edge result = null;
	if (id != null) {
		Element chk = getElement(id);
		if (chk != null && chk instanceof Vertex) {
			return (Edge) chk;
		}
	}
	Object localkey = localizeKey(id);
	Map<String, Object> delegate = addElementDelegate(localkey, Edge.class, false);
	if (delegate != null) {
		DEdge edge = new DEdge(getConfiguration().getGraph(), delegate);
		result = edge;
		getElementCache().put((NoteCoordinate) result.getId(), result);
		if (id != null) {
			getKeyMap().put(id, (NoteCoordinate) result.getId()); //TODO shouldn't force NoteCoordinate, but it covers all current use cases
		}
		getConfiguration().getGraph().startTransaction(result);
	}
	return result;
}
 
Example #8
Source File: OrientSingleInsertion.java    From graphdb-benchmarks with Apache License 2.0 6 votes vote down vote up
@Override
protected Vertex getOrCreate(final String value)
{
    final int key = Integer.parseInt(value);

    Vertex v;
    final OIdentifiable rec = (OIdentifiable) index.get(key);
    if (rec != null)
    {
        return orientGraph.getVertex(rec);
    }

    v = orientGraph.addVertex(key, "nodeId", key);

    if (orientGraph instanceof TransactionalGraph)
    {
        orientGraph.commit();
    }

    return v;
}
 
Example #9
Source File: IdGraph.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
public Edge addEdge(final Object id,
                    final Vertex outVertex,
                    final Vertex inVertex,
                    final String label) {
    if (uniqueIds && null != id && null != getEdge(id)) {
        throw new IllegalArgumentException("edge with given id already exists: " + id);
    }

    verifyNativeElement(outVertex);
    verifyNativeElement(inVertex);

    Edge base = baseGraph.addEdge(null, ((IdVertex) outVertex).getBaseVertex(), ((IdVertex) inVertex).getBaseVertex(), label);

    if (supportEdgeIds) {
        Object v = null == id ? edgeIdFactory.createId() : id;

        if (null != v) {
            base.setProperty(ID, v);
        }
    }

    return new IdEdge(base, this);
}
 
Example #10
Source File: ActiveVersionedGraph.java    From antiquity with GNU General Public License v3.0 6 votes vote down vote up
@Override
public GraphQuery query() {
    final ActiveVersionedGraph<T, V> ag = this;
    return new WrappedGraphQuery(getBaseGraph().query()) {
        @Override
        public Iterable<Edge> edges() {
            return new ActiveVersionedEdgeIterable<V>(getQuery().edges(), ag);
        }

        @Override
        public Iterable<Vertex> vertices() {
            return new ActiveVersionedVertexIterable<V>(getQuery().vertices(), ag);
        }

        public GraphQuery getQuery() {
            return this.query.has(VEProps.HISTORIC_ELEMENT_PROP_KEY, false);
        }
    };
}
 
Example #11
Source File: FunctionAlocCreator.java    From bjoern with GNU General Public License v3.0 5 votes vote down vote up
private Vertex createAloc(
		String alocName, String subType, Integer width) {
	return GraphHelper.addVertex(graph, 0,
			BjoernNodeProperties.TYPE, BjoernNodeTypes.ALOC,
			BjoernNodeProperties.SUBTYPE, subType,
			BjoernNodeProperties.NAME, alocName,
			BjoernNodeProperties.WIDTH, width);
}
 
Example #12
Source File: AbstractUserRule.java    From light with Apache License 2.0 5 votes vote down vote up
@Deprecated
String generateToken(Vertex user, String clientId, Boolean rememberMe) throws Exception {
    Map<String, Object> jwtMap = new LinkedHashMap<String, Object>();
    jwtMap.put("userId", user.getProperty("userId"));
    jwtMap.put("clientId", clientId);
    jwtMap.put("roles", user.getProperty("roles"));
    if(user.getProperty("host") != null) jwtMap.put("host", user.getProperty("host"));
    return JwtUtil.getJwt(jwtMap, rememberMe);
}
 
Example #13
Source File: AbstractEdgeHelper.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Override
public SortedSet<? extends Edge> getSortedEdges(final Vertex vertex, final String... sortproperties) {
	try {
		Set<? extends Edge> rawSet = getEdges(vertex);
		//			System.out.println("Requested sorting of " + rawSet.size() + " raw edges");

		SortedSet<? extends Edge> sortedSet = DominoGraph.sortEdges(rawSet, sortproperties);
		//			System.out.println("Returning sorted edge set of " + sortedSet.size());
		SortedSet<? extends Edge> result = sortedSet;
		return result;
	} catch (Throwable t) {
		throw new RuntimeException(t);
	}
}
 
Example #14
Source File: DFramedTransactionalGraph.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Override
public <F> Iterable<F> getVertices(final String key, final Object value, final Class<F> kind) {
	org.openntf.domino.graph2.DElementStore store = null;
	DGraph base = (DGraph) this.getBaseGraph();
	store = base.findElementStore(kind);
	if (store != null) {
		String formulaFilter = org.openntf.domino.graph2.DGraph.Utils.getFramedVertexFormula(key, value, kind);
		Iterable<Vertex> vertices = store.getVertices(formulaFilter);
		return this.frameVertices(vertices, kind);
	} else {
		return null;
	}
}
 
Example #15
Source File: VersionedGraphTestSuite.java    From antiquity with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Ensure vertices versions are as expected.
 * 
 * Removed elements ranges already tested in
 * {@link #removeVersionedVertex()}
 */
@Test
public void testVertexVersionRanges() {
    ActiveVersionedVertex fooV = (ActiveVersionedVertex) graph.addVertex(null);
    CIT();
    V ver1 = last();

    Vertex fooHV = graph.getHistoricGraph().getLatestHistoricRevision(fooV);
    assertThat(Range.range(ver1, graph.getMaxPossibleGraphVersion()), is(graph.utils.getVersionRange(fooHV)));

    fooV.setProperty("prop", "foo");
    CIT();
    V ver2 = last();
    fooHV = graph.getHistoricGraph().getLatestHistoricRevision(fooV);
    assertThat(Range.range(ver2, graph.getMaxPossibleGraphVersion()), is(graph.utils.getVersionRange(fooHV)));


    ActiveVersionedVertex barV = (ActiveVersionedVertex) graph.addVertex(null);
    CIT();
    barV.setProperty("prop", "bar");
    CIT();
    V ver4 = last();

    fooHV = graph.getHistoricGraph().getLatestHistoricRevision(fooV);
    Vertex barHV = graph.getHistoricGraph().getLatestHistoricRevision(barV);

    assertThat(Range.range(ver2, graph.getMaxPossibleGraphVersion()), is(graph.utils.getVersionRange(fooHV)));
    assertThat(Range.range(ver4, graph.getMaxPossibleGraphVersion()), is(graph.utils.getVersionRange(barHV)));
}
 
Example #16
Source File: DEdge.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Override
public Object getOtherVertexId(final Vertex vertex) {
	if (vertex.getId().equals(getVertexId(Direction.IN))) {
		return getVertexId(Direction.OUT);
	} else {
		return getVertexId(Direction.IN);
	}
}
 
Example #17
Source File: MixedFramedVertexList.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Override
public void add(final int arg0, final Object arg1) {
	if (arg1 instanceof VertexFrame) {
		list_.add(arg0, ((VertexFrame) arg1).asVertex());
	} else if (arg1 instanceof Vertex) {
		list_.add(arg0, (Vertex) arg1);
	}
}
 
Example #18
Source File: PartitionGraph.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
public GraphQuery query() {
    final PartitionGraph partitionGraph = this;
    return new WrappedGraphQuery(this.baseGraph.query()) {
        @Override
        public Iterable<Edge> edges() {
            return new PartitionEdgeIterable(this.query.has(partitionKey, Contains.IN, readPartitions).edges(), partitionGraph);
        }

        @Override
        public Iterable<Vertex> vertices() {
            return new PartitionVertexIterable(this.query.has(partitionKey, Contains.IN, readPartitions).vertices(), partitionGraph);
        }
    };
}
 
Example #19
Source File: EdOrgImporter.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public void importEducationOrganizations(String type) {
    logger.log(Level.INFO, "Importing education organizations into graph: " + type);
    
    DBObject query = new BasicDBObject();
    query.put("type", type);
    
    DBCursor cursor = mongo.getCollection(EDUCATION_ORGANIZATION).find(query);
    cursor.batchSize(BATCH_SIZE);
    while (cursor.hasNext()) {
        DBObject edOrg = cursor.next();
        String currentEdOrgId = (String) edOrg.get("_id");
        
        Vertex v = graph.addVertex(null);
        logger.log(Level.INFO, "Adding vertex for {0}#{1} \t {2}", new String[] { type,
                currentEdOrgId, v.getId().toString() });
        
        v.setProperty("mongoid", currentEdOrgId);
        
        @SuppressWarnings("unchecked")
        Map<String, Object> body = (Map<String, Object>) edOrg.get("body");
        if (body.containsKey("parentEducationAgencyReference")) {
            String parentId = (String) body.get("parentEducationAgencyReference");
            for (Vertex child : graph.getVertices("mongoid", currentEdOrgId)) {
                for (Vertex parent : graph.getVertices("mongoid", parentId)) {
                    graph.addEdge(null, parent, child, EDUCATION_ORGANIZATION_ASSOCIATION);
                    logger.log(Level.INFO, "Adding an edge between ed org: " + parentId + " --> " + currentEdOrgId);
                }
            }
        }
    }
}
 
Example #20
Source File: AccumuloEdge.java    From AccumuloGraph with Apache License 2.0 5 votes vote down vote up
public AccumuloEdge(GlobalInstances globals, String id,
    Vertex inVertex, Vertex outVertex, String label) {
  super(globals, id, Edge.class);
  this.label = label;
  this.inVertex = inVertex;
  this.outVertex = outVertex;
}
 
Example #21
Source File: AccumuloElementTest.java    From AccumuloGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonStringIds() throws Exception {
  Graph graph = AccumuloGraphTestUtils.makeGraph("nonStringIds");

  Object[] ids = new Object[] {
      10, 20, 30L, 40L,
      50.0f, 60.0f, 70.0d, 80.0d,
      (byte) 'a', (byte) 'b', 'c', 'd',
      "str1", "str2",
      new GenericObject("str3"), new GenericObject("str4"),
  };

  Object[] edgeIds = new Object[] {
      100, 200, 300L, 400L,
      500.0f, 600.0f, 700.0d, 800.0d,
      (byte) 'e', (byte) 'f', 'g', 'h',
      "str5", "str6",
      new GenericObject("str7"), new GenericObject("str8"),
  };

  for (int i = 0; i < ids.length; i++) {
    assertNull(graph.getVertex(ids[i]));
    Vertex v = graph.addVertex(ids[i]);
    assertNotNull(v);
    assertNotNull(graph.getVertex(ids[i]));
  }
  assertEquals(ids.length, count(graph.getVertices()));

  for (int i = 1; i < edgeIds.length; i++) {
    assertNull(graph.getEdge(edgeIds[i-1]));
    Edge e = graph.addEdge(edgeIds[i-1],
        graph.getVertex(ids[i-1]),
        graph.getVertex(ids[i]), "label");
    assertNotNull(e);
    assertNotNull(graph.getEdge(edgeIds[i-1]));
  }
  assertEquals(edgeIds.length-1, count(graph.getEdges()));

  graph.shutdown();
}
 
Example #22
Source File: FunctionAlocCreator.java    From bjoern with GNU General Public License v3.0 5 votes vote down vote up
private Vertex getRegisterFamilyNode(String registerName) {
	String registerFamilyName = radare.getRegisterFamily(registerName);
	if (!registerFamilyCache.containsKey(registerFamilyName)) {
		Vertex familyNode = GraphHelper.addVertex(graph, 0,
				BjoernNodeProperties.TYPE, FAMILY_TYPE,
				BjoernNodeProperties.NAME, registerFamilyName);
		registerFamilyCache
				.put(registerFamilyName, familyNode);
		return familyNode;
	}
	return registerFamilyCache.get(registerFamilyName);
}
 
Example #23
Source File: AbstractEdgeHelper.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Override
public Class<? extends Vertex> getOtherType(final Class<? extends Vertex> type) {
	if (getInType().equals(type)) {
		return getOutType();
	}
	if (getOutType().equals(type)) {
		return getInType();
	}
	if (getInType().isAssignableFrom(type))
		return getOutType();
	if (getOutType().isAssignableFrom(type))
		return getInType();
	throw new EdgeHelperException(type.getName() + " is not a participating type in edge " + getLabel());
}
 
Example #24
Source File: AbstractEdgeHelper.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
public AbstractEdgeHelper(final DominoGraph parent, final String label, final Class<? extends Vertex> inType,
		final Class<? extends Vertex> outType, final boolean unique) {
	label_ = label;
	inType_ = inType;
	outType_ = outType;
	unique_ = unique;
	sameTypes_ = inType_.equals(outType_);
	parent_ = parent;
}
 
Example #25
Source File: ReachingDefinitionAnalyser.java    From bjoern with GNU General Public License v3.0 5 votes vote down vote up
private Set<Definition> getOut(Vertex predecessor) {
	Set<Definition> out = this.out.get(predecessor);
	if (null == out) {
		out = getGenSet(predecessor);
	}
	return out;
}
 
Example #26
Source File: ExtendedElementTest.java    From AccumuloGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipExistenceChecks() throws Exception {
  AccumuloGraphConfiguration cfg =
      AccumuloGraphTestUtils.generateGraphConfig("skipExistenceChecks");
  cfg.setSkipExistenceChecks(true);
  Graph graph = makeGraph(cfg);

  String id;

  id = "doubleAdd";
  assertNotNull(graph.addVertex(id));
  assertNotNull(graph.addVertex(id));
  Vertex vAdd = graph.getVertex(id);
  assertNotNull(vAdd);
  graph.removeVertex(vAdd);
  assertNotNull(graph.getVertex(id));


  id = "doubleRemove";
  Vertex vRemove = graph.addVertex(id);
  assertNotNull(vRemove);
  graph.removeVertex(vRemove);
  assertNotNull(graph.getVertex(id));
  // MDL 24 Dec 2014:  removeVertex still does checks.
  //graph.removeVertex(vRemove);
  //assertNotNull(graph.getVertex(id));


  id = "notExist";
  assertNotNull(graph.getVertex(id));

  graph.shutdown();
}
 
Example #27
Source File: TagRelationTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsDeleted() {
    Vertex v = createStrictMock(Vertex.class);
    expect(v.getProperty(Constants.STATE_PROPERTY_KEY)).andReturn(Id.EntityState.ACTIVE.name());
    replay(v);

    BaseRelation relation = new TagRelation();
    assertFalse(relation.isDeleted(v));
}
 
Example #28
Source File: FunctionExportPlugin.java    From bjoern with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute() throws Exception
{
	OrientGraphNoTx graph = orientConnector.getNoTxGraphInstance();

	Iterable<Vertex> functions = LookupOperations.getAllFunctions(graph);

	for (Vertex function : functions)
	{
		exportFunction(function);
	}

	graph.shutdown();
}
 
Example #29
Source File: DominoGraphTest.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	long start = System.nanoTime();
	Session s = Factory.getSession(SessionType.FULL_ACCESS);
	Database db = s.getDatabase(server, dbPath);
	DominoGraph graph = new DominoGraph(db);
	for (int i = 1; i <= 10000; i++) {
		Vertex v1 = graph.addVertex(null);
		v1.setProperty("Test1", i);

		Vertex v2 = graph.addVertex(null);
		v2.setProperty("Test1", i);

		graph.addEdge(null, v1, v2, "IAmInYou");
		if (i % 1000 == 0) {
			System.out.println("Iterated test " + i + " times.  Committing...");
			graph.commit();
		}
	}
	graph.commit();
	System.gc();

	long elapsed = System.nanoTime() - start;
	StringBuilder sb = new StringBuilder();
	sb.append("Thread " + Thread.currentThread().getName());
	sb.append(" *** ALL OPERATIONS COMPLETE elapsed time: ");
	sb.append(elapsed / 1000000 + "ms");
	System.out.println(sb.toString());
}
 
Example #30
Source File: WrappedGraph.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
public GraphQuery query() {
    return new WrappedGraphQuery(this.baseGraph.query()) {
        @Override
        public Iterable<Edge> edges() {
            return new WrappedEdgeIterable(this.query.edges());
        }

        @Override
        public Iterable<Vertex> vertices() {
            return new WrappedVertexIterable(this.query.vertices());
        }
    };
}