org.neo4j.graphdb.Node Java Examples
The following examples show how to use
org.neo4j.graphdb.Node.
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: StackOverflowExtractor.java From SnowGraph with Apache License 2.0 | 6 votes |
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (!qName.equals("row")) return; int id = Integer.parseInt(attributes.getValue("Id")); int parentId = Integer.parseInt(attributes.getValue("ParentId")); String creationDate = attributes.getValue("CreationDate"); int score = Integer.parseInt(attributes.getValue("Score")); String body = attributes.getValue("Body"); String ownerUserIdString = attributes.getValue("OwnerUserId"); if (ownerUserIdString == null) ownerUserIdString = "-1"; int ownerUserId = Integer.parseInt(ownerUserIdString); Node node = db.createNode(); AnswerInfo answerInfo = new AnswerInfo(node, id, parentId, creationDate, score, body, ownerUserId); answerMap.put(id, answerInfo); }
Example #2
Source File: Traversals.java From EvilCoder with MIT License | 6 votes |
public static List<Node> getCallsToForFunction(String source, long functionId) { List<Node> retval = new LinkedList<Node>(); // JANNIK String my = source; my = my.replace("*", "\\*"); my = my.replace("(", "\\("); my = my.replace(")", "\\)"); my = my.replace("-", "\\-"); my = my.replace(" ", "\\ "); String query = String.format("%s:Callee AND %s:%s AND %s:%s", NodeKeys.TYPE, NodeKeys.FUNCTION_ID, functionId, NodeKeys.CODE, my); IndexHits<Node> hits = Neo4JDBInterface.queryIndex(query); for (Node n : hits) { List<Node> parents = getParentsConnectedBy(n, "IS_AST_PARENT"); retval.add(parents.get(0)); } return retval; }
Example #3
Source File: ExecutionResultIterator.java From neo4jena with Apache License 2.0 | 6 votes |
@Override public Triple next() { //System.out.println("ExecutionResultIterator#next"); try(Transaction tx = graphdb.beginTx()) { Map<String,Object> row = delegate.next(); //System.out.println("In execution iterator subject: " + row.get("subject") + row.get("subject").getClass()); //Node nsubject = (Node) row.get("subject"); // JenaNeoNode neonode = new JenaNeoNode(nsubject); // System.out.println("Node is uri:" + neonode.isURI()); //System.out.println("Subject: "+ new JenaNeoNode((Node)row.get("subject"))); Triple t = new Triple(new JenaNeoNode((Node)row.get("subject")), ResourceFactory.createProperty((String)row.get("type(predicate)")).asNode(), new JenaNeoNode((Node)row.get("object"))); return t; } }
Example #4
Source File: ReferenceExtractor.java From SnowGraph with Apache License 2.0 | 6 votes |
private void fromTextToJira(){ Map<String, Node> jiraMap=new HashMap<>(); try (Transaction tx = db.beginTx()) { for (Node node:db.getAllNodes()){ if (node.hasLabel(Label.label(JiraExtractor.ISSUE))){ String name=(String) node.getProperty(JiraExtractor.ISSUE_NAME); jiraMap.put(name, node); } } tx.success(); } try (Transaction tx = db.beginTx()) { for (Node srcNode : textNodes) { String content = text(srcNode); Set<String> tokenSet=new HashSet<>(); for (String e:content.split("[^A-Za-z0-9\\-_]+")) tokenSet.add(e); for (String jiraName:jiraMap.keySet()){ if (tokenSet.contains(jiraName)) srcNode.createRelationshipTo(jiraMap.get(jiraName), RelationshipType.withName(REFERENCE)); } } tx.success(); } }
Example #5
Source File: StatusUpdateManager.java From metalcon with GNU General Public License v3.0 | 6 votes |
/** * store the status update template linking to the latest previous version * * @param graphDatabase * social graph database to store the template in * @param template * status update template * @param previousTemplateNode * template node of the latest previous version */ private static void storeStatusUpdateTemplate( final AbstractGraphDatabase graphDatabase, final StatusUpdateTemplate template, final Node previousTemplateNode) { final Transaction transaction = graphDatabase.beginTx(); try { // create template node final Node templateNode = StatusUpdateTemplate.createTemplateNode( graphDatabase, template); // link to the latest previous version if (previousTemplateNode != null) { templateNode.createRelationshipTo(previousTemplateNode, SocialGraphRelationshipType.Templates.PREVIOUS); } // store the template node NeoUtils.storeStatusUpdateTemplateNode(graphDatabase, template.getName(), templateNode, previousTemplateNode); transaction.success(); } finally { transaction.finish(); } }
Example #6
Source File: Neo4jApiTransformationInjectConnectedSegments.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
@Override public void activate(final Collection<Neo4jConnectedSegmentsInjectMatch> matches) { for (final Neo4jConnectedSegmentsInjectMatch match : matches) { // create (segment2) node final Node segment2 = driver.getGraphDb().createNode(Neo4jConstants.labelSegment); segment2.setProperty(ModelConstants.ID, driver.generateNewVertexId()); segment2.setProperty(ModelConstants.LENGTH, TrainBenchmarkConstants.DEFAULT_SEGMENT_LENGTH); // (segment2)-[:monitoredBy]->(sensor) segment2.createRelationshipTo(match.getSensor(), Neo4jConstants.relationshipTypeMonitoredBy); // (segment1)-[:connectsTo]->(segment2) match.getSegment1().createRelationshipTo(segment2, Neo4jConstants.relationshipTypeConnectsTo); // (segment2)-[:connectsTo]->(segment3) segment2.createRelationshipTo(match.getSegment3(), Neo4jConstants.relationshipTypeConnectsTo); // remove (segment1)-[:connectsTo]->(segment3) final Iterable<Relationship> connectsToEdges = match.getSegment1().getRelationships(Direction.OUTGOING, Neo4jConstants.relationshipTypeConnectsTo); for (final Relationship connectsToEdge : connectsToEdges) { if (connectsToEdge.getEndNode().equals(match.getSegment3())) { connectsToEdge.delete(); } } } }
Example #7
Source File: HyperGeometricAnalyzer.java From SciGraph with Apache License 2.0 | 6 votes |
private Set<AnalyzerInnerNode> getCompleteSetNodes(AnalyzeRequest request) throws Exception { String query = "match (r)<-[:subClassOf*]-(n)" + request.getPath() + "(i) where id(r) = " + getNodeIdFromIri(request.getOntologyClass()) + " with n, i as t return t, count(distinct n)"; //System.out.println(query); Result result2 = cypherUtil.execute(query); Set<AnalyzerInnerNode> allSubjects = new HashSet<>(); while (result2.hasNext()) { Map<String, Object> map = result2.next(); Long count = (Long) map.get("count(distinct n)"); Long nodeId = ((Node) map.get("t")).getId(); allSubjects.add(new AnalyzerInnerNode(nodeId, count)); allSubjects.addAll(resolveToParents(nodeId, count)); } return allSubjects; }
Example #8
Source File: Neo4jIndexer.java From elasticsearch-river-neo4j with Apache License 2.0 | 6 votes |
public void index() { version = getVersion(); logger.debug("Awake and about to poll..."); Iterable<Node> r = db.getAllNodes(); for (Node node : r) { // If labels exists, filter nodes by label if(labels.size() > 0) { for (Label label : labels) { if(node.hasLabel(label)) { worker.queue(new IndexOperation(indexingStrategy, index, type, node, version)); } } } else { worker.queue(new IndexOperation(indexingStrategy, index, type, node, version)); } } logger.debug("...polling completed"); logger.debug("Deleting all nodes with version < {}", version); worker.queue(new ExpungeOperation(deletingStategy, index, type, version)); }
Example #9
Source File: MoveIndicesToIsLatestVertexMigration.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
private void updateQuicksearchIndex(Vres vres, IndexManager indexManager, ObjectMapper mapper, Node node, Collection wwpersonCollection, GraphTraversalSource traversalSource) { for (String type : getEntityTypes(node, mapper)) { if (!type.equals("relationtype")) { Optional<Collection> collection = vres.getCollectionForType(type); long id = node.getId(); if (collection.isPresent()) { String displayName; if (type.equals("wwdocument")) { displayName = getWwDocumentsQuickSearchValue(collection.get(), wwpersonCollection, id, traversalSource ); } else { displayName = getGenericQuickSearchValue(collection.get(), id, traversalSource); } indexManager.forNodes(collection.get().getCollectionName()).add(node, "quickSearch", displayName); } else { LOG.error("Could not find collection for " + type + " at vertex " + id); } } } }
Example #10
Source File: OwlPostprocessor.java From SciGraph with Apache License 2.0 | 6 votes |
long processCategory(Node root, RelationshipType type, Direction direction, String category) { long count = 0; int batchSize = 100_000; Label label = Label.label(category); Transaction tx = graphDb.beginTx(); for (Path position : graphDb.traversalDescription().uniqueness(Uniqueness.NODE_GLOBAL) .depthFirst().relationships(type, direction) .relationships(OwlRelationships.RDF_TYPE, Direction.INCOMING) .relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH).traverse(root)) { Node end = position.endNode(); GraphUtil.addProperty(end, Concept.CATEGORY, category); end.addLabel(label); if (0 == ++count % batchSize) { logger.fine("Commiting " + count); tx.success(); tx.close(); tx = graphDb.beginTx(); } } tx.success(); tx.close(); return count; }
Example #11
Source File: Neo4JApiQuerySwitchMonitoredInject.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
@Override public Collection<Neo4jSwitchMonitoredInjectMatch> evaluate() { final Collection<Neo4jSwitchMonitoredInjectMatch> matches = new ArrayList<>(); final GraphDatabaseService graphDb = driver.getGraphDb(); try (final Transaction tx = graphDb.beginTx()) { // (sw:Switch) final Iterable<Node> sws = () -> graphDb.findNodes(Neo4jConstants.labelSwitch); for (final Node sw : sws) { final Map<String, Object> match = new HashMap<>(); match.put(QueryConstants.VAR_SW, sw); matches.add(new Neo4jSwitchMonitoredInjectMatch(match)); } } return matches; }
Example #12
Source File: TestSubClassOfExistential.java From SciGraph with Apache License 2.0 | 6 votes |
/** * See https://github.com/SciCrunch/SciGraph/wiki/MappingToOWL#subclassof-axioms * * Reduction step should give us a simple edge {sub p super} */ @Test public void testSubclass() { Node subclass = getNode("http://example.org/subclass"); Node superclass = getNode("http://example.org/superclass"); RelationshipType p = RelationshipType.withName("http://example.org/p"); Relationship relationship = getOnlyElement(GraphUtil.getRelationships(subclass, superclass, p)); assertThat("subclassOf relationship should start with the subclass.", relationship.getStartNode(), is(subclass)); assertThat("subclassOf relationship should end with the superclass.", relationship.getEndNode(), is(superclass)); assertThat("relationship has the correct iri", GraphUtil.getProperty(relationship, CommonProperties.IRI, String.class), is(Optional.of("http://example.org/p"))); assertThat("relationship is asserted", GraphUtil.getProperty(relationship, CommonProperties.CONVENIENCE, Boolean.class), is(Optional.of(true))); assertThat("owltype is added", GraphUtil.getProperty(relationship, CommonProperties.OWL_TYPE, String.class), is(Optional.of(OwlRelationships.RDFS_SUBCLASS_OF.name()))); }
Example #13
Source File: Neo4jGraphDatabase.java From graphdb-benchmarks with Apache License 2.0 | 6 votes |
@Override public Set<Integer> getNodesFromCommunity(int community) { Set<Integer> nodes = new HashSet<Integer>(); try (final Transaction tx = beginUnforcedTransaction()) { try { ResourceIterable<Node> iter = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, COMMUNITY, community); for (Node n : iter) { String nodeIdString = (String) (n.getProperty(NODE_ID)); nodes.add(Integer.valueOf(nodeIdString)); } tx.success(); } catch (Exception e) { tx.failure(); throw new BenchmarkingException("unable to get nodes from community", e); } } return nodes; }
Example #14
Source File: Init.java From neo4j-versioner-core with Apache License 2.0 | 6 votes |
@Procedure(value = "graph.versioner.init", mode = Mode.WRITE) @Description("graph.versioner.init(entityLabel, {key:value,...}, {key:value,...}, additionalLabel, date) - Create an Entity node with an optional initial State.") public Stream<NodeOutput> init( @Name("entityLabel") String entityLabel, @Name(value = "entityProps", defaultValue = "{}") Map<String, Object> entityProps, @Name(value = "stateProps", defaultValue = "{}") Map<String, Object> stateProps, @Name(value = "additionalLabel", defaultValue = "") String additionalLabel, @Name(value = "date", defaultValue = "null") LocalDateTime date) { Node entity = createNode(entityProps, singletonList(entityLabel)); Node state = createNode(stateProps, getStateLabels(additionalLabel)); connectWithCurrentRelationship(entity, state, date); log.info(LOGGER_TAG + "Created a new Entity with label {} and id {}", entityLabel, entity.getId()); createRNodeAndAssociateTo(entity); return streamOfNodes(entity); }
Example #15
Source File: DeleteFollowRequest.java From metalcon with GNU General Public License v3.0 | 6 votes |
/** * check if the request contains a valid followed identifier * * @param request * Tomcat servlet request * @param response * response object * @return user node with the identifier passed<br> * <b>null</b> if the identifier is invalid */ private static Node checkFollowedIdentifier( final HttpServletRequest request, final DeleteFollowResponse response) { final String followedId = request .getParameter(ProtocolConstants.Parameters.Delete.Follow.FOLLOWED_IDENTIFIER); if (followedId != null) { final Node followed = NeoUtils.getUserByIdentifier(followedId); if (followed != null) { return followed; } response.followedIdentifierInvalid(followedId); } else { response.followedIdentifierMissing(); } return null; }
Example #16
Source File: ReachabilityIndex.java From SciGraph with Apache License 2.0 | 6 votes |
public void dropIndex() { if (indexExists()) { Transaction tx = graphDb.beginTx(); // ...cleanup the index. int counter = 0; for (Node n : graphDb.getAllNodes()) { n.removeProperty(IN_LIST_PROPERTY); n.removeProperty(OUT_LIST_PROPERTY); tx = batchTransactions(tx, counter++); } // reset the flag. metaDataNode.setProperty(INDEX_EXISTS_PROPERTY, false); tx.success(); tx.close(); logger.info("Reachability index dropped."); } else { logger.warning("There was no reachability index to drop."); } }
Example #17
Source File: GraphTransactionalImpl.java From SciGraph with Apache License 2.0 | 5 votes |
@Override public Collection<Label> getLabels(long nodeId) { try (Transaction tx = graphDb.beginTx()) { Node node = graphDb.getNodeById(nodeId); Collection<Label> labels = newArrayList(node.getLabels()); tx.success(); return labels; } }
Example #18
Source File: EdgeLabelerTest.java From SciGraph with Apache License 2.0 | 5 votes |
@Before public void setup() { n1 = createNode("http://x.org/a"); n2 = createNode("http://x.org/b"); Node rel = createNode(relationshipType1); rel.setProperty(NodeProperties.LABEL, relationshipType1Label); createNode(relationshipType2); n1.createRelationshipTo(n2, RelationshipType.withName(relationshipType1)); n1.createRelationshipTo(n2, RelationshipType.withName(relationshipType2)); n1.createRelationshipTo(n2, RelationshipType.withName(relationshipType3)); edgeLabeler = new EdgeLabeler(graphDb); edgeLabeler.run(); }
Example #19
Source File: Traversals.java From EvilCoder with MIT License | 5 votes |
public static Node getStatementForASTNode(Node node) { Node n = node; Node parent = node; while (true) { try { Object property = n.getProperty(NodeKeys.IS_CFG_NODE); return n; } catch (NotFoundException ex) { } Iterable<Relationship> rels = n .getRelationships(Direction.INCOMING); for (Relationship rel : rels) { parent = rel.getStartNode(); break; } if (n == parent) return null; n = parent; } }
Example #20
Source File: Diff.java From neo4j-versioner-core with Apache License 2.0 | 5 votes |
@Procedure(value = "graph.versioner.diff.from.previous", mode = DEFAULT) @Description("graph.versioner.diff.from.previous(state) - Get a list of differences that must be applied to the previous statusof the given one in order to become the given state") public Stream<DiffOutput> diffFromPrevious( @Name("state") Node state) { return Optional.ofNullable(state.getSingleRelationship(RelationshipType.withName(Utility.PREVIOUS_TYPE), Direction.OUTGOING)) .map(Relationship::getEndNode) .map(sFrom -> diffBetweenStates(sFrom, state)) .orElse(Stream.empty()); }
Example #21
Source File: Rollback.java From neo4j-versioner-core with Apache License 2.0 | 5 votes |
/** * This method returns the first available State node, by a given State node to rollback * * @param state state to rollback * @return the first available rollback node */ private Optional<Node> getFirstAvailableRollbackNode(Node state) { return StreamSupport.stream(state.getRelationships(RelationshipType.withName(Utility.ROLLBACK_TYPE), Direction.OUTGOING).spliterator(), false).findFirst() // Recursive iteration for ROLLBACKed State node .map(e -> getFirstAvailableRollbackNode(e.getEndNode())) // No ROLLBACK relationship found .orElse(StreamSupport.stream(state.getRelationships(RelationshipType.withName(Utility.PREVIOUS_TYPE), Direction.OUTGOING).spliterator(), false) .findFirst().map(Relationship::getEndNode)); }
Example #22
Source File: Neo4jApiTransformationInjectSwitchSet.java From trainbenchmark with Eclipse Public License 1.0 | 5 votes |
@Override public void activate(final Collection<Neo4jSwitchSetInjectMatch> matches) { for (final Neo4jSwitchSetInjectMatch match : matches) { final Node sw = match.getSw(); final String currentPositionString = (String) sw.getProperty(ModelConstants.CURRENTPOSITION); final Position currentPosition = Position.valueOf(currentPositionString); final Position newCurrentPosition = Position.values()[(currentPosition.ordinal() + 1) % Position.values().length]; sw.setProperty(ModelConstants.CURRENTPOSITION, newCurrentPosition.toString()); } }
Example #23
Source File: Neo4jGraphDatabase.java From graphdb-benchmarks with Apache License 2.0 | 5 votes |
@Override public double getNodeCommunityWeight(int nodeCommunity) { double nodeCommunityWeight = 0; try (final Transaction tx = beginUnforcedTransaction()) { try { ResourceIterable<Node> iter = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, NODE_COMMUNITY, nodeCommunity); if (Iterables.size(iter) > 1) { for (Node n : iter) { nodeCommunityWeight += getNodeOutDegree(n); } } tx.success(); } catch (Exception e) { tx.failure(); throw new BenchmarkingException("unable to get node community weight", e); } } return nodeCommunityWeight; }
Example #24
Source File: Find_data_paths.java From EvilCoder with MIT License | 5 votes |
public static List<Node> get_cfg_same_use(Joern_db joern_db, Long node_id, Object var_name) { String var_name_together = member_to_var_name(var_name); List<Long> defs = new ArrayList<>(); HashSet<Long> nodes_till_now = new HashSet<>(); for(Long i = new Long(1), i_end = new Long(50); i<i_end; ++i) { // print "i:", i HashSet<Long> nodes = find_inflow_nodes_with_path_length(joern_db, node_id, i, nodes_till_now); for(Long n : nodes) { List<Node> uses = Pipeline.v(n).uses().to_list(); for(Node u : uses) { String code = (String)(u.getProperty("code")); String u_together = member_to_var_name(Function_sets_parameter.split_into_elements(code)); if(u_together.equals(var_name_together)) { // print "get_cfg_same_use, found match:", n defs.add(get_deepest_child_using(joern_db, n, var_name_together)); } } } // print "n, uses:", n, uses if(defs.size() != 0) { break; } nodes_till_now = nodes; } return Pipeline.v(defs).to_list(); }
Example #25
Source File: Neo4jHelper.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
public static void dumpDb(GraphDatabaseService gds) { for (Node node : gds.getAllNodes()) { System.out.println(dumpNode(node)); } for (Relationship rel : gds.getAllRelationships()) { System.out.println(dumpEdge(rel)); } }
Example #26
Source File: FunctionPatcher.java From EvilCoder with MIT License | 5 votes |
private void determineCallsToPatch(Long funcId) { List<Node> callNodes = Traversals.getCallsToForFunction(sourceToPatch, funcId); for (Node callNode : callNodes) { Node parent = Traversals.getStatementForASTNode(callNode); statementsToPatch.add(parent); } }
Example #27
Source File: Traversals.java From EvilCoder with MIT License | 5 votes |
public static int getNodeChildNum(long nodeId) { Node node = Neo4JDBInterface.getNodeById(nodeId); String childNumStr = (String) node.getProperty(NodeKeys.CHILD_NUMBER, null); if (childNumStr == null) return 0; return Integer.parseInt(childNumStr); }
Example #28
Source File: GitCommit.java From SnowGraph with Apache License 2.0 | 5 votes |
public Node createNode(GraphDatabaseService db){ Node node=db.createNode(); node.addLabel(Label.label(GitExtractor.COMMIT)); node.setProperty(GitExtractor.COMMIT_ID,commitId); node.setProperty(GitExtractor.COMMIT_DATE,createDate); node.setProperty(GitExtractor.COMMIT_LOGMESSAGE,logMessage); node.setProperty(GitExtractor.COMMIT_CONTENT,content); return node; }
Example #29
Source File: PageRank.java From Neo4jSNA with Apache License 2.0 | 5 votes |
@Override public void apply(Node node) { double secondMember = 0.0; for( Relationship rin : node.getRelationships() ) { Node neigh = rin.getOtherNode(node); double neighRank = (double) neigh.getProperty(attName); secondMember += neighRank / neigh.getDegree(); } secondMember *= this.dampingFactor; node.setProperty(attName, firstMember + secondMember); }
Example #30
Source File: Neo4JDBInterface.java From EvilCoder with MIT License | 5 votes |
public static Node addNode(Map<String,Object> properties) { Node newNode = graphDb.createNode(); Set<Entry<String, Object>> entrySet = properties.entrySet(); Iterator<Entry<String, Object>> it = entrySet.iterator(); while(it.hasNext()){ Entry<String, Object> next = it.next(); newNode.setProperty(next.getKey(), next.getValue()); } return newNode; }