Java Code Examples for com.tinkerpop.blueprints.Vertex

The following examples show how to use com.tinkerpop.blueprints.Vertex. These examples are extracted from open source projects. 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 Project: light   Source File: AbstractUserRule.java    License: 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 2
Source Project: light   Source File: AbstractPaymentRule.java    License: 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 3
Source Project: graphdb-benchmarks   Source File: OrientGraphDatabase.java    License: 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 4
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 5
Source Project: org.openntf.domino   Source File: IdGraph.java    License: 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 6
Source Project: AccumuloGraph   Source File: AutoIndexTest.java    License: 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 7
Source Project: bjoern   Source File: DotWriter.java    License: 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 8
Source Project: org.openntf.domino   Source File: DElementStore.java    License: 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 9
@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 10
Source Project: graphdb-benchmarks   Source File: OrientSingleInsertion.java    License: 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 11
protected void testBigdataGraph(BigdataGraph testGraph) throws Exception {

	loadTestGraph(testGraph, testData);

	for (Vertex v : testGraph.getVertices()) {
		testPrint(v);
	}
	for (Edge e : testGraph.getEdges()) {
		testPrint(e);
	}

	testGraph.shutdown();

}
 
Example 12
Source Project: bjoern   Source File: LookupOperations.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Deprecated
public static Iterable<Vertex> getAllFunctions(OrientGraphNoTx graph)
{
	Iterable<Vertex> functions = graph.command(
			BjoernConstants.LUCENE_QUERY).execute("nodeType:" + BjoernNodeTypes.FUNCTION);
	return functions;
}
 
Example 13
Source Project: bjoern   Source File: LookupOperations.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Iterable<Function> getFunctions(OrientGraphNoTx graph)
{
	boolean parallel = true;
	Iterable<Vertex> functions = graph.command(BjoernConstants.LUCENE_QUERY)
			.execute("nodeType:" + BjoernNodeTypes.FUNCTION);
	return StreamSupport.stream(functions.spliterator(), parallel).map(Function::new)
			.collect(Collectors.toList());
}
 
Example 14
Source Project: light   Source File: AbstractRuleRule.java    License: Apache License 2.0 5 votes vote down vote up
protected void updEtag(Map<String, Object> data) throws Exception {
    String ruleClass = (String)data.get("ruleClass");
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        graph.begin();
        Vertex rule = graph.getVertexByKey("Rule.ruleClass", ruleClass);
        if(rule != null) {
            rule.setProperty("enableEtag", data.get("enableEtag"));
            String cacheControl = (String)data.get("cacheControl");
            if(cacheControl != null) {
                rule.setProperty("cacheControl", cacheControl);
            } else {
                rule.removeProperty("cacheControl");
            }
            rule.setProperty("updateDate", data.get("updateDate"));
            Map<String, Object> ruleMap = ServiceLocator.getInstance().getMemoryImage("ruleMap");
            ConcurrentMap<String, Map<String, Object>> cache = (ConcurrentMap<String, Map<String, Object>>)ruleMap.get("cache");
            if(cache != null) {
                cache.remove(ruleClass);
            }
        }
        graph.commit();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
        throw e;
    } finally {
        graph.shutdown();
    }
}
 
Example 15
Source Project: light   Source File: AbstractRuleRule.java    License: Apache License 2.0 5 votes vote down vote up
protected String updateValidation(Map<String, Object> inputMap, Map<String, Object> eventData) {
    Map<String, Object> data = (Map<String, Object>)inputMap.get("data");
    Map<String, Object> user = (Map<String, Object>) inputMap.get("user");
    String rid = (String)data.get("@rid");
    String ruleClass = (String)data.get("ruleClass");
    String error = null;
    String host = (String)user.get("host");
    if(host != null) {
        if(!host.equals(data.get("host"))) {
            error = "You can only update rule for host: " + host;
            inputMap.put("responseCode", 403);
        } else {
            // make sure the ruleClass contains the host.
            if(host != null && !ruleClass.contains(host)) {
                // you are not allowed to update rule as it is not owned by the host.
                error = "ruleClass is not owned by the host: " + host;
                inputMap.put("responseCode", 403);
            }
        }
    }
    if(error == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            Vertex rule = DbService.getVertexByRid(graph, rid);
            if(rule == null) {
                error = "Rule with @rid " + rid + " cannot be found";
                inputMap.put("responseCode", 404);
            } else {
                eventData.put("ruleClass", ruleClass);
                eventData.put("updateUserId", user.get("userId"));
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return error;
}
 
Example 16
Source Project: SciGraph   Source File: EvidenceAspectTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void evidenceIsAdded() {
  assertThat(graph.getVertices(), IsIterableWithSize.<Vertex>iterableWithSize(5));
  assertThat(graph.getEdges(), IsIterableWithSize.<Edge>iterableWithSize(1));
  aspect.invoke(graph);
  assertThat(graph.getVertices(), IsIterableWithSize.<Vertex>iterableWithSize(6));
  assertThat(graph.getEdges(), IsIterableWithSize.<Edge>iterableWithSize(4));
}
 
Example 17
Source Project: AccumuloGraph   Source File: AccumuloGraph.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown() {
  try {
    globals.getMtbw().close();
    globals.getVertexWrapper().close();
    globals.getEdgeWrapper().close();
  } catch (MutationsRejectedException e) {
    throw new AccumuloGraphException(e);
  }
  globals.getCaches().clear(Vertex.class);
  globals.getCaches().clear(Edge.class);
}
 
Example 18
Source Project: secure-data-service   Source File: BaseImporter.java    License: Apache License 2.0 5 votes vote down vote up
protected final boolean vertexExists(String id) {
    boolean hasVertex = false;
    for (@SuppressWarnings("unused") Vertex v : graph.getVertices("mongoid", id)) {
        hasVertex = true;
    }
    return hasVertex;
}
 
Example 19
Source Project: light   Source File: AbstractConfigRule.java    License: Apache License 2.0 5 votes vote down vote up
protected void updHostConfigDb(Map<String, Object> data) throws Exception {
    String host = (String)data.get("host");
    String configId = (String)data.get("configId");
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try{
        graph.begin();
        Vertex updateUser = graph.getVertexByKey("User.userId", data.remove("updateUserId"));
        OrientVertex config = getConfigByHostId(graph, host, configId);
        if(config != null) {
            if(data.get("description") != null) {
                config.setProperty("description", data.get("description"));
            } else {
                config.removeProperty("description");
            }
            if(data.get("properties") != null) {
                config.setProperty("properties", data.get("properties"));
            } else {
                config.removeProperty("properties");
            }
            config.setProperty("updateDate", data.get("updateDate"));
            // updateUser
            updateUser.addEdge("Update", config);
        }
        graph.commit();
    } catch (Exception e) {
        logger.error("Exception:", e);
        graph.rollback();
    } finally {
        graph.shutdown();
    }
}
 
Example 20
Source Project: secure-data-service   Source File: EdOrgImporter.java    License: 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 21
Source Project: org.openntf.domino   Source File: PartitionGraph.java    License: 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 22
Source Project: org.openntf.domino   Source File: MixedFramedVertexList.java    License: 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 23
/**
 * 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 24
@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 25
Source Project: AccumuloGraph   Source File: AccumuloEdge.java    License: 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 26
Source Project: AccumuloGraph   Source File: AccumuloElementTest.java    License: 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 27
Source Project: org.openntf.domino   Source File: AbstractEdgeHelper.java    License: 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 28
private Set<Definition> getOut(Vertex predecessor) {
	Set<Definition> out = this.out.get(predecessor);
	if (null == out) {
		out = getGenSet(predecessor);
	}
	return out;
}
 
Example 29
Source Project: AccumuloGraph   Source File: ExtendedElementTest.java    License: 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 30
Source Project: bjoern   Source File: FunctionExportPlugin.java    License: 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();
}