public virtual void AssertPaths <T1>(IEnumerable <T1> paths, IList <string> pathDefs) where T1 : Org.Neo4j.Graphdb.Path { IList <string> unexpectedDefs = new List <string>(); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: try (org.neo4j.graphdb.ResourceIterator<? extends org.neo4j.graphdb.Path> iterator = org.neo4j.helpers.collection.Iterators.asResourceIterator(paths.iterator())) using (ResourceIterator <Path> iterator = Iterators.asResourceIterator(paths.GetEnumerator())) { while (iterator.MoveNext()) { Path path = iterator.Current; string pathDef = GetPathDef(path); int index = pathDefs.IndexOf(pathDef); if (index != -1) { pathDefs.RemoveAt(index); } else { unexpectedDefs.Add(GetPathDef(path)); } } } assertTrue("These unexpected paths were found: " + unexpectedDefs + ". In addition these expected paths weren't found:" + pathDefs, unexpectedDefs.Count == 0); assertTrue("These were expected, but not found: " + pathDefs.ToString(), pathDefs.Count == 0); }
private void CollectNodes(MutableLongSet bucket, ResourceIterator <Node> toCollect) { while (toCollect.MoveNext()) { bucket.add(toCollect.Current.Id); } }
public override TraversalBranch Next(PathExpander expander, TraversalContext context) { if (_relationships == null) { ExpandRelationships(expander); } while (_relationships.MoveNext()) { Relationship relationship = _relationships.Current; if (relationship.Equals(_howIGotHere)) { context.UnnecessaryRelationshipTraversed(); continue; } _expandedCount++; Node node = relationship.GetOtherNode(_source); // TODO maybe an unnecessary instantiation. Instead pass in this+node+relationship to uniqueness check TraversalBranch next = NewNextBranch(node, relationship); if (context.IsUnique(next)) { context.RelationshipTraversed(); next.Initialize(expander, context); return(next); } else { context.UnnecessaryRelationshipTraversed(); } } ResetRelationships(); return(null); }
private void DeleteOneRelationship(Node node, RelType type, Direction direction, int which) { Relationship last = null; int counter = 0; IEnumerable <Relationship> relationships = node.GetRelationships(type, direction); using (ResourceIterator <Relationship> relationshipIterator = ( ResourceIterator )relationships.GetEnumerator()) { while (relationshipIterator.MoveNext()) { Relationship rel = relationshipIterator.Current; if (IsLoop(rel) == (direction == Direction.BOTH)) { last = rel; if (counter++ == which) { rel.Delete(); return; } } } } if (which == int.MaxValue && last != null) { last.Delete(); return; } fail("Couldn't find " + (direction == Direction.BOTH ? "loop" : "non-loop") + " relationship " + type.name() + " " + direction + " to delete"); }
// Attempt at recreating this issue without cypher // https://github.com/neo4j/neo4j/issues/4160 //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldAbortAsSoonAsPossible() public virtual void ShouldAbortAsSoonAsPossible() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Label A = org.neo4j.graphdb.Label.label("A"); Label a = Label.label("A"); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Label B = org.neo4j.graphdb.Label.label("B"); Label b = Label.label("B"); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Label C = org.neo4j.graphdb.Label.label("C"); Label c = Label.label("C"); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Label D = org.neo4j.graphdb.Label.label("D"); Label d = Label.label("D"); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Label E = org.neo4j.graphdb.Label.label("E"); Label e = Label.label("E"); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Label F = org.neo4j.graphdb.Label.label("F"); Label f = Label.label("F"); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.RelationshipType relType = org.neo4j.graphdb.RelationshipType.withName("TO"); RelationshipType relType = RelationshipType.withName("TO"); RecursiveSnowFlake(null, 0, 4, 5, new Label[] { a, b, c, d, e }, relType); Node a = GetNodeByLabel(a); using (ResourceIterator <Node> allE = GraphDb.findNodes(e)) { while (allE.MoveNext()) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Node e = allE.Current; Node e = allE.Current; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Node f = graphDb.createNode(F); Node f = GraphDb.createNode(f); f.CreateRelationshipTo(e, relType); } } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final CountingPathExpander countingPathExpander = new CountingPathExpander(org.neo4j.graphdb.PathExpanders.forTypeAndDirection(relType, org.neo4j.graphdb.Direction.OUTGOING)); CountingPathExpander countingPathExpander = new CountingPathExpander(this, PathExpanders.forTypeAndDirection(relType, Direction.OUTGOING)); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final ShortestPath shortestPath = new ShortestPath(Integer.MAX_VALUE, countingPathExpander, Integer.MAX_VALUE); ShortestPath shortestPath = new ShortestPath(int.MaxValue, countingPathExpander, int.MaxValue); using (ResourceIterator <Node> allF = GraphDb.findNodes(f)) { while (allF.MoveNext()) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.graphdb.Node f = allF.Current; Node f = allF.Current; shortestPath.FindAllPaths(a, f); } } assertEquals("There are 625 different end nodes. The algorithm should start one traversal for each such node. " + "That is 625*2 visited nodes if traversal is interrupted correctly.", 1250, countingPathExpander.NodesVisited.intValue()); }
internal override void RemoveOffendingDataInRunningTx(GraphDatabaseService db) { using (ResourceIterator <Node> nodes = Db.findNodes(label(KEY))) { while (nodes.MoveNext()) { nodes.Current.delete(); } } }
protected internal override Relationship fetchNextOrNull() { while (_pathIterator.MoveNext()) { Path path = _pathIterator.Current; if (path.Length() > 0) { return(path.LastRelationship()); } } return(null); }
private void DeleteHumans() { using (Transaction tx = _db.beginTx()) { using (ResourceIterator <Node> humans = _db.findNodes(_human)) { while (humans.MoveNext()) { humans.Current.delete(); } } tx.Success(); } }
public List <T> All() { string href = GetURI(); ResourcePage <T> page = new ResourcePage <T>(href); List <T> items = new List <T>(page.GetTotal()); ResourceIterator iterator = new ResourceIterator(href, page); while (iterator.MoveNext()) { object obj = iterator.Current; items.Add((T)obj); } return(items); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void useColumnAsOnEagerResult() public virtual void UseColumnAsOnEagerResult() { Result result = _database.execute("MATCH (n) RETURN n.c as c, n.b as b"); assertEquals(1, _testCursorContext.AdditionalAttempts); ResourceIterator <object> cValues = result.ColumnAs("c"); int rows = 0; while (cValues.MoveNext()) { cValues.Current; rows++; } assertEquals(2, rows); }
private bool ObjectExistsInIterable(Relationship rel, ResourceIterable <Relationship> allRels) { using (ResourceIterator <Relationship> resourceIterator = allRels.GetEnumerator()) { while (resourceIterator.MoveNext()) { Relationship iteratedRel = resourceIterator.Current; { if (rel.Equals(iteratedRel)) { return(true); } } } return(false); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldDoWholeTraversalInCorrectOrder() public virtual void ShouldDoWholeTraversalInCorrectOrder() { Node a = Graph.getNode("a"); Traverser traverser = (new MonoDirectionalTraversalDescription()).expand(_expander).order(_factory).uniqueness(_uniqueness).traverse(a); ResourceIterator <Path> iterator = traverser.GetEnumerator(); int i = 0; while (iterator.MoveNext()) { assertPath(iterator.Current, _expectedResult[i]); i++; } assertEquals(string.Format("Not all expected paths where traversed. Missing paths are {0}\n", Arrays.ToString(Arrays.copyOfRange(_expectedResult, i, _expectedResult.Length))), _expectedResult.Length, i); }
protected internal override void ProcessCache() { CacheAccess.clearCache(); long[] fields = new long[] { -1, 1, 0 }; CacheAccess_Client client = CacheAccess.client(); using (ResourceIterator <NodeRecord> nodeRecords = Nodes.GetEnumerator()) { while (nodeRecords.MoveNext()) { NodeRecord node = nodeRecords.Current; if (node.InUse()) { fields[CacheSlots_NextRelationship_Fields.SLOT_RELATIONSHIP_ID] = node.NextRel; client.PutToCache(node.Id, fields); } } } }
private void SetWeight(string start, string end, double weight) { Node startNode = Graph.getNode(start); Node endNode = Graph.getNode(end); ResourceIterable <Relationship> relationships = Iterables.asResourceIterable(startNode.Relationships); using (ResourceIterator <Relationship> resourceIterator = relationships.GetEnumerator()) { while (resourceIterator.MoveNext()) { Relationship rel = resourceIterator.Current; if (rel.GetOtherNode(startNode).Equals(endNode)) { rel.SetProperty("weight", weight); return; } } } throw new Exception("No relationship between nodes " + start + " and " + end); }
//JAVA TO C# CONVERTER TODO TASK: There is no .NET equivalent to the Java 'super' constraint: //ORIGINAL LINE: <R extends org.neo4j.kernel.impl.store.record.AbstractBaseRecord> void apply(RecordStore<R> store, org.neo4j.helpers.progress.ProgressListener progressListener, System.Predicate<? super R>... filters) throws FAILURE //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: internal virtual void Apply <R>(RecordStore <R> store, ProgressListener progressListener, params System.Predicate <object>[] filters) where R : Org.Neo4j.Kernel.impl.store.record.AbstractBaseRecord { ResourceIterable <R> iterable = Scanner.Scan(store, true, filters); using (ResourceIterator <R> scan = iterable.GetEnumerator()) { while (scan.MoveNext()) { R record = scan.Current; if (ShouldStop) { break; } store.Accept(this, record); progressListener.Set(record.Id); } progressListener.Done(); } }
protected internal virtual Node GetNodeWithName(string name) { ResourceIterable <Node> allNodes = GraphDb.AllNodes; using (ResourceIterator <Node> nodeIterator = allNodes.GetEnumerator()) { while (nodeIterator.MoveNext()) { Node node = nodeIterator.Current; { string nodeName = ( string )node.GetProperty("name", null); if (!string.ReferenceEquals(nodeName, null) && nodeName.Equals(name)) { return(node); } } } } return(null); }
public override Relationship GetSingleRelationship(RelationshipType type, Direction dir) { using (ResourceIterator <Relationship> rels = GetRelationships(dir, type).GetEnumerator()) { //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: if (!rels.hasNext()) { return(null); } //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: Relationship rel = rels.next(); while (rels.MoveNext()) { Relationship other = rels.Current; if (!other.Equals(rel)) { throw new NotFoundException("More than one relationship[" + type + ", " + dir + "] found for " + this); } } return(rel); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: protected void channelRead0(io.netty.channel.ChannelHandlerContext ctx, T request) throws Exception protected internal override void ChannelRead0(ChannelHandlerContext ctx, T request) { _log.debug("Handling request %s", request); StoreCopyFinishedResponse.Status responseStatus = StoreCopyFinishedResponse.Status.EUnknown; try { NeoStoreDataSource neoStoreDataSource = _dataSource.get(); if (!hasSameStoreId(request.expectedStoreId(), neoStoreDataSource)) { responseStatus = StoreCopyFinishedResponse.Status.EStoreIdMismatch; } else if (!isTransactionWithinReach(request.requiredTransactionId(), _checkPointerService)) { responseStatus = StoreCopyFinishedResponse.Status.ETooFarBehind; _checkPointerService.tryAsyncCheckpoint(e => _log.error("Failed to do a checkpoint that was invoked after a too far behind error on store copy request", e)); } else { File databaseDirectory = neoStoreDataSource.DatabaseLayout.databaseDirectory(); using (ResourceIterator <StoreFileMetadata> resourceIterator = Files(request, neoStoreDataSource)) { while (resourceIterator.MoveNext()) { StoreFileMetadata storeFileMetadata = resourceIterator.Current; StoreResource storeResource = new StoreResource(storeFileMetadata.File(), relativePath(databaseDirectory, storeFileMetadata.File()), storeFileMetadata.RecordSize(), _fs); _storeFileStreamingProtocol.stream(ctx, storeResource); } } responseStatus = StoreCopyFinishedResponse.Status.Success; } } finally { _storeFileStreamingProtocol.end(ctx, responseStatus); _protocol.expect(CatchupServerProtocol.State.MESSAGE_TYPE); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldNotThrowConcurrentModificationExceptionWhenUpdatingWhileIterating() public virtual void ShouldNotThrowConcurrentModificationExceptionWhenUpdatingWhileIterating() { // given GraphDatabaseService graph = DbRule.GraphDatabaseAPI; Label label = Label.label("Bird"); Node node1; Node node2; Node node3; using (Transaction tx = graph.BeginTx()) { node1 = graph.CreateNode(label); node2 = graph.CreateNode(label); tx.Success(); } // when ISet <Node> result = new HashSet <Node>(); using (Transaction tx = graph.BeginTx()) { node3 = graph.CreateNode(label); ResourceIterator <Node> iterator = graph.FindNodes(label); node3.RemoveLabel(label); graph.CreateNode(label); while (iterator.MoveNext()) { result.Add(iterator.Current); } tx.Success(); } // then does not throw and retains view from iterator creation time assertEquals(asSet(node1, node2, node3), result); }
/// <param name="node1Id"> </param> /// <param name="node2Id"> </param> /// <returns> One relationship between two given nodes, if there exists one, /// otherwise null. </returns> public virtual Relationship GetRelationship(string node1Id, string node2Id) { Node node1 = GetNode(node1Id); Node node2 = GetNode(node2Id); if (node1 == null || node2 == null) { return(null); } ResourceIterable <Relationship> relationships = Iterables.asResourceIterable(node1.Relationships); using (ResourceIterator <Relationship> resourceIterator = relationships.GetEnumerator()) { while (resourceIterator.MoveNext()) { Relationship relationship = resourceIterator.Current; if (relationship.GetOtherNode(node1).Equals(node2)) { return(relationship); } } } return(null); }
public override Node Next() { if (!HasNext()) { throw new NoSuchElementException(); } Node currentNode = Queue.extractMin(); CostType currentCost = MySeen[currentNode]; // Already done with this node? if (MyDistances.ContainsKey(currentNode)) { return(null); } if (outerInstance.LimitReached()) { return(null); } ++outerInstance.NumberOfNodesTraversed; MyDistances[currentNode] = currentCost; // TODO: remove from seen or not? probably not... because of path // detection // Check if we have found a better path CheckForPath(currentNode, currentCost, OtherSeen); // Found a path? (abort traversing from this node) if (OtherDistances.ContainsKey(currentNode)) { OneShortestPathHasBeenFound = true; } else { // Otherwise, follow all edges from this node foreach (RelationshipType costRelationType in outerInstance.CostRelationTypes) { ResourceIterable <Relationship> relationships = Iterables.asResourceIterable(currentNode.GetRelationships(costRelationType, Direction)); using (ResourceIterator <Relationship> iterator = relationships.GetEnumerator()) { while (iterator.MoveNext()) { Relationship relationship = iterator.Current; if (outerInstance.LimitReached()) { break; } ++outerInstance.NumberOfTraversedRelationShips; // Target node Node target = relationship.GetOtherNode(currentNode); if (OtherDistances.ContainsKey(target)) { continue; } // Find out if an eventual path would go in the opposite // direction of the edge bool backwardsEdge = relationship.EndNode.Equals(currentNode) ^ Backwards; CostType newCost = outerInstance.CostAccumulator.addCosts(currentCost, outerInstance.CostEvaluator.getCost(relationship, backwardsEdge ? Direction.INCOMING : Direction.OUTGOING)); // Already done with target node? if (MyDistances.ContainsKey(target)) { // Have we found a better cost for a node which is // already // calculated? if (outerInstance.CostComparator.Compare(MyDistances[target], newCost) > 0) { throw new Exception("Cycle with negative costs found."); } // Equally good path found? else if (outerInstance.CalculateAllShortestPaths && outerInstance.CostComparator.Compare(MyDistances[target], newCost) == 0) { // Put it in predecessors IList <Relationship> myPredecessors = Predecessors[currentNode]; // Dont do it if this relation is already in // predecessors (other direction) if (myPredecessors == null || !myPredecessors.Contains(relationship)) { IList <Relationship> predList = Predecessors[target]; if (predList == null) { // This only happens if we get back to // the // start node, which is just bogus } else { predList.Add(relationship); } } } continue; } // Have we found a better cost for this node? if (!MySeen.ContainsKey(target) || outerInstance.CostComparator.Compare(MySeen[target], newCost) > 0) { // Put it in the queue if (!MySeen.ContainsKey(target)) { Queue.insertValue(target, newCost); } // or update the entry. (It is important to keep // these // cases apart to limit the size of the queue) else { Queue.decreaseValue(target, newCost); } // Update it MySeen[target] = newCost; // Put it in predecessors IList <Relationship> predList = new LinkedList <Relationship>(); predList.Add(relationship); Predecessors[target] = predList; } // Have we found an equal cost for (additional path to) // this // node? else if (outerInstance.CalculateAllShortestPaths && outerInstance.CostComparator.Compare(MySeen[target], newCost) == 0) { // Put it in predecessors IList <Relationship> predList = Predecessors[target]; predList.Add(relationship); } } } } } // Check how far we need to continue when searching for all shortest // paths if (outerInstance.CalculateAllShortestPaths && OneShortestPathHasBeenFound) { // If we cannot continue or continuation would only find more // expensive paths: conclude that all shortest paths have been // found. AllShortestPathsHasBeenFound = Queue.Empty || outerInstance.CostComparator.Compare(MySeen[Queue.peek()], currentCost) > 0; } return(currentNode); }
public virtual GraphResult BuildSchemaGraph() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.Map<String,VirtualNodeHack> nodes = new java.util.HashMap<>(); IDictionary <string, VirtualNodeHack> nodes = new Dictionary <string, VirtualNodeHack>(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.Map<String,java.util.Set<VirtualRelationshipHack>> relationships = new java.util.HashMap<>(); IDictionary <string, ISet <VirtualRelationshipHack> > relationships = new Dictionary <string, ISet <VirtualRelationshipHack> >(); using (Statement statement = _kernelTransaction.acquireStatement()) { Read dataRead = _kernelTransaction.dataRead(); TokenRead tokenRead = _kernelTransaction.tokenRead(); TokenNameLookup tokenNameLookup = new SilentTokenNameLookup(tokenRead); SchemaRead schemaRead = _kernelTransaction.schemaRead(); using (Transaction transaction = _graphDatabaseAPI.beginTx()) { // add all labelsInDatabase using (ResourceIterator <Label> labelsInDatabase = _graphDatabaseAPI.AllLabelsInUse.GetEnumerator()) { while (labelsInDatabase.MoveNext()) { Label label = labelsInDatabase.Current; int labelId = tokenRead.NodeLabel(label.Name()); IDictionary <string, object> properties = new Dictionary <string, object>(); IEnumerator <IndexReference> indexReferences = schemaRead.IndexesGetForLabel(labelId); List <string> indexes = new List <string>(); while (indexReferences.MoveNext()) { IndexReference index = indexReferences.Current; if (!index.Unique) { string[] propertyNames = PropertyNameUtils.getPropertyKeys(tokenNameLookup, index.Properties()); indexes.Add(string.join(",", propertyNames)); } } properties["indexes"] = indexes; IEnumerator <ConstraintDescriptor> nodePropertyConstraintIterator = schemaRead.ConstraintsGetForLabel(labelId); List <string> constraints = new List <string>(); while (nodePropertyConstraintIterator.MoveNext()) { ConstraintDescriptor constraint = nodePropertyConstraintIterator.Current; constraints.Add(constraint.PrettyPrint(tokenNameLookup)); } properties["constraints"] = constraints; GetOrCreateLabel(label.Name(), properties, nodes); } } //add all relationships using (ResourceIterator <RelationshipType> relationshipTypeIterator = _graphDatabaseAPI.AllRelationshipTypesInUse.GetEnumerator()) { while (relationshipTypeIterator.MoveNext()) { RelationshipType relationshipType = relationshipTypeIterator.Current; string relationshipTypeGetName = relationshipType.Name(); int relId = tokenRead.RelationshipType(relationshipTypeGetName); using (ResourceIterator <Label> labelsInUse = _graphDatabaseAPI.AllLabelsInUse.GetEnumerator()) { IList <VirtualNodeHack> startNodes = new LinkedList <VirtualNodeHack>(); IList <VirtualNodeHack> endNodes = new LinkedList <VirtualNodeHack>(); while (labelsInUse.MoveNext()) { Label labelToken = labelsInUse.Current; string labelName = labelToken.Name(); IDictionary <string, object> properties = new Dictionary <string, object>(); VirtualNodeHack node = GetOrCreateLabel(labelName, properties, nodes); int labelId = tokenRead.NodeLabel(labelName); if (dataRead.CountsForRelationship(labelId, relId, [email protected]_Fields.ANY_LABEL) > 0) { startNodes.Add(node); } if (dataRead.CountsForRelationship([email protected]_Fields.ANY_LABEL, relId, labelId) > 0) { endNodes.Add(node); } } foreach (VirtualNodeHack startNode in startNodes) { foreach (VirtualNodeHack endNode in endNodes) { AddRelationship(startNode, endNode, relationshipTypeGetName, relationships); } } } } } transaction.Success(); return(GetGraphResult(nodes, relationships)); } } }