Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
600
{ @Override protected boolean includePath( Path path, TraversalBranch startPath, TraversalBranch endPath ) { assertEquals( 0, startPath.state() ); assertEquals( 10, endPath.state() ); return true; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestBidirectionalTraversal.java
601
{ @Override public BranchCollisionDetector create( Evaluator evaluator ) { return new StandardBranchCollisionDetector( null ) { @Override protected boolean includePath( Path path, TraversalBranch startPath, TraversalBranch endPath ) { assertEquals( 0, startPath.state() ); assertEquals( 10, endPath.state() ); return true; } }; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestBidirectionalTraversal.java
602
public class TestBidirectionalTraversal extends TraversalTestBase { RelationshipType to = withName( "TO" ); private Transaction tx; @Before public void init() { tx = beginTx(); } @After public void tearDown() { tx.finish(); } @Test( expected = IllegalArgumentException.class ) public void bothSidesMustHaveSameUniqueness() throws Exception { createGraph( "A TO B" ); count( bidirectionalTraversal() .startSide( traversal().uniqueness( Uniqueness.NODE_GLOBAL ) ) .endSide( traversal().uniqueness( Uniqueness.RELATIONSHIP_GLOBAL ) ) .traverse( getNodeWithName( "A" ), getNodeWithName( "B" ) ) ); } @Test public void pathsForOneDirection() throws Exception { /* * (a)-->(b)==>(c)-->(d) * ^ / * \--(f)<--(e)<-/ */ createGraph( "a TO b", "b TO c", "c TO d", "d TO e", "e TO f", "f TO a" ); PathExpander<Void> expander = Traversal.pathExpanderForTypes( to, OUTGOING ); expectPaths( bidirectionalTraversal() .mirroredSides( traversal().uniqueness( NODE_PATH ).expand( expander ) ) .traverse( getNodeWithName( "a" ), getNodeWithName( "f" ) ), "a,b,c,d,e,f" ); expectPaths( bidirectionalTraversal() .mirroredSides( traversal().uniqueness( RELATIONSHIP_PATH ).expand( expander ) ) .traverse( getNodeWithName( "a" ), getNodeWithName( "f" ) ), "a,b,c,d,e,f", "a,b,c,d,e,f" ); } @Test public void collisionEvaluator() throws Exception { /* * (d)-->(e)-- * ^ | \ * | v v * (a)-->(b)<--(f) * | ^ * v / * (c)-/ */ createGraph( "a TO b", "a TO c", "c TO b", "a TO d", "d TO e", "e TO b", "e TO f", "f TO b" ); PathExpander<Void> expander = pathExpanderForTypes( to, OUTGOING ); BidirectionalTraversalDescription traversal = bidirectionalTraversal() .mirroredSides( traversal().uniqueness( NODE_PATH ).expand( expander ) ); expectPaths( traversal .collisionEvaluator( includeIfContainsAll( getNodeWithName( "e" ) ) ) .traverse( getNodeWithName( "a" ), getNodeWithName( "b" ) ), "a,d,e,b", "a,d,e,f,b" ); expectPaths( traversal .collisionEvaluator( includeIfContainsAll( getNodeWithName( "e" ), getNodeWithName( "f" ) ) ) .traverse( getNodeWithName( "a" ), getNodeWithName( "b" ) ), "a,d,e,f,b" ); } @Test public void multipleCollisionEvaluators() throws Exception { /* * (g) * ^ \ * / v * (a)-->(b) (c) * | --^ ^ * v / | * (d)-->(e)----(f) */ createGraph( "a TO b", "b TO g", "g TO c", "a TO d", "d TO e", "e TO c", "e TO f", "f TO c" ); expectPaths( bidirectionalTraversal().mirroredSides( traversal().uniqueness( NODE_PATH ) ) .collisionEvaluator( Evaluators.atDepth( 3 ) ) .collisionEvaluator( Evaluators.includeIfContainsAll( getNodeWithName( "e" ) ) ) .traverse( getNodeWithName( "a" ), getNodeWithName( "c" ) ), "a,d,e,c" ); } @Test public void multipleStartAndEndNodes() throws Exception { /* * (a)--\ -->(f) * v / * (b)-->(d)<--(e)-->(g) * ^ * (c)--/ */ createGraph( "a TO d", "b TO d", "c TO d", "e TO d", "e TO f", "e TO g" ); PathExpander<Void> expander = PathExpanderBuilder.<Void>empty().add( to ).build(); TraversalDescription side = traversal().uniqueness( NODE_PATH ).expand( expander ); expectPaths( bidirectionalTraversal().mirroredSides( side ).traverse( asList( getNodeWithName( "a" ), getNodeWithName( "b" ), getNodeWithName( "c" ) ), asList( getNodeWithName( "f" ), getNodeWithName( "g" ) ) ), "a,d,e,f", "a,d,e,g", "b,d,e,f", "b,d,e,g", "c,d,e,f", "c,d,e,g" ); } @Test public void ensureCorrectPathEntitiesInShortPath() throws Exception { /* * (a)-->(b) */ createGraph( "a TO b" ); Node a = getNodeWithName( "a" ); Node b = getNodeWithName( "b" ); Relationship r = a.getSingleRelationship( to, OUTGOING ); Path path = single( bidirectionalTraversal() .mirroredSides( traversal().relationships( to, OUTGOING ).uniqueness( NODE_PATH ) ) .collisionEvaluator( Evaluators.atDepth( 1 ) ) .sideSelector( SideSelectorPolicies.LEVEL, 1 ) .traverse( a, b ) ); assertContainsInOrder( path.nodes(), a, b ); assertContainsInOrder( path.reverseNodes(), b, a ); assertContainsInOrder( path.relationships(), r ); assertContainsInOrder( path.reverseRelationships(), r ); assertContainsInOrder( path, a, r, b ); assertEquals( a, path.startNode() ); assertEquals( b, path.endNode() ); assertEquals( r, path.lastRelationship() ); } @Test public void mirroredTraversalReversesInitialState() throws Exception { /* * (a)-->(b)-->(c)-->(d) */ createGraph( "a TO b", "b TO c", "c TO d" ); BranchCollisionPolicy collisionPolicy = new BranchCollisionPolicy() { @Override public BranchCollisionDetector create( Evaluator evaluator ) { return new StandardBranchCollisionDetector( null ) { @Override protected boolean includePath( Path path, TraversalBranch startPath, TraversalBranch endPath ) { assertEquals( 0, startPath.state() ); assertEquals( 10, endPath.state() ); return true; } }; } }; count( bidirectionalTraversal() // Just make up a number bigger than the path length (in this case 10) so that we can assert it in // the collision policy later .mirroredSides( traversal( NODE_PATH ).expand( PathExpanders.<Integer>forType( to ), new InitialBranchState.State<Integer>( 0, 10 ) ) ) .collisionPolicy( collisionPolicy ) .traverse( getNodeWithName( "a" ), getNodeWithName( "d" ) ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestBidirectionalTraversal.java
603
class StartNodeTraversalBranch extends TraversalBranchWithState { private final InitialBranchState initialState; StartNodeTraversalBranch( TraversalContext context, TraversalBranch parent, Node source, InitialBranchState initialState ) { super( parent, source, initialState ); this.initialState = initialState; evaluate( context ); context.isUniqueFirst( this ); } @Override public TraversalBranch next( PathExpander expander, TraversalContext metadata ) { if ( !hasExpandedRelationships() ) { expandRelationships( expander ); return this; } return super.next( expander, metadata ); } @Override protected TraversalBranch newNextBranch( Node node, Relationship relationship ) { return initialState != InitialBranchState.NO_STATE ? new TraversalBranchWithState( this, 1, node, relationship, stateForChildren ) : new TraversalBranchImpl( this, 1, node, relationship ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_StartNodeTraversalBranch.java
604
public class SpecificDepthTraversalTest extends TraversalTestBase { private Transaction tx; @Before public void createTheGraph() { createGraph( "0 ROOT 1", "1 KNOWS 2", "2 KNOWS 3", "2 KNOWS 4", "4 KNOWS 5", "5 KNOWS 6", "3 KNOWS 1" ); tx = beginTx(); } @After public void tearDown() { tx.finish(); } @Test public void shouldGetStartNodeOnDepthZero() { TraversalDescription description = Traversal.description().evaluator( Evaluators.atDepth( 0 ) ); expectNodes( description.traverse( getNodeWithName( "6" ) ), "6" ); } @Test public void shouldGetCorrectNodesFromToDepthOne() { TraversalDescription description = Traversal.description().evaluator( Evaluators.fromDepth( 1 ) ).evaluator( Evaluators.toDepth( 1 ) ); expectNodes( description.traverse( getNodeWithName( "6" ) ), "5" ); } @Test public void shouldGetCorrectNodeAtDepthOne() { TraversalDescription description = Traversal.description().evaluator( Evaluators.atDepth( 1 ) ); expectNodes( description.traverse( getNodeWithName( "6" ) ), "5" ); } @Test public void shouldGetCorrectNodesAtDepthZero() { TraversalDescription description = Traversal.description().evaluator( Evaluators.fromDepth( 0 ) ).evaluator( Evaluators.toDepth( 0 ) ); expectNodes( description.traverse( getNodeWithName( "6" ) ), "6" ); } @Test public void shouldGetStartNodeWhenFromToIsZeroBreadthFirst() { TraversalDescription description = Traversal.description().breadthFirst() .evaluator(Evaluators.fromDepth(0)).evaluator(Evaluators.toDepth(0)); expectNodes( description.traverse( getNodeWithName( "0" ) ), "0" ); } @Test public void shouldGetStartNodeWhenAtIsZeroBreadthFirst() { TraversalDescription description = Traversal.description().breadthFirst() .evaluator(Evaluators.atDepth(0)); expectNodes( description.traverse( getNodeWithName( "2" ) ), "2" ); } @Test public void shouldGetSecondNodeWhenFromToIsTwoBreadthFirst() { TraversalDescription description = Traversal.description().breadthFirst() .evaluator(Evaluators.fromDepth(2)).evaluator(Evaluators.toDepth(2)); expectNodes( description.traverse( getNodeWithName( "5" ) ), "2" ); } @Test public void shouldGetSecondNodeWhenAtIsTwoBreadthFirst() { TraversalDescription description = Traversal.description().breadthFirst() .evaluator( Evaluators.atDepth( 2 ) ); expectNodes( description.traverse( getNodeWithName( "6" ) ), "4" ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_SpecificDepthTraversalTest.java
605
class SortingTraverserIterator extends PrefetchingResourceIterator<Path> implements TraverserIterator { private final Comparator<? super Path> sortingStrategy; private final MonoDirectionalTraverserIterator source; private final Resource resource; private Iterator<Path> sortedResultIterator; SortingTraverserIterator( Resource resource, Comparator<? super Path> sortingStrategy, MonoDirectionalTraverserIterator source ) { this.resource = resource; this.sortingStrategy = sortingStrategy; this.source = source; } @Override public int getNumberOfPathsReturned() { return source.getNumberOfPathsReturned(); } @Override public int getNumberOfRelationshipsTraversed() { return source.getNumberOfRelationshipsTraversed(); } @Override public void relationshipTraversed() { source.relationshipTraversed(); } @Override public void unnecessaryRelationshipTraversed() { source.unnecessaryRelationshipTraversed(); } @Override public boolean isUniqueFirst( TraversalBranch branch ) { return source.isUniqueFirst( branch ); } @Override public boolean isUnique( TraversalBranch branch ) { return source.isUnique( branch ); } @Override public Evaluation evaluate( TraversalBranch branch, BranchState state ) { return source.evaluate( branch, state ); } @Override protected Path fetchNextOrNull() { if ( sortedResultIterator == null ) { sortedResultIterator = fetchAndSortResult(); } return sortedResultIterator.hasNext() ? sortedResultIterator.next() : null; } private Iterator<Path> fetchAndSortResult() { List<Path> result = new ArrayList<>(); while ( source.hasNext() ) { result.add( source.next() ); } Collections.sort( result, sortingStrategy ); return result.iterator(); } @Override public void close() { resource.close(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_SortingTraverserIterator.java
606
public class SmallestGraphEverTest extends TraversalTestBase { @Before public void setup() { createGraph( "1 TO 2" ); } @Test public void testUnrestrictedTraversalCanFinishDepthFirst() throws Exception { execute( traversal().depthFirst(), Uniqueness.NONE ); } @Test public void testUnrestrictedTraversalCanFinishBreadthFirst() throws Exception { execute( traversal().breadthFirst(), Uniqueness.NONE ); } @Test public void testNodeGlobalTraversalCanFinishDepthFirst() throws Exception { execute( traversal().depthFirst(), Uniqueness.NODE_GLOBAL ); } @Test public void testNodeGlobalTraversalCanFinishBreadthFirst() throws Exception { execute( traversal().breadthFirst(), Uniqueness.NODE_GLOBAL ); } @Test public void testRelationshipGlobalTraversalCanFinishDepthFirst() throws Exception { execute( traversal().depthFirst(), Uniqueness.RELATIONSHIP_GLOBAL ); } @Test public void testRelationshipGlobalTraversalCanFinishBreadthFirst() throws Exception { execute( traversal().breadthFirst(), Uniqueness.RELATIONSHIP_GLOBAL ); } @Test public void testNodePathTraversalCanFinishDepthFirst() throws Exception { execute( traversal().depthFirst(), Uniqueness.NODE_PATH ); } @Test public void testNodePathTraversalCanFinishBreadthFirst() throws Exception { execute( traversal().breadthFirst(), Uniqueness.NODE_PATH ); } @Test public void testRelationshipPathTraversalCanFinishDepthFirst() throws Exception { execute( traversal().depthFirst(), Uniqueness.RELATIONSHIP_PATH ); } @Test public void testRelationshipPathTraversalCanFinishBreadthFirst() throws Exception { execute( traversal().breadthFirst(), Uniqueness.RELATIONSHIP_PATH ); } @Test public void testNodeRecentTraversalCanFinishDepthFirst() throws Exception { execute( traversal().depthFirst(), Uniqueness.NODE_RECENT ); } @Test public void testNodeRecentTraversalCanFinishBreadthFirst() throws Exception { execute( traversal().breadthFirst(), Uniqueness.NODE_RECENT ); } @Test public void testRelationshipRecentTraversalCanFinishDepthFirst() throws Exception { execute( traversal().depthFirst(), Uniqueness.RELATIONSHIP_RECENT ); } @Test public void testRelationshipRecentTraversalCanFinishBreadthFirst() throws Exception { execute( traversal().breadthFirst(), Uniqueness.RELATIONSHIP_RECENT ); } private void execute( TraversalDescription traversal, Uniqueness uniqueness ) { Transaction transaction = beginTx(); try { Traverser traverser = traversal.uniqueness( uniqueness ).traverse( node( "1" ) ); assertFalse( "empty traversal", count( traverser ) == 0 ); } finally { transaction.finish(); } } @Test public void testTraverseRelationshipsWithStartNodeNotIncluded() throws Exception { Transaction transaction = beginTx(); try { TraversalDescription traversal = traversal().evaluator( excludeStartPosition() ); assertEquals( 1, count( traversal.traverse( node( "1" ) ).relationships() ) ); } finally { transaction.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_SmallestGraphEverTest.java
607
private static class TraverserImpl implements org.neo4j.graphdb.Traverser, Iterator<Node> { private TraversalPosition currentPos; private Iterator<Path> iter; private int count; public TraversalPosition currentPosition() { return currentPos; } public int numberOfNodesReturned() { return count; } public Collection<Node> getAllNodes() { List<Node> result = new ArrayList<Node>(); for ( Node node : this ) { result.add( node ); } return result; } public Iterator<Node> iterator() { return this; } public boolean hasNext() { return iter.hasNext(); } public Node next() { currentPos = new PositionImpl( this, iter.next() ); count++; return currentPos.currentNode(); } public void remove() { throw new UnsupportedOperationException(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_OldTraverserWrapper.java
608
private static class Pruner implements Evaluator { private final TraverserImpl traverser; private final StopEvaluator evaluator; Pruner( TraverserImpl traverser, StopEvaluator stopEvaluator ) { this.traverser = traverser; this.evaluator = stopEvaluator; } @Override public Evaluation evaluate( Path path ) { return Evaluation.ofContinues( !evaluator.isStopNode( new PositionImpl( traverser, path ) ) ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_OldTraverserWrapper.java
609
private static class PositionImpl implements TraversalPosition { private final Path position; private final int count; PositionImpl( TraverserImpl traverser, Path position ) { this.position = position; this.count = traverser.numberOfNodesReturned(); } public Node currentNode() { return position.endNode(); } public int depth() { return position.length(); } public boolean isStartNode() { return position.length() == 0; } public boolean notStartNode() { return !isStartNode(); } public Relationship lastRelationshipTraversed() { return position.lastRelationship(); } public Node previousNode() { return position.lastRelationship().getOtherNode( position.endNode() ); } public int returnedNodesCount() { return count; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_OldTraverserWrapper.java
610
private static class Filter implements Evaluator { private final TraverserImpl traverser; private final ReturnableEvaluator evaluator; Filter( TraverserImpl traverser, ReturnableEvaluator returnableEvaluator ) { this.traverser = traverser; this.evaluator = returnableEvaluator; } @Override public Evaluation evaluate( Path path ) { return Evaluation.ofIncludes( evaluator.isReturnableNode( new PositionImpl( traverser, path ) ) ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_OldTraverserWrapper.java
611
public class OldTraverserWrapper { private static class TraverserImpl implements org.neo4j.graphdb.Traverser, Iterator<Node> { private TraversalPosition currentPos; private Iterator<Path> iter; private int count; public TraversalPosition currentPosition() { return currentPos; } public int numberOfNodesReturned() { return count; } public Collection<Node> getAllNodes() { List<Node> result = new ArrayList<Node>(); for ( Node node : this ) { result.add( node ); } return result; } public Iterator<Node> iterator() { return this; } public boolean hasNext() { return iter.hasNext(); } public Node next() { currentPos = new PositionImpl( this, iter.next() ); count++; return currentPos.currentNode(); } public void remove() { throw new UnsupportedOperationException(); } } private static class PositionImpl implements TraversalPosition { private final Path position; private final int count; PositionImpl( TraverserImpl traverser, Path position ) { this.position = position; this.count = traverser.numberOfNodesReturned(); } public Node currentNode() { return position.endNode(); } public int depth() { return position.length(); } public boolean isStartNode() { return position.length() == 0; } public boolean notStartNode() { return !isStartNode(); } public Relationship lastRelationshipTraversed() { return position.lastRelationship(); } public Node previousNode() { return position.lastRelationship().getOtherNode( position.endNode() ); } public int returnedNodesCount() { return count; } } private static void assertNotNull( Object object, String message ) { if ( object == null ) { throw new IllegalArgumentException( "Null " + message ); } } private static final TraversalDescription BASE_DESCRIPTION = Traversal.traversal().uniqueness( Uniqueness.NODE_GLOBAL ); public static org.neo4j.graphdb.Traverser traverse( Node node, Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, Object... relationshipTypesAndDirections ) { assertNotNull( traversalOrder, "order" ); assertNotNull( stopEvaluator, "stop evaluator" ); assertNotNull( returnableEvaluator, "returnable evaluator" ); if ( relationshipTypesAndDirections.length % 2 != 0 || relationshipTypesAndDirections.length == 0 ) { throw new IllegalArgumentException(); } TraverserImpl result = new TraverserImpl(); TraversalDescription description = traversal( result, traversalOrder, stopEvaluator, returnableEvaluator ); description = description.expand( toExpander( relationshipTypesAndDirections ) ); result.iter = description.traverse( node ).iterator(); return result; } private static RelationshipExpander toExpander( Object[] relationshipTypesAndDirections ) { Stack<Object[]> entries = new Stack<Object[]>(); for ( int i = 0; i < relationshipTypesAndDirections.length; i += 2 ) { Object relType = relationshipTypesAndDirections[i]; if ( relType == null ) { throw new IllegalArgumentException( "Null relationship type at " + i ); } if ( !(relType instanceof RelationshipType) ) { throw new IllegalArgumentException( "Expected RelationshipType at var args pos " + i + ", found " + relType ); } Object direction = relationshipTypesAndDirections[i+1]; if ( direction == null ) { throw new IllegalArgumentException( "Null direction at " + (i+1) ); } if ( !(direction instanceof Direction) ) { throw new IllegalArgumentException( "Expected Direction at var args pos " + (i+1) + ", found " + direction ); } entries.push( new Object[] { relType, direction } ); } OrderedByTypeExpander expander = new OrderedByTypeExpander(); while ( !entries.isEmpty() ) { Object[] entry = entries.pop(); expander = (OrderedByTypeExpander) expander.add( (RelationshipType) entry[0], (Direction) entry[1] ); } return expander; } private static TraversalDescription traversal( TraverserImpl traverser, Order order, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator ) { TraversalDescription description = BASE_DESCRIPTION; switch ( order ) { case BREADTH_FIRST: description = description.breadthFirst(); break; case DEPTH_FIRST: description = description.depthFirst(); break; default: throw new IllegalArgumentException( "Onsupported traversal order: " + order ); } description = description.evaluator( new Pruner( traverser, stopEvaluator ) ); description = description.evaluator( new Filter( traverser, returnableEvaluator ) ); return description; } private static class Pruner implements Evaluator { private final TraverserImpl traverser; private final StopEvaluator evaluator; Pruner( TraverserImpl traverser, StopEvaluator stopEvaluator ) { this.traverser = traverser; this.evaluator = stopEvaluator; } @Override public Evaluation evaluate( Path path ) { return Evaluation.ofContinues( !evaluator.isStopNode( new PositionImpl( traverser, path ) ) ); } } private static class Filter implements Evaluator { private final TraverserImpl traverser; private final ReturnableEvaluator evaluator; Filter( TraverserImpl traverser, ReturnableEvaluator returnableEvaluator ) { this.traverser = traverser; this.evaluator = returnableEvaluator; } @Override public Evaluation evaluate( Path path ) { return Evaluation.ofIncludes( evaluator.isReturnableNode( new PositionImpl( traverser, path ) ) ); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_OldTraverserWrapper.java
612
public class MultiEvaluator<STATE> extends PathEvaluator.Adapter<STATE> { private final PathEvaluator[] evaluators; MultiEvaluator( PathEvaluator... evaluators ) { this.evaluators = evaluators; } /** * Returns whether or not the {@code position} is to be included and also * if it's going to be continued. * * The include/exclude part of the returned {@link Evaluation} will be * {@code include} if all of the internal evaluators think it's going to be * included, otherwise it will be excluded. * * The continue/prune part of the returned {@link Evaluation} will be * {@code continue} if all of the internal evaluators think it's going to be * continued, otherwise it will be pruned. * * @param position the {@link Path} to evaluate. * @see Evaluator */ public Evaluation evaluate( Path position, BranchState<STATE> state ) { boolean includes = true; boolean continues = true; for ( PathEvaluator<STATE> evaluator : this.evaluators ) { Evaluation bla = evaluator.evaluate( position, state ); if ( !bla.includes() ) { includes = false; if ( !continues ) return Evaluation.EXCLUDE_AND_PRUNE; } if ( !bla.continues() ) { continues = false; if ( !includes ) return Evaluation.EXCLUDE_AND_PRUNE; } } return Evaluation.of( includes, continues ); } /** * Adds {@code evaluator} to the list of evaluators wrapped by the returned * evaluator. A new {@link MultiEvaluator} instance additionally containing * the supplied {@code evaluator} is returned and this instance will be * left intact. * * @param evaluator the {@link Evaluator} to add to this multi evaluator. * @return a new instance containing the current list of evaluator plus * the supplied one. */ public MultiEvaluator<STATE> add( PathEvaluator<STATE> evaluator ) { PathEvaluator[] newArray = new PathEvaluator[this.evaluators.length+1]; System.arraycopy( this.evaluators, 0, newArray, 0, this.evaluators.length ); newArray[newArray.length-1] = evaluator; return new MultiEvaluator<STATE>( newArray ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_MultiEvaluator.java
613
public class TestEvaluators extends TraversalTestBase { private static enum Types implements RelationshipType { A,B,C; } private Transaction tx; @Before public void createGraph() { /* * (a)--[A]->(b)--[B]-->(c)--[B]-->(d)--[C]-->(e)--[A]-->(j) * \ | * [B] [C]-->(h)--[B]-->(i)--[C]-->(k) * \ * v * (f)--[C]-->(g) */ createGraph( "a A b", "b B c", "c B d", "d C e", "e A j", "b C h", "h B i", "i C k", "a B f", "f C g" ); tx = beginTx(); } @After public void tearDown() { tx.finish(); } @Test public void lastRelationshipTypeEvaluator() throws Exception { Node a = getNodeWithName( "a" ); expectPaths( traversal().evaluator( lastRelationshipTypeIs( INCLUDE_AND_PRUNE, EXCLUDE_AND_CONTINUE, Types.C ) ).traverse( a ), "a,b,c,d,e", "a,f,g", "a,b,h" ); expectPaths( traversal().evaluator( lastRelationshipTypeIs( INCLUDE_AND_CONTINUE, EXCLUDE_AND_CONTINUE, Types.C ) ).traverse( a ), "a,b,c,d,e", "a,f,g", "a,b,h", "a,b,h,i,k" ); } @Test public void endNodeIs() { Node a = getNodeWithName( "a" ); Node c = getNodeWithName( "c" ); Node h = getNodeWithName( "h" ); Node g = getNodeWithName( "g" ); expectPaths( description().evaluator( includeWhereEndNodeIs( c, h, g ) ).traverse( a ), "a,b,c", "a,b,h", "a,f,g" ); expectPaths( description().evaluator( includeWhereEndNodeIs( g ) ).traverse( a ), "a,f,g" ); } @Test public void depths() throws Exception { Node a = getNodeWithName( "a" ); expectPaths( traversal().evaluator( Evaluators.atDepth( 1 ) ).traverse( a ), "a,b", "a,f" ); expectPaths( traversal().evaluator( Evaluators.fromDepth( 2 ) ).traverse( a ), "a,f,g", "a,b,h", "a,b,h,i", "a,b,h,i,k", "a,b,c", "a,b,c,d", "a,b,c,d,e", "a,b,c,d,e,j" ); expectPaths( traversal().evaluator( Evaluators.toDepth( 2 ) ).traverse( a ), "a", "a,b", "a,b,c", "a,b,h", "a,f", "a,f,g" ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestEvaluators.java
614
public class TestMultiPruneEvaluators extends TraversalTestBase { @Before public void setupGraph() { createGraph( "a to b", "a to c", "a to d", "a to e", "b to f", "b to g", "b to h", "c to i", "d to j", "d to k", "d to l", "e to m", "e to n", "k to o", "k to p", "k to q", "k to r" ); } @Test public void testMaxDepthAndCustomPruneEvaluatorCombined() { Evaluator lessThanThreeRels = new Evaluator() { public Evaluation evaluate( Path path ) { return count( path.endNode().getRelationships( Direction.OUTGOING ).iterator() ) < 3 ? Evaluation.INCLUDE_AND_PRUNE : Evaluation.INCLUDE_AND_CONTINUE; } }; TraversalDescription description = traversal().evaluator( Evaluators.all() ) .evaluator( toDepth( 1 ) ).evaluator( lessThanThreeRels ); Set<String> expectedNodes = new HashSet<String>( asList( "a", "b", "c", "d", "e" ) ); Transaction tx = beginTx(); for ( Path position : description.traverse( node( "a" ) ) ) { String name = (String) position.endNode().getProperty( "name" ); assertTrue( name + " shouldn't have been returned", expectedNodes.remove( name ) ); } tx.success(); tx.finish(); assertTrue( expectedNodes.isEmpty() ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestMultiPruneEvaluators.java
615
{ public Evaluation evaluate( Path path ) { return count( path.endNode().getRelationships( Direction.OUTGOING ).iterator() ) < 3 ? Evaluation.INCLUDE_AND_PRUNE : Evaluation.INCLUDE_AND_CONTINUE; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestMultiPruneEvaluators.java
616
{ @Override public boolean isReturnableNode( TraversalPosition pos ) { try { Node node = pos.currentNode(); String key = "node.test.id"; String nodeId = (String) node.getProperty( key ); return nodeId.equals( "2" ); } catch ( Exception e ) { return false; } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversal.java
617
{ @Override public Evaluation evaluate( Path path ) { return Evaluation.ofIncludes( path.endNode().equals( e ) ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversalWithLoops.java
618
public class TestTraversalWithLoops extends TraversalTestBase { @Test public void traverseThroughNodeWithLoop() throws Exception { /* * (a)-->(b)-->(c)-->(d)-->(e) * / \ / \ * \__/ \__/ */ createGraph( "a TO b", "b TO c", "c TO c", "c TO d", "d TO d", "d TO e" ); Transaction tx = beginTx(); try { Node a = getNodeWithName( "a" ); final Node e = getNodeWithName( "e" ); Evaluator onlyEndNode = new Evaluator() { @Override public Evaluation evaluate( Path path ) { return Evaluation.ofIncludes( path.endNode().equals( e ) ); } }; TraversalDescription basicTraverser = traversal().evaluator( onlyEndNode ); expectPaths( basicTraverser.traverse( a ), "a,b,c,d,e" ); expectPaths( basicTraverser.uniqueness( Uniqueness.RELATIONSHIP_PATH ).traverse( a ), "a,b,c,d,e", "a,b,c,c,d,e", "a,b,c,d,d,e", "a,b,c,c,d,d,e" ); tx.success(); } finally { tx.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversalWithLoops.java
619
{ @Override public boolean isStopNode( TraversalPosition position ) { // Stop when we got here by traversing a clone relationship Relationship rel = position.lastRelationshipTraversed(); return rel != null && rel.isType( MyRelTypes.TEST_TRAVERSAL ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversal.java
620
{ @Override public boolean isReturnableNode( TraversalPosition position ) { // Return nodes until we've reached 5 nodes or end of graph return position.returnedNodesCount() < 5; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversal.java
621
{ @Override public boolean isStopNode( TraversalPosition position ) { // Stop traversing when we've returned 5 nodes return position.returnedNodesCount() >= 5; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversal.java
622
{ @Override public boolean isStopNode( TraversalPosition position ) { return position.depth() >= 2; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversal.java
623
{ @Override public boolean isStopNode( TraversalPosition position ) { try { Node node = position.previousNode(); String nodeId = (String) node.getProperty( "node.test.id" ); return nodeId.equals( "1" ); } catch ( Exception e ) { return false; } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversal.java
624
{ @Override public boolean isStopNode( TraversalPosition position ) { try { Node node = position.currentNode(); String nodeId = (String) node.getProperty( "node.test.id" ); return nodeId.equals( "5" ) || nodeId.equals( "6" ) || nodeId.equals( "3" ) || nodeId.equals( "4" ); } catch ( Exception e ) { return false; } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversal.java
625
public class TestTraversal extends AbstractNeo4jTestCase { // Tests the traverser factory for sanity checks with corrupted input @Test public void testSanityChecks1() throws Exception { // Valid data Node root = getGraphDb().createNode(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, }; // Null traversable relationships this.sanityCheckTraverser( "Sanity check failed: null traversable " + "rels should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, null, Direction.OUTGOING, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL ); // Null stop evaluator this.sanityCheckTraverser( "Sanity check failed: null stop eval " + "should throw an IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], Direction.OUTGOING, null, ReturnableEvaluator.ALL ); // Null returnable evaluator this.sanityCheckTraverser( "Sanity check failed: null returnable " + "evaluator should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], Direction.OUTGOING, StopEvaluator.END_OF_GRAPH, null ); root.delete(); } @Test public void testSanityChecks2() throws Exception { // ------------- with traverser direction ------------- // Valid data Node root = getGraphDb().createNode(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, }; Direction[] traversableDirs = new Direction[] { Direction.OUTGOING }; // Null traversable relationships this.sanityCheckTraverser( "Sanity check failed: null traversable " + "rels should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, null, traversableDirs[0], StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL ); // Null traversable directions this.sanityCheckTraverser( "Sanity check failed: null traversable " + "rels should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], null, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL ); // Null stop evaluator this.sanityCheckTraverser( "Sanity check failed: null stop eval " + "should throw an IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], traversableDirs[0], null, ReturnableEvaluator.ALL ); // Null returnable evaluator this.sanityCheckTraverser( "Sanity check failed: null returnable " + "evaluator should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], traversableDirs[0], StopEvaluator.END_OF_GRAPH, null ); // traversable relationships length not equal to traversable directions // length this.sanityCheckTraverser( "Sanity check failed: null returnable " + "evaluator should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], null, StopEvaluator.END_OF_GRAPH, null ); this.sanityCheckTraverser( "Sanity check failed: null returnable " + "evaluator should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, null, traversableDirs[0], StopEvaluator.END_OF_GRAPH, null ); root.delete(); } // Tests the traverser factory for simple corrupted (null) input, used // by testSanityChecks() private void sanityCheckTraverser( String failMessage, Order type, Node startNode, RelationshipType traversableRel, Direction direction, StopEvaluator stopEval, ReturnableEvaluator retEval ) { try { startNode.traverse( type, stopEval, retEval, traversableRel, direction ); fail( failMessage ); } catch ( IllegalArgumentException iae ) { // This is ok } } // Traverses the full test "ise-tree-like" population breadth first // and verifies that it is returned in correct order @Test public void testBruteBreadthTraversal() throws Exception { Node root = this.buildIseTreePopulation(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, MyRelTypes.TEST_TRAVERSAL }; Traverser traverser = root.traverse( BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH, traversableRels[1], Direction.BOTH ); try { this.assertLevelsOfNodes( traverser, new String[][] { new String[] { "1" }, new String[] { "2", "3", "4" }, new String[] { "5", "6", "7", "8", "9" }, new String[] { "10", "11", "12", "13", "14" } } ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } private void assertNodes( Traverser traverser, String... expectedNodes ) { Set<String> set = new HashSet<String>( Arrays.asList( expectedNodes ) ); for ( Node node : traverser ) { assertTrue( set.remove( node.getProperty( "node.test.id" ) ) ); } assertTrue( set.isEmpty() ); } private void assertLevelsOfNodes( Traverser traverser, String[][] nodes ) { Map<Integer, Collection<String>> map = new HashMap<Integer, Collection<String>>(); for ( Node node : traverser ) { Collection<String> collection = map.get( traverser.currentPosition().depth() ); if ( collection == null ) { collection = new ArrayList<String>(); map.put( traverser.currentPosition().depth(), collection ); } String name = (String) node.getProperty( "node.test.id" ); collection.add( name ); } for ( int i = 0; i < nodes.length; i++ ) { Collection<String> expected = Arrays.asList( nodes[i] ); assertEquals( expected, map.get( i ) ); } } // Traverses the test "ise-tree-like" population breadth first, // but only traverses "ise" (TEST) relationships (the population also // contains // "ise_clone" (TEST_TRAVERSAL) rels) @Test public void testMultiRelBreadthTraversal() throws Exception { Node root = this.buildIseTreePopulation(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; Traverser traverser = root.traverse( BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { this.assertLevelsOfNodes( traverser, new String[][] { new String[] { "1" }, new String[] { "2", "3", "4" }, new String[] { "5", "6", "7" }, new String[] { "10", "11", "12", "13" }, } ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Traverses the test "ise-tree-like" population breadth first, // starting in the middle of the tree and traversing only in the // "forward" direction @Test public void testDirectedBreadthTraversal() throws Exception { // Build test population Node root = this.buildIseTreePopulation(); Node startNode = null; // Get a node in the middle of the tree: try { // a) Construct a returnable evaluator that returns node 2 ReturnableEvaluator returnEvaluator = new ReturnableEvaluator() { @Override public boolean isReturnableNode( TraversalPosition pos ) { try { Node node = pos.currentNode(); String key = "node.test.id"; String nodeId = (String) node.getProperty( key ); return nodeId.equals( "2" ); } catch ( Exception e ) { return false; } } }; // b) create a traverser Traverser toTheMiddleTraverser = root.traverse( BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, returnEvaluator, MyRelTypes.TEST, Direction.BOTH ); // c) get the first node it returns startNode = toTheMiddleTraverser.iterator().next(); assertEquals( "2", startNode.getProperty( "node.test.id" ) ); } catch ( Exception e ) { e.printStackTrace(); fail( "Something went wrong when trying to get a start node " + "in the middle of the tree: " + e ); } // Construct the real traverser Traverser traverser = startNode.traverse( BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, MyRelTypes.TEST, Direction.OUTGOING ); try { this.assertNextNodeId( traverser, "2" ); this.assertNextNodeId( traverser, "5" ); this.assertNextNodeId( traverser, "6" ); this.assertNextNodeId( traverser, "10" ); this.assertNextNodeId( traverser, "11" ); this.assertNextNodeId( traverser, "12" ); this.assertNextNodeId( traverser, "13" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { nsee.printStackTrace(); fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Traverses the full test "ise-tree-like" population depth first // and verifies that it is returned in correct order @Test public void testBruteDepthTraversal() throws Exception { Node root = this.buildIseTreePopulation(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, MyRelTypes.TEST_TRAVERSAL }; Traverser traverser = root.traverse( DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH, traversableRels[1], Direction.BOTH ); try { this.assertNodes( traverser, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Traverses the test "ise-tree-like" population depth first, // but only traverses "ise" relationships (the population also contains // "ise_clone" rels) @Test public void testMultiRelDepthTraversal() throws Exception { Node root = this.buildIseTreePopulation(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; Traverser traverser = root.traverse( DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { assertNodes( traverser, "1", "2", "3", "4", "5", "6", "7", "10", "11", "12", "13" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the current node @Test public void testStopOnCurrentNode() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; // Construct a stop evaluator that stops on nodes 5, 6, 3 and 4 StopEvaluator stopEvaluator = new StopEvaluator() { @Override public boolean isStopNode( TraversalPosition position ) { try { Node node = position.currentNode(); String nodeId = (String) node.getProperty( "node.test.id" ); return nodeId.equals( "5" ) || nodeId.equals( "6" ) || nodeId.equals( "3" ) || nodeId.equals( "4" ); } catch ( Exception e ) { return false; } } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { this.assertNextNodeId( traverser, "1" ); this.assertNextNodeId( traverser, "2" ); this.assertNextNodeId( traverser, "3" ); this.assertNextNodeId( traverser, "4" ); this.assertNextNodeId( traverser, "5" ); this.assertNextNodeId( traverser, "6" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the previous node @Test public void testStopOnPreviousNode() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; // Construct a stop evaluator that stops on nodes 2, 3, and 4 // (ie root's children) StopEvaluator stopEvaluator = new StopEvaluator() { @Override public boolean isStopNode( TraversalPosition position ) { try { Node node = position.previousNode(); String nodeId = (String) node.getProperty( "node.test.id" ); return nodeId.equals( "1" ); } catch ( Exception e ) { return false; } } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { this.assertNextNodeId( traverser, "1" ); this.assertNextNodeId( traverser, "2" ); this.assertNextNodeId( traverser, "3" ); this.assertNextNodeId( traverser, "4" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { // Delete ise tree and commmit work this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the current depth @Test public void testStopOnDepth() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; // Construct a stop evaluator that stops on depth 2 StopEvaluator stopEvaluator = new StopEvaluator() { @Override public boolean isStopNode( TraversalPosition position ) { return position.depth() >= 2; } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { this.assertNextNodeId( traverser, "1" ); this.assertNextNodeId( traverser, "2" ); this.assertNextNodeId( traverser, "3" ); this.assertNextNodeId( traverser, "4" ); this.assertNextNodeId( traverser, "5" ); this.assertNextNodeId( traverser, "6" ); this.assertNextNodeId( traverser, "7" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { // Delete ise tree and commmit work this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the amount of // returned nodes @Test public void testStopOnReturnedNodes() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; // Construct stop- and returnable evaluators that return 5 nodes StopEvaluator stopEvaluator = new StopEvaluator() { @Override public boolean isStopNode( TraversalPosition position ) { // Stop traversing when we've returned 5 nodes return position.returnedNodesCount() >= 5; } }; ReturnableEvaluator returnEvaluator = new ReturnableEvaluator() { @Override public boolean isReturnableNode( TraversalPosition position ) { // Return nodes until we've reached 5 nodes or end of graph return position.returnedNodesCount() < 5; } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, returnEvaluator, traversableRels[0], Direction.BOTH ); try { this.assertLevelsOfNodes( traverser, new String[][] { new String[] { "1" }, new String[] { "2", "3", "4" }, new String[] { "5" }, } ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { // Delete ise tree and commmit work this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the last // traversed relationship @Test public void testStopOnLastRelationship() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, MyRelTypes.TEST_TRAVERSAL }; // Construct stop- and returnable evaluators that return 5 nodes StopEvaluator stopEvaluator = new StopEvaluator() { @Override public boolean isStopNode( TraversalPosition position ) { // Stop when we got here by traversing a clone relationship Relationship rel = position.lastRelationshipTraversed(); return rel != null && rel.isType( MyRelTypes.TEST_TRAVERSAL ); } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH, traversableRels[1], Direction.BOTH ); try { this.assertLevelsOfNodes( traverser, new String[][] { new String[] { "1" }, new String[] { "2", "3", "4" }, new String[] { "5", "6", "7", "8", "9" }, new String[] { "10", "11", "12", "13" } } ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { // Delete ise tree and commmit work this.deleteNodeTreeRecursively( root, 0 ); } } // -- Utility operations private Node buildIseTreePopulation() throws Exception { // Create population Node[] nodeSpace = new Node[] { null, // empty getGraphDb().createNode(), // 1 [root] getGraphDb().createNode(), // 2 getGraphDb().createNode(), // 3 getGraphDb().createNode(), // 4 getGraphDb().createNode(), // 5 getGraphDb().createNode(), // 6 getGraphDb().createNode(), // 7 getGraphDb().createNode(), // 8 getGraphDb().createNode(), // 9 getGraphDb().createNode(), // 10 getGraphDb().createNode(), // 11 getGraphDb().createNode(), // 12 getGraphDb().createNode(), // 13 getGraphDb().createNode(), // 14 }; String key = "node.test.id"; for ( int i = 1; i < nodeSpace.length; i++ ) { nodeSpace[i].setProperty( key, "" + i ); } RelationshipType ise = MyRelTypes.TEST; RelationshipType clone = MyRelTypes.TEST_TRAVERSAL; // Bind it together // // ----(1)------- // / \ \ // --(2)-- (3) (4)-- // / \ \ | \ // --(5)----- (6)---(7) (8) (9) // / | \ \ | // (10) (11)(12)(13) (14) // nodeSpace[1].createRelationshipTo( nodeSpace[2], ise ); nodeSpace[2].createRelationshipTo( nodeSpace[5], ise ); nodeSpace[5].createRelationshipTo( nodeSpace[10], ise ); nodeSpace[5].createRelationshipTo( nodeSpace[11], ise ); nodeSpace[5].createRelationshipTo( nodeSpace[12], ise ); nodeSpace[5].createRelationshipTo( nodeSpace[13], ise ); nodeSpace[2].createRelationshipTo( nodeSpace[6], ise ); nodeSpace[1].createRelationshipTo( nodeSpace[3], ise ); nodeSpace[1].createRelationshipTo( nodeSpace[4], ise ); nodeSpace[3].createRelationshipTo( nodeSpace[7], ise ); nodeSpace[6].createRelationshipTo( nodeSpace[7], clone ); nodeSpace[4].createRelationshipTo( nodeSpace[8], clone ); nodeSpace[4].createRelationshipTo( nodeSpace[9], clone ); nodeSpace[9].createRelationshipTo( nodeSpace[14], clone ); return nodeSpace[1]; // root } // Deletes a tree-like structure of nodes, starting with 'currentNode'. // Works fine with trees, dies horribly on cyclic structures. private void deleteNodeTreeRecursively( Node currentNode, int depth ) { if ( depth > 100 ) { throw new RuntimeException( "Recursive guard: depth = " + depth ); } if ( currentNode == null ) { return; } Iterable<Relationship> rels = currentNode.getRelationships(); for ( Relationship rel : rels ) { if ( !rel.getStartNode().equals( currentNode ) ) { continue; } Node endNode = rel.getEndNode(); rel.delete(); this.deleteNodeTreeRecursively( endNode, depth + 1 ); } String msg = "Deleting " + currentNode + "\t["; String id = (String) currentNode.getProperty( "node.test.id" ); msg += id + "]"; Iterable<Relationship> allRels = currentNode.getRelationships(); for ( Relationship rel : allRels ) { rel.delete(); } currentNode.delete(); } private void assertNextNodeId( Traverser traverser, String property ) throws NotFoundException { Node node = traverser.iterator().next(); assertEquals( property, node.getProperty( "node.test.id" ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestTraversal.java
626
public class TestMultiRelTypesAndDirections extends TraversalTestBase { private static final RelationshipType ONE = withName( "ONE" ); @Before public void setupGraph() { createGraph( "A ONE B", "B ONE C", "A TWO C" ); } @Test public void testCIsReturnedOnDepthTwoDepthFirst() { testCIsReturnedOnDepthTwo( traversal().depthFirst() ); } @Test public void testCIsReturnedOnDepthTwoBreadthFirst() { testCIsReturnedOnDepthTwo( traversal().breadthFirst() ); } private void testCIsReturnedOnDepthTwo( TraversalDescription description ) { Transaction transaction = beginTx(); try { description = description.expand( expanderForTypes( ONE, OUTGOING ) ); int i = 0; for ( Path position : description.traverse( node( "A" ) ) ) { assertEquals( i++, position.length() ); } } finally { transaction.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestMultiRelTypesAndDirections.java
627
public class TestSorting extends TraversalTestBase { @Test public void sortFriendsByName() throws Exception { /* * (Abraham) * | * (me)--(George)--(Dan) * | | * (Zack)---(Andreas) * | * (Nicholas) */ String me = "me"; String abraham = "Abraham"; String george = "George"; String dan = "Dan"; String zack = "Zack"; String andreas = "Andreas"; String nicholas = "Nicholas"; String knows = "KNOWS"; createGraph( triplet( me, knows, abraham ), triplet( me, knows, george), triplet( george, knows, dan ), triplet( me, knows, zack ), triplet( zack, knows, andreas ), triplet( george, knows, andreas ), triplet( andreas, knows, nicholas ) ); Transaction tx = beginTx(); List<Node> nodes = asNodes( abraham, george, dan, zack, andreas, nicholas ); assertEquals( nodes, asCollection( traversal().evaluator( excludeStartPosition() ) .sort( endNodeProperty( "name" ) ).traverse( getNodeWithName( me ) ).nodes() ) ); tx.success(); tx.finish(); } private List<Node> asNodes( String abraham, String george, String dan, String zack, String andreas, String nicholas ) { List<String> allNames = new ArrayList<String>( asList( abraham, george, dan, zack, andreas, nicholas ) ); Collections.sort( allNames ); List<Node> all = new ArrayList<Node>(); for ( String name : allNames ) { all.add( getNodeWithName( name ) ); } return all; } private static String triplet( String i, String type, String you ) { return i + " " + type + " " + you; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestSorting.java
628
public class TestPathDescription extends TraversalTestBase { private static final RelationshipType A = DynamicRelationshipType.withName( "A" ); private static final RelationshipType B = DynamicRelationshipType.withName( "B" ); private static final RelationshipType C = DynamicRelationshipType.withName( "C" ); private static final RelationshipType D = DynamicRelationshipType.withName( "D" ); @Test public void specificPath() throws Exception { /** * (1) -A-> (2) -B-> (3) -C-> (4) -D-> (5) * \ / * A ---B----- * v / * (6) */ createGraph( "1 A 2", "2 B 3", "3 C 4", "4 D 5", "1 A 6", "6 B 3" ); Transaction tx = beginTx(); try { expectPaths( traversal( NODE_PATH ) .expand( path().step( A ).step( B ).step( C ).step( D ).build() ) .evaluator( includeWhereLastRelationshipTypeIs( D ) ) .traverse( getNodeWithName( "1" ) ), "1,2,3,4,5", "1,6,3,4,5" ); } finally { tx.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestPathDescription.java
629
public class TestPath extends TraversalTestBase { private static Node a,b,c,d,e; private Transaction tx; @Before public void setup() { createGraph( "A TO B", "B TO C", "C TO D", "D TO E" ); tx = beginTx(); a = getNodeWithName( "A" ); b = getNodeWithName( "B" ); c = getNodeWithName( "C" ); d = getNodeWithName( "D" ); e = getNodeWithName( "E" ); } @After public void tearDown() { tx.finish(); } @Test public void testPathIterator() { Path path = traversal().evaluator( atDepth( 4 ) ).traverse( node( "A" ) ).iterator().next(); assertPathIsCorrect( path ); } @Test public void reverseNodes() throws Exception { Path path = first( traversal().evaluator( atDepth( 0 ) ).traverse( a ) ); assertContains( path.reverseNodes(), a ); path = first( traversal().evaluator( atDepth( 4 ) ).traverse( a ) ); assertContainsInOrder( path.reverseNodes(), e, d, c, b, a ); } @Test public void reverseRelationships() throws Exception { Path path = first( traversal().evaluator( atDepth( 0 ) ).traverse( a ) ); assertFalse( path.reverseRelationships().iterator().hasNext() ); path = first( traversal().evaluator( atDepth( 4 ) ).traverse( a ) ); Node[] expectedNodes = new Node[] { e, d, c, b, a }; int index = 0; for ( Relationship rel : path.reverseRelationships() ) assertEquals( "For index " + index, expectedNodes[index++], rel.getEndNode() ); assertEquals( 4, index ); } @Test public void testBidirectionalPath() throws Exception { TraversalDescription side = traversal().uniqueness( Uniqueness.NODE_PATH ); BidirectionalTraversalDescription bidirectional = bidirectionalTraversal().mirroredSides( side ); Path bidirectionalPath = first( bidirectional.traverse( a, e ) ); assertPathIsCorrect( bidirectionalPath ); assertEquals( a, first( bidirectional.traverse( a, e ) ).startNode() ); // White box testing below: relationships(), nodes(), reverseRelationships(), reverseNodes() // does cache the start node if not already cached, so just make sure they to it properly. bidirectionalPath = first( bidirectional.traverse( a, e ) ); bidirectionalPath.relationships(); assertEquals( a, bidirectionalPath.startNode() ); bidirectionalPath = first( bidirectional.traverse( a, e ) ); bidirectionalPath.nodes(); assertEquals( a, bidirectionalPath.startNode() ); bidirectionalPath = first( bidirectional.traverse( a, e ) ); bidirectionalPath.reverseRelationships(); assertEquals( a, bidirectionalPath.startNode() ); bidirectionalPath = first( bidirectional.traverse( a, e ) ); bidirectionalPath.reverseNodes(); assertEquals( a, bidirectionalPath.startNode() ); bidirectionalPath = first( bidirectional.traverse( a, e ) ); bidirectionalPath.iterator(); assertEquals( a, bidirectionalPath.startNode() ); } private void assertPathIsCorrect( Path path ) { Node a = node( "A" ); Relationship to1 = a.getRelationships( Direction.OUTGOING ).iterator().next(); Node b = to1.getEndNode(); Relationship to2 = b.getRelationships( Direction.OUTGOING ).iterator().next(); Node c = to2.getEndNode(); Relationship to3 = c.getRelationships( Direction.OUTGOING ).iterator().next(); Node d = to3.getEndNode(); Relationship to4 = d.getRelationships( Direction.OUTGOING ).iterator().next(); Node e = to4.getEndNode(); assertEquals( (Integer) 4, (Integer) path.length() ); assertEquals( a, path.startNode() ); assertEquals( e, path.endNode() ); assertEquals( to4, path.lastRelationship() ); assertContainsInOrder( path, a, to1, b, to2, c, to3, d, to4, e ); assertContainsInOrder( path.nodes(), a, b, c, d, e ); assertContainsInOrder( path.relationships(), to1, to2, to3, to4 ); assertContainsInOrder( path.reverseNodes(), e, d, c, b, a ); assertContainsInOrder( path.reverseRelationships(), to4, to3, to2, to1 ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestPath.java
630
public class TestOrderByTypeExpander extends TraversalTestBase { private final RelationshipType next = withName( "NEXT" ); private final RelationshipType firstComment = withName( "FIRST_COMMENT" ); private final RelationshipType comment = withName( "COMMENT" ); @Before public void setup() { /** * (A1)-NEXT->(A2)-NEXT->(A3) * / | \ * FIRST_COMMENT FIRST_COMMENT FIRST_COMMENT * / | \ * v v v * (C1) (C4) (C7) * | | | * COMMENT COMMENT COMMENT * | | | * v v v * (C2) (C5) (C8) * | | | * COMMENT COMMENT COMMENT * | | | * v v v * (C3) (C6) (C9) */ createGraph( "A1 NEXT A2", "A2 NEXT A3", "A1 FIRST_COMMENT C1", "C1 COMMENT C2", "C2 COMMENT C3", "A2 FIRST_COMMENT C4", "C4 COMMENT C5", "C5 COMMENT C6", "A3 FIRST_COMMENT C7", "C7 COMMENT C8", "C8 COMMENT C9" ); } @Test public void makeSureNodesAreTraversedInCorrectOrder() { RelationshipExpander expander = new OrderedByTypeExpander().add( firstComment ).add( comment ).add( next ); Iterator<Node> itr = traversal().depthFirst().expand( expander ).traverse( node( "A1" ) ).nodes().iterator(); assertOrder( itr, "A1", "C1", "C2", "C3", "A2", "C4", "C5", "C6", "A3", "C7", "C8", "C9" ); expander = new OrderedByTypeExpander().add( next ).add( firstComment ).add( comment ); itr = traversal().depthFirst().expand( expander ).traverse( node( "A1" ) ).nodes().iterator(); assertOrder( itr, "A1", "A2", "A3", "C7", "C8", "C9", "C4", "C5", "C6", "C1", "C2", "C3" ); } @Test public void evenDifferentDirectionsKeepsOrder() throws Exception { RelationshipExpander expander = new OrderedByTypeExpander() .add( next, INCOMING ) .add( firstComment ) .add( comment ) .add( next, OUTGOING ); Iterator<Node> itr = traversal().depthFirst().expand( expander ).traverse( node( "A2" ) ).nodes().iterator(); assertOrder( itr, "A2", "A1", "C1", "C2", "C3", "C4", "C5", "C6", "A3", "C7", "C8", "C9" ); } private void assertOrder( Iterator<Node> itr, String... names ) { Transaction tx = beginTx(); for ( String name : names ) { Node node = itr.next(); assertEquals( "expected " + name + ", was " + node.getProperty( "name" ), getNodeWithName( name ), node ); } assertFalse( itr.hasNext() ); tx.success(); tx.finish(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestOrderByTypeExpander.java
631
public class TestMultipleStartNodes extends TraversalTestBase { @Test public void myFriendsAsWellAsYourFriends() throws Exception { /* * Hey, this looks like a futuristic gun or something * * (f8) _----(f1)--(f5) * | / / * (f7)--(you)--(me)--(f2)--(f6) * | / \ * (f4) (f3) */ createGraph( "you KNOW me", "you KNOW f1", "you KNOW f4", "me KNOW f1", "me KNOW f4", "me KNOW f2", "me KNOW f3", "f1 KNOW f5", "f2 KNOW f6", "you KNOW f7", "f7 KNOW f8" ); Transaction tx = beginTx(); try { RelationshipType KNOW = withName( "KNOW" ); Node you = getNodeWithName( "you" ); Node me = getNodeWithName( "me" ); String[] levelOneFriends = new String[]{"f1", "f2", "f3", "f4", "f7"}; TraversalDescription levelOneTraversal = traversal().relationships( KNOW ).evaluator( atDepth( 1 ) ); expectNodes( levelOneTraversal.depthFirst().traverse( you, me ), levelOneFriends ); expectNodes( levelOneTraversal.breadthFirst().traverse( you, me ), levelOneFriends ); String[] levelTwoFriends = new String[]{"f5", "f6", "f8"}; TraversalDescription levelTwoTraversal = traversal().relationships( KNOW ).evaluator( atDepth( 2 ) ); expectNodes( levelTwoTraversal.depthFirst().traverse( you, me ), levelTwoFriends ); expectNodes( levelTwoTraversal.breadthFirst().traverse( you, me ), levelTwoFriends ); } finally { tx.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestMultipleStartNodes.java
632
private static class MustBeConnectedToNodeFilter implements Predicate<Path>, Evaluator { private final Node node; MustBeConnectedToNodeFilter( Node node ) { this.node = node; } public boolean accept( Path item ) { for ( Relationship rel : item.endNode().getRelationships( Direction.OUTGOING ) ) { if ( rel.getEndNode().equals( node ) ) { return true; } } return false; } public Evaluation evaluate( Path path ) { return accept( path ) ? Evaluation.INCLUDE_AND_CONTINUE : Evaluation.EXCLUDE_AND_CONTINUE; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestMultipleFilters.java
633
{ public Evaluation evaluate( Path path ) { return Evaluation.ofIncludes( count( path.endNode().getRelationships( Direction.OUTGOING ) ) <= 2 ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestMultipleFilters.java
634
public class TestMultipleFilters extends TraversalTestBase { private Transaction tx; @Before public void setupGraph() { // // (a)-------- // / \ // v v // (b)-->(k)<----(c)-->(f) // / \ // v v // (d) (e) createGraph( "a TO b", "b TO d", "b TO e", "b TO k", "a TO c", "c TO f", "c TO k" ); tx = beginTx(); } @After public void tearDown() { tx.finish(); } private static class MustBeConnectedToNodeFilter implements Predicate<Path>, Evaluator { private final Node node; MustBeConnectedToNodeFilter( Node node ) { this.node = node; } public boolean accept( Path item ) { for ( Relationship rel : item.endNode().getRelationships( Direction.OUTGOING ) ) { if ( rel.getEndNode().equals( node ) ) { return true; } } return false; } public Evaluation evaluate( Path path ) { return accept( path ) ? Evaluation.INCLUDE_AND_CONTINUE : Evaluation.EXCLUDE_AND_CONTINUE; } } @Test public void testNarrowingFilters() { Evaluator mustBeConnectedToK = new MustBeConnectedToNodeFilter( getNodeWithName( "k" ) ); Evaluator mustNotHaveMoreThanTwoOutRels = new Evaluator() { public Evaluation evaluate( Path path ) { return Evaluation.ofIncludes( count( path.endNode().getRelationships( Direction.OUTGOING ) ) <= 2 ); } }; TraversalDescription description = traversal().evaluator( mustBeConnectedToK ); expectNodes( description.traverse( node( "a" ) ), "b", "c" ); expectNodes( description.evaluator( mustNotHaveMoreThanTwoOutRels ).traverse( node( "a" ) ), "c" ); } @Test public void testBroadeningFilters() { MustBeConnectedToNodeFilter mustBeConnectedToC = new MustBeConnectedToNodeFilter( getNodeWithName( "c" ) ); MustBeConnectedToNodeFilter mustBeConnectedToE = new MustBeConnectedToNodeFilter( getNodeWithName( "e" ) ); // Nodes connected (OUTGOING) to c (which "a" is) expectNodes( traversal().evaluator( mustBeConnectedToC ).traverse( node( "a" ) ), "a" ); // Nodes connected (OUTGOING) to c AND e (which none is) expectNodes( traversal().evaluator( mustBeConnectedToC ).evaluator( mustBeConnectedToE ).traverse( node( "a" ) ) ); // Nodes connected (OUTGOING) to c OR e (which "a" and "b" is) expectNodes( traversal().evaluator( includeIfAcceptedByAny( mustBeConnectedToC, mustBeConnectedToE ) ).traverse( node( "a" ) ), "a", "b" ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestMultipleFilters.java
635
class MonoDirectionalTraverserIterator extends AbstractTraverserIterator { private final BranchSelector selector; private final PathEvaluator evaluator; private final UniquenessFilter uniqueness; MonoDirectionalTraverserIterator( Resource resource, UniquenessFilter uniqueness, PathExpander expander, BranchOrderingPolicy order, PathEvaluator evaluator, Iterable<Node> startNodes, InitialBranchState initialState ) { super( resource ); this.uniqueness = uniqueness; this.evaluator = evaluator; this.selector = order.create( new AsOneStartBranch( this, startNodes, initialState ), expander ); } protected BranchSelector selector() { return selector; } @Override public Evaluation evaluate( TraversalBranch branch, BranchState state ) { return evaluator.evaluate( branch, state ); } @Override protected Path fetchNextOrNull() { TraversalBranch result; while ( true ) { result = selector.next( this ); if ( result == null ) { close(); return null; } if ( result.includes() ) { numberOfPathsReturned++; return result; } } } @Override public boolean isUniqueFirst( TraversalBranch branch ) { return uniqueness.checkFirst( branch ); } @Override public boolean isUnique( TraversalBranch branch ) { return uniqueness.check( branch ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_MonoDirectionalTraverserIterator.java
636
{ @Override public Resource instance() { return Resource.EMPTY; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_MonoDirectionalTraversalDescription.java
637
class TraversalBranchImpl implements TraversalBranch { private static final Iterator<Relationship> PRUNED_ITERATOR = new Iterator<Relationship>() { @Override public boolean hasNext() { return false; } @Override public Relationship next() { throw new UnsupportedOperationException(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; final TraversalBranch parent; private final Relationship howIGotHere; private final Node source; private Iterator<Relationship> relationships; // high bit here [cidd,dddd][dddd,dddd][dddd,dddd][dddd,dddd] private int depthAndEvaluationBits; private int expandedCount; /* * For expansion sources for all nodes except the start node */ TraversalBranchImpl( TraversalBranch parent, int depth, Node source, Relationship toHere ) { this.parent = parent; this.source = source; this.howIGotHere = toHere; this.depthAndEvaluationBits = depth; } /* * For the start node branches */ TraversalBranchImpl( TraversalBranch parent, Node source ) { this.parent = parent; this.source = source; this.howIGotHere = null; this.depthAndEvaluationBits = 0; } protected void setEvaluation( Evaluation evaluation ) { this.depthAndEvaluationBits &= 0x3FFFFFFF; // First clear those evaluation bits this.depthAndEvaluationBits |= bitValue( evaluation.includes(), 30 ) | bitValue( evaluation.continues(), 31 ); } private int bitValue( boolean value, int bit ) { return (value ? 1 : 0) << bit; } protected void expandRelationships( PathExpander expander ) { if ( continues() ) { relationships = expandRelationshipsWithoutChecks( expander ); } else { relationships = PRUNED_ITERATOR; } } protected Iterator<Relationship> expandRelationshipsWithoutChecks( PathExpander expander ) { Iterable<Relationship> iterable = expander.expand( this, BranchState.NO_STATE ); return iterable.iterator(); } protected boolean hasExpandedRelationships() { return relationships != null; } protected void evaluate( TraversalContext context ) { setEvaluation( context.evaluate( this, null ) ); } public void initialize( final PathExpander expander, TraversalContext metadata ) { evaluate( metadata ); expandRelationships( expander ); } public TraversalBranch next( PathExpander expander, TraversalContext context ) { while ( relationships.hasNext() ) { Relationship relationship = relationships.next(); 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(); } } // Just to help GC relationships = PRUNED_ITERATOR; return null; } protected TraversalBranch newNextBranch( Node node, Relationship relationship ) { return new TraversalBranchImpl( this, length() + 1, node, relationship ); } @Override public void prune() { relationships = PRUNED_ITERATOR; } public int length() { return depthAndEvaluationBits&0x3FFFFFFF; } public TraversalBranch parent() { return this.parent; } public int expanded() { return expandedCount; } @Override public boolean includes() { return (depthAndEvaluationBits & 0x40000000) != 0; } @Override public boolean continues() { return (depthAndEvaluationBits & 0x80000000) != 0; } @Override public void evaluation( Evaluation eval ) { setEvaluation( Evaluation.of( includes() & eval.includes(), continues() & eval.continues() ) ); } public Node startNode() { return findStartBranch().endNode(); } private TraversalBranch findStartBranch() { TraversalBranch branch = this; while ( branch.length() > 0 ) { branch = branch.parent(); } return branch; } public Node endNode() { return source; } public Relationship lastRelationship() { return howIGotHere; } public Iterable<Relationship> relationships() { LinkedList<Relationship> relationships = new LinkedList<Relationship>(); TraversalBranch branch = this; while ( branch.length() > 0 ) { relationships.addFirst( branch.lastRelationship() ); branch = branch.parent(); } return relationships; } @Override public Iterable<Relationship> reverseRelationships() { return new Iterable<Relationship>() { @Override public Iterator<Relationship> iterator() { return new PrefetchingIterator<Relationship>() { private TraversalBranch branch = TraversalBranchImpl.this; @Override protected Relationship fetchNextOrNull() { try { return branch != null ? branch.lastRelationship() : null; } finally { branch = branch != null ? branch.parent() : null; } } }; } }; } public Iterable<Node> nodes() { LinkedList<Node> nodes = new LinkedList<Node>(); TraversalBranch branch = this; while ( branch.length() > 0 ) { nodes.addFirst( branch.endNode() ); branch = branch.parent(); } nodes.addFirst( branch.endNode() ); return nodes; } @Override public Iterable<Node> reverseNodes() { return new Iterable<Node>() { @Override public Iterator<Node> iterator() { return new PrefetchingIterator<Node>() { private TraversalBranch branch = TraversalBranchImpl.this; @Override protected Node fetchNextOrNull() { try { return branch.length() >= 0 ? branch.endNode() : null; } finally { branch = branch.parent(); } } }; } }; } public Iterator<PropertyContainer> iterator() { LinkedList<PropertyContainer> entities = new LinkedList<PropertyContainer>(); TraversalBranch branch = this; while ( branch.length() > 0 ) { entities.addFirst( branch.endNode() ); entities.addFirst( branch.lastRelationship() ); branch = branch.parent(); } entities.addFirst( branch.endNode() ); return entities.iterator(); } @Override public int hashCode() { TraversalBranch branch = this; int hashCode = 1; while ( branch.length() > 0 ) { Relationship relationship = branch.lastRelationship(); hashCode = 31*hashCode + relationship.hashCode(); branch = branch.parent(); } if ( hashCode == 1 ) { hashCode = endNode().hashCode(); } return hashCode; } @Override public boolean equals( Object obj ) { if ( obj == this) { return true; } if ( !( obj instanceof TraversalBranch ) ) { return false; } TraversalBranch branch = this; TraversalBranch other = (TraversalBranch) obj; if ( branch.length() != other.length() ) { return false; } while ( branch.length() > 0 ) { if ( !branch.lastRelationship().equals( other.lastRelationship() ) ) { return false; } branch = branch.parent(); other = other.parent(); } return true; } @Override public String toString() { return Traversal.defaultPathToString( this ); } @Override public Object state() { return null; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_TraversalBranchImpl.java
638
public final class MonoDirectionalTraversalDescription implements TraversalDescription { final static Provider<Resource> NO_STATEMENT = new Provider<Resource>() { @Override public Resource instance() { return Resource.EMPTY; } }; final PathExpander expander; final InitialBranchState initialState; final Provider<? extends Resource> statementFactory; final UniquenessFactory uniqueness; final Object uniquenessParameter; final PathEvaluator evaluator; final BranchOrderingPolicy branchOrdering; final Comparator<? super Path> sorting; final Collection<Node> endNodes; public MonoDirectionalTraversalDescription() { /* * Use one statement per operation performed, rather than a global statement for the whole traversal. This is * significantly less performant, and only used when accessing the traversal framework via the legacy access * methods (eg. Traversal.description()). */ this(NO_STATEMENT); } public MonoDirectionalTraversalDescription( Provider<? extends Resource> statementProvider ) { this( Traversal.emptyPathExpander(), Uniqueness.NODE_GLOBAL, null, Evaluators.all(), InitialBranchState.NO_STATE, Traversal.preorderDepthFirst(), null, null, statementProvider ); } private MonoDirectionalTraversalDescription( PathExpander expander, UniquenessFactory uniqueness, Object uniquenessParameter, PathEvaluator evaluator, InitialBranchState initialState, BranchOrderingPolicy branchOrdering, Comparator<? super Path> sorting, Collection<Node> endNodes, Provider<? extends Resource> statementFactory ) { this.expander = expander; this.uniqueness = uniqueness; this.uniquenessParameter = uniquenessParameter; this.evaluator = evaluator; this.branchOrdering = branchOrdering; this.sorting = sorting; this.endNodes = endNodes; this.initialState = initialState; this.statementFactory = statementFactory; } public Traverser traverse( Node startNode ) { return traverse( new Node[]{startNode} ); } public Traverser traverse( Node... startNodes ) { final Iterable<Node> iterableStartNodes = Arrays.asList( startNodes ); return new DefaultTraverser( new Factory<TraverserIterator>(){ @Override public TraverserIterator newInstance() { Resource statement = statementFactory.instance(); MonoDirectionalTraverserIterator iterator = new MonoDirectionalTraverserIterator( statement, uniqueness.create( uniquenessParameter ), expander, branchOrdering, evaluator, iterableStartNodes, initialState ); return sorting != null ? new SortingTraverserIterator( statement, sorting, iterator ) : iterator; } }); } /* (non-Javadoc) * @see org.neo4j.graphdb.traversal.TraversalDescription#uniqueness(org.neo4j.graphdb.traversal.Uniqueness) */ public TraversalDescription uniqueness( UniquenessFactory uniqueness ) { return new MonoDirectionalTraversalDescription( expander, uniqueness, null, evaluator, initialState, branchOrdering, sorting, endNodes, statementFactory ); } /* (non-Javadoc) * @see org.neo4j.graphdb.traversal.TraversalDescription#uniqueness(org.neo4j.graphdb.traversal.Uniqueness, java.lang.Object) */ public TraversalDescription uniqueness( UniquenessFactory uniqueness, Object parameter ) { if ( this.uniqueness == uniqueness && (uniquenessParameter == null ? parameter == null : uniquenessParameter.equals( parameter )) ) { return this; } return new MonoDirectionalTraversalDescription( expander, uniqueness, parameter, evaluator, initialState, branchOrdering, sorting, endNodes, statementFactory ); } public TraversalDescription evaluator( Evaluator evaluator ) { return evaluator( new Evaluator.AsPathEvaluator( evaluator) ); } public TraversalDescription evaluator( PathEvaluator evaluator ) { if ( this.evaluator == evaluator ) { return this; } nullCheck( evaluator, Evaluator.class, "RETURN_ALL" ); return new MonoDirectionalTraversalDescription( expander, uniqueness, uniquenessParameter, addEvaluator( this.evaluator, evaluator ), initialState, branchOrdering, sorting, endNodes, statementFactory ); } protected static PathEvaluator addEvaluator( PathEvaluator existing, PathEvaluator toAdd ) { if ( existing instanceof MultiEvaluator ) { return ((MultiEvaluator) existing).add( toAdd ); } else { return existing == Evaluators.all() ? toAdd : new MultiEvaluator( new PathEvaluator[] { existing, toAdd } ); } } protected static <T> void nullCheck( T parameter, Class<T> parameterType, String defaultName ) { if ( parameter == null ) { String typeName = parameterType.getSimpleName(); throw new IllegalArgumentException( typeName + " may not be null, use " + typeName + "." + defaultName + " instead." ); } } /* (non-Javadoc) * @see org.neo4j.graphdb.traversal.TraversalDescription#order(org.neo4j.graphdb.traversal.Order) */ public TraversalDescription order( BranchOrderingPolicy order ) { if ( this.branchOrdering == order ) { return this; } return new MonoDirectionalTraversalDescription( expander, uniqueness, uniquenessParameter, evaluator, initialState, order, sorting, endNodes, statementFactory ); } public TraversalDescription depthFirst() { return order( Traversal.preorderDepthFirst() ); } public TraversalDescription breadthFirst() { return order( Traversal.preorderBreadthFirst() ); } /* (non-Javadoc) * @see org.neo4j.graphdb.traversal.TraversalDescription#relationships(org.neo4j.graphdb.RelationshipType) */ public TraversalDescription relationships( RelationshipType type ) { return relationships( type, Direction.BOTH ); } /* (non-Javadoc) * @see org.neo4j.graphdb.traversal.TraversalDescription#relationships(org.neo4j.graphdb.RelationshipType, org.neo4j.graphdb.Direction) */ public TraversalDescription relationships( RelationshipType type, Direction direction ) { if ( expander instanceof Expander ) return expand( ((Expander)expander).add( type, direction ) ); throw new IllegalStateException( "The current expander cannot be added to" ); } public TraversalDescription expand( RelationshipExpander expander ) { return expand( StandardExpander.toPathExpander( expander ) ); } public TraversalDescription expand( PathExpander<?> expander ) { if ( expander.equals( this.expander ) ) { return this; } return new MonoDirectionalTraversalDescription( expander, uniqueness, uniquenessParameter, evaluator, initialState, branchOrdering, sorting, endNodes, statementFactory ); } public <STATE> TraversalDescription expand( PathExpander<STATE> expander, InitialBranchState<STATE> initialState ) { return new MonoDirectionalTraversalDescription( expander, uniqueness, uniquenessParameter, evaluator, initialState, branchOrdering, sorting, endNodes, statementFactory ); } public <STATE> TraversalDescription expand( PathExpander<STATE> expander, InitialStateFactory<STATE> initialState ) { return new MonoDirectionalTraversalDescription( expander, uniqueness, uniquenessParameter, evaluator, new InitialStateFactory.AsInitialBranchState<>( initialState ), branchOrdering, sorting, endNodes, statementFactory ); } @Override public TraversalDescription sort( Comparator<? super Path> sorting ) { return new MonoDirectionalTraversalDescription( expander, uniqueness, uniquenessParameter, evaluator, initialState, branchOrdering, sorting, endNodes, statementFactory ); } @Override public TraversalDescription reverse() { return new MonoDirectionalTraversalDescription( expander.reverse(), uniqueness, uniquenessParameter, evaluator, initialState.reverse(), branchOrdering, sorting, endNodes, statementFactory ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_MonoDirectionalTraversalDescription.java
639
private static class TransactionStatus implements Comparable<TransactionStatus> { private boolean prepared = false; private boolean commitStarted = false; private boolean rollback = false; private boolean startWritten = false; private final XaTransaction xaTransaction; private int sequenceNumber; TransactionStatus( XaTransaction xaTransaction ) { this.xaTransaction = xaTransaction; } void markAsPrepared() { prepared = true; } void markAsRollback() { rollback = true; } void markCommitStarted() { commitStarted = true; } boolean prepared() { return prepared; } boolean rollback() { return rollback; } boolean commitStarted() { return commitStarted; } boolean startWritten() { return startWritten; } void markStartWritten() { this.startWritten = true; } XaTransaction getTransaction() { return xaTransaction; } @Override public String toString() { return "TransactionStatus[" + xaTransaction.getIdentifier() + ", prepared=" + prepared + ", commitStarted=" + commitStarted + ", rolledback=" + rollback + "]"; } public void setSequenceNumber( int sequenceNumber ) { this.sequenceNumber = sequenceNumber; } @Override public int compareTo( TransactionStatus that ) { return this.sequenceNumber > that.sequenceNumber ? 1 : this.sequenceNumber < that.sequenceNumber ? -1 : 0; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaResourceManager.java
640
{ @Override public void add( PropertyBlock target, DynamicRecord record ) { record.setCreated(); target.addValueRecord( record ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_Command.java
641
{ @Override public int compare( Xid o1, Xid o2 ) { TransactionStatus a = xidMap.get( o1 ).txStatus; TransactionStatus b = xidMap.get( o2 ).txStatus; return a.compareTo( b ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaResourceManager.java
642
public class XaResourceManager { private static class ResourceTransaction { private Xid xid; private final XaTransaction xaTx; ResourceTransaction( XaTransaction xaTx ) { this.xaTx = xaTx; } } private final ArrayMap<XAResource,ResourceTransaction> xaResourceMap = new ArrayMap<>(); private final ArrayMap<Xid,XidStatus> xidMap = new ArrayMap<>(); private final TransactionMonitor transactionMonitor; private int recoveredTxCount = 0; private final Map<Integer, TransactionInfo> recoveredTransactions = new HashMap<>(); private XaLogicalLog log = null; private final XaTransactionFactory tf; private final String name; private final TxIdGenerator txIdGenerator; private final XaDataSource dataSource; private StringLogger msgLog; private final AbstractTransactionManager transactionManager; private final RecoveryVerifier recoveryVerifier; public XaResourceManager( XaDataSource dataSource, XaTransactionFactory tf, TxIdGenerator txIdGenerator, AbstractTransactionManager transactionManager, RecoveryVerifier recoveryVerifier, String name, Monitors monitors ) { this.dataSource = dataSource; this.tf = tf; this.txIdGenerator = txIdGenerator; this.transactionManager = transactionManager; this.recoveryVerifier = recoveryVerifier; this.name = name; this.transactionMonitor = monitors.newMonitor( TransactionMonitor.class, getClass(), dataSource.getName() ); } public synchronized void setLogicalLog( XaLogicalLog log ) { this.log = log; this.msgLog = log.getStringLogger(); } /** * Creates a transaction that can be used for read operations, but is not yet * {@link #start(XAResource, Xid) started} and hasn't got an identifier associated with it. * A call to {@link #start(XAResource, Xid)} after a call to this method will start the transaction * created here. Otherwise if there's no {@link #createTransaction(XAResource)} call prior to a * {@link #start(XAResource, Xid)} call the transaction will be created there instead. * * @param xaResource the {@link XAResource} to create the transaction for. * @return the created transaction. * @throws XAException if the {@code resource} was already associated with another transaction. */ synchronized XaTransaction createTransaction( XAResource xaResource ) throws XAException { if ( xaResourceMap.get( xaResource ) != null ) { throw new XAException( "Resource[" + xaResource + "] already enlisted or suspended" ); } XaTransaction xaTx = tf.create( dataSource.getLastCommittedTxId(), transactionManager.getTransactionState() ); xaResourceMap.put( xaResource, new ResourceTransaction( xaTx ) ); return xaTx; } synchronized XaTransaction getXaTransaction( XAResource xaRes ) throws XAException { XidStatus status = xidMap.get( xaResourceMap.get( xaRes ).xid ); if ( status == null ) { throw new XAException( "Resource[" + xaRes + "] not enlisted" ); } return status.getTransactionStatus().getTransaction(); } synchronized void start( XAResource xaResource, Xid xid ) throws XAException { ResourceTransaction tx = xaResourceMap.get( xaResource ); if ( tx == null ) { // Why allow creating the transaction here? See javadoc about createTransaction. createTransaction( xaResource ); tx = xaResourceMap.get( xaResource ); } if ( xidMap.get( xid ) == null ) // TODO why are we allowing this? { int identifier = log.start( xid, txIdGenerator.getCurrentMasterId(), txIdGenerator.getMyId(), dataSource.getLastCommittedTxId() ); tx.xaTx.setIdentifier( identifier ); xidMap.put( xid, new XidStatus( tx.xaTx ) ); tx.xid = xid; } } synchronized void injectStart( Xid xid, XaTransaction tx ) throws IOException { if ( xidMap.get( xid ) != null ) { throw new IOException( "Inject start failed, xid: " + xid + " already injected" ); } xidMap.put( xid, new XidStatus( tx ) ); recoveredTxCount++; } synchronized void resume( Xid xid ) throws XAException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } if ( status.getActive() ) { throw new XAException( "Xid [" + xid + "] not suspended" ); } status.setActive( true ); } synchronized void join( XAResource xaResource, Xid xid ) throws XAException { if ( xidMap.get( xid ) == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } if ( xaResourceMap.get( xaResource ) != null ) { throw new XAException( "Resource[" + xaResource + "] already enlisted" ); } ResourceTransaction tx = new ResourceTransaction( null /* TODO hmm */ ); tx.xid = xid; xaResourceMap.put( xaResource, tx ); } synchronized void end( XAResource xaResource, Xid xid ) throws XAException { if ( xaResourceMap.remove( xaResource ) == null ) { throw new XAException( "Resource[" + xaResource + "] not enlisted" ); } } synchronized void suspend( Xid xid ) throws XAException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } if ( !status.getActive() ) { throw new XAException( "Xid[" + xid + "] already suspended" ); } status.setActive( false ); } synchronized void fail( XAResource xaResource, Xid xid ) throws XAException { XidStatus xidStatus = xidMap.get( xid ); if ( xidStatus == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } if ( xaResourceMap.remove( xaResource ) == null ) { throw new XAException( "Resource[" + xaResource + "] not enlisted" ); } xidStatus.getTransactionStatus().markAsRollback(); } synchronized void validate( XAResource xaResource ) throws XAException { ResourceTransaction tx = xaResourceMap.get( xaResource ); XidStatus status = null; if ( tx == null || (status = xidMap.get( tx.xid )) == null ) { throw new XAException( "Resource[" + xaResource + "] not enlisted" ); } if ( !status.getActive() ) { throw new XAException( "Resource[" + xaResource + "] suspended" ); } } // TODO: check so we're not currently committing on the resource synchronized void destroy( XAResource xaResource ) { xaResourceMap.remove( xaResource ); } private static class XidStatus { private boolean active = true; private final TransactionStatus txStatus; XidStatus( XaTransaction xaTransaction ) { txStatus = new TransactionStatus( xaTransaction ); } void setActive( boolean active ) { this.active = active; } boolean getActive() { return this.active; } TransactionStatus getTransactionStatus() { return txStatus; } } private static class TransactionStatus implements Comparable<TransactionStatus> { private boolean prepared = false; private boolean commitStarted = false; private boolean rollback = false; private boolean startWritten = false; private final XaTransaction xaTransaction; private int sequenceNumber; TransactionStatus( XaTransaction xaTransaction ) { this.xaTransaction = xaTransaction; } void markAsPrepared() { prepared = true; } void markAsRollback() { rollback = true; } void markCommitStarted() { commitStarted = true; } boolean prepared() { return prepared; } boolean rollback() { return rollback; } boolean commitStarted() { return commitStarted; } boolean startWritten() { return startWritten; } void markStartWritten() { this.startWritten = true; } XaTransaction getTransaction() { return xaTransaction; } @Override public String toString() { return "TransactionStatus[" + xaTransaction.getIdentifier() + ", prepared=" + prepared + ", commitStarted=" + commitStarted + ", rolledback=" + rollback + "]"; } public void setSequenceNumber( int sequenceNumber ) { this.sequenceNumber = sequenceNumber; } @Override public int compareTo( TransactionStatus that ) { return this.sequenceNumber > that.sequenceNumber ? 1 : this.sequenceNumber < that.sequenceNumber ? -1 : 0; } } private void checkStartWritten( TransactionStatus status, XaTransaction tx ) throws XAException { if ( !status.startWritten() && !tx.isRecovered() ) { log.writeStartEntry( tx.getIdentifier() ); status.markStartWritten(); } } synchronized int prepare( Xid xid ) throws XAException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } TransactionStatus txStatus = status.getTransactionStatus(); XaTransaction xaTransaction = txStatus.getTransaction(); checkStartWritten( txStatus, xaTransaction ); if ( xaTransaction.isReadOnly() ) { // Called here to release locks of two-phase read-only transactions // cf. TransactionImpl.doCommit() and commit() commitKernelTx( xaTransaction ); log.done( xaTransaction.getIdentifier() ); xidMap.remove( xid ); if ( xaTransaction.isRecovered() ) { oneMoreTransactionRecovered(); } return XAResource.XA_RDONLY; } else { xaTransaction.prepare(); log.prepare( xaTransaction.getIdentifier() ); txStatus.markAsPrepared(); return XAResource.XA_OK; } } private void oneMoreTransactionRecovered() { recoveredTxCount--; checkIfRecoveryComplete(); } // called from XaResource internal recovery // returns true if read only and should be removed... synchronized boolean injectPrepare( Xid xid ) throws IOException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new IOException( "Unknown xid[" + xid + "]" ); } TransactionStatus txStatus = status.getTransactionStatus(); XaTransaction xaTransaction = txStatus.getTransaction(); if ( xaTransaction.isReadOnly() ) { xidMap.remove( xid ); if ( xaTransaction.isRecovered() ) { oneMoreTransactionRecovered(); } return true; } else { txStatus.setSequenceNumber( nextTxOrder++ ); txStatus.markAsPrepared(); return false; } } private int nextTxOrder = 0; // called during recovery // if not read only transaction will be commited. synchronized void injectOnePhaseCommit( Xid xid ) throws XAException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } TransactionStatus txStatus = status.getTransactionStatus(); txStatus.setSequenceNumber( nextTxOrder++ ); txStatus.markAsPrepared(); txStatus.markCommitStarted(); XaTransaction xaTransaction = txStatus.getTransaction(); xaTransaction.commit(); transactionMonitor.injectOnePhaseCommit( xid ); } synchronized void injectTwoPhaseCommit( Xid xid ) throws XAException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } TransactionStatus txStatus = status.getTransactionStatus(); txStatus.setSequenceNumber( nextTxOrder++ ); txStatus.markAsPrepared(); txStatus.markCommitStarted(); XaTransaction xaTransaction = txStatus.getTransaction(); xaTransaction.commit(); transactionMonitor.injectTwoPhaseCommit( xid ); } synchronized XaTransaction getXaTransaction( Xid xid ) throws XAException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } TransactionStatus txStatus = status.getTransactionStatus(); XaTransaction xaTransaction = txStatus.getTransaction(); return xaTransaction; } /*synchronized(this) in the method*/ XaTransaction commit( Xid xid, boolean onePhase ) throws XAException { XaTransaction xaTransaction; boolean isReadOnly; synchronized ( this ) { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } TransactionStatus txStatus = status.getTransactionStatus(); xaTransaction = txStatus.getTransaction(); TxIdGenerator txIdGenerator = xaTransaction.getTxIdGenerator(); isReadOnly = xaTransaction.isReadOnly(); if(isReadOnly) { // called for one-phase read-only transactions since they skip prepare // cf. TransactionImpl.doCommit() and prepare() commitReadTx( xid, onePhase, xaTransaction, txStatus ); } else { commitWriteTx( xid, onePhase, xaTransaction, txStatus, txIdGenerator ); } } commitKernelTx( xaTransaction ); if ( !xaTransaction.isRecovered() && !isReadOnly ) { try { txIdGenerator.committed( dataSource, xaTransaction.getIdentifier(), xaTransaction.getCommitTxId(), null ); } catch ( Exception e ) { throw new CommitNotificationFailedException( e ); } } return xaTransaction; } private void commitReadTx( Xid xid, boolean onePhase, XaTransaction xaTransaction, TransactionStatus txStatus ) throws XAException { if ( onePhase ) { txStatus.markAsPrepared(); } if ( !txStatus.prepared() || txStatus.rollback() ) { throw new XAException( "Transaction not prepared or " + "(marked as) rolledbacked" ); } if ( !xaTransaction.isRecovered() ) { log.forget( xaTransaction.getIdentifier() ); } xidMap.remove( xid ); if ( xaTransaction.isRecovered() ) { oneMoreTransactionRecovered(); } } private void commitWriteTx( Xid xid, boolean onePhase, XaTransaction xaTransaction, TransactionStatus txStatus, TxIdGenerator txIdGenerator ) throws XAException { checkStartWritten( txStatus, xaTransaction ); if ( onePhase ) { txStatus.markAsPrepared(); if ( !xaTransaction.isRecovered() ) { xaTransaction.prepare(); long txId = txIdGenerator.generate( dataSource, xaTransaction.getIdentifier() ); xaTransaction.setCommitTxId( txId ); // The call to getForceMode() is critical for correctness. // See TxManager.getTransaction() for details. log.commitOnePhase( xaTransaction.getIdentifier(), xaTransaction.getCommitTxId(), getForceMode() ); } } if ( !txStatus.prepared() || txStatus.rollback() ) { throw new XAException( "Transaction not prepared or " + "(marked as) rolledbacked" ); } if ( !onePhase && !xaTransaction.isRecovered() ) { long txId = txIdGenerator.generate( dataSource, xaTransaction.getIdentifier() ); xaTransaction.setCommitTxId( txId ); // The call to getForceMode() is critical for correctness. // See TxManager.getTransaction() for details. log.commitTwoPhase( xaTransaction.getIdentifier(), xaTransaction.getCommitTxId(), getForceMode() ); } txStatus.markCommitStarted(); if ( xaTransaction.isRecovered() && xaTransaction.getCommitTxId() == -1 ) { boolean previousRecoveredValue = dataSource.setRecovered( true ); try { xaTransaction.setCommitTxId( dataSource.getLastCommittedTxId() + 1 ); } finally { dataSource.setRecovered( previousRecoveredValue ); } } xaTransaction.commit(); if ( !xaTransaction.isRecovered() ) { log.done( xaTransaction.getIdentifier() ); } else if ( !log.scanIsComplete() || recoveredTxCount > 0 ) { int identifier = xaTransaction.getIdentifier(); Start startEntry = log.getStartEntry( identifier ); recoveredTransactions.put( identifier, new TransactionInfo( identifier, onePhase, xaTransaction.getCommitTxId(), startEntry.getMasterId(), startEntry.getChecksum() ) ); } xidMap.remove( xid ); if ( xaTransaction.isRecovered() ) { oneMoreTransactionRecovered(); } transactionMonitor.transactionCommitted( xid, xaTransaction.isRecovered() ); } private ForceMode getForceMode() { return transactionManager.getForceMode(); } synchronized XaTransaction rollback( Xid xid ) throws XAException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new XAException( "Unknown xid[" + xid + "]" ); } TransactionStatus txStatus = status.getTransactionStatus(); XaTransaction xaTransaction = txStatus.getTransaction(); checkStartWritten( txStatus, xaTransaction ); if ( txStatus.commitStarted() ) { throw new XAException( "Transaction already started commit" ); } txStatus.markAsRollback(); xaTransaction.rollback(); rollbackKernelTx( xaTransaction ); log.done( xaTransaction.getIdentifier() ); xidMap.remove( xid ); if ( xaTransaction.isRecovered() ) { oneMoreTransactionRecovered(); } return txStatus.getTransaction(); } synchronized XaTransaction forget( Xid xid ) throws XAException { XidStatus status = xidMap.get( xid ); if ( status == null ) { // START record has not been applied, // so we don't have a transaction return null; } TransactionStatus txStatus = status.getTransactionStatus(); XaTransaction xaTransaction = txStatus.getTransaction(); if(!xaTransaction.isReadOnly()) { checkStartWritten( txStatus, xaTransaction ); log.done( xaTransaction.getIdentifier() ); } xidMap.remove( xid ); if ( xaTransaction.isRecovered() ) { oneMoreTransactionRecovered(); } return xaTransaction; } synchronized Xid[] recover( int flag ) throws XAException { List<Xid> xids = new ArrayList<Xid>(); Iterator<Xid> keyIterator = xidMap.keySet().iterator(); while ( keyIterator.hasNext() ) { xids.add( keyIterator.next() ); } return xids.toArray( new Xid[xids.size()] ); } // called from neostore internal recovery synchronized void pruneXid( Xid xid ) throws IOException { XidStatus status = xidMap.get( xid ); if ( status == null ) { throw new IOException( "Unknown xid[" + xid + "]" ); } TransactionStatus txStatus = status.getTransactionStatus(); XaTransaction xaTransaction = txStatus.getTransaction(); xidMap.remove( xid ); if ( xaTransaction.isRecovered() ) { recoveredTransactions.remove( xaTransaction.getIdentifier() ); oneMoreTransactionRecovered(); } } synchronized void checkXids() throws IOException { msgLog.logMessage( "XaResourceManager[" + name + "] sorting " + xidMap.size() + " xids" ); Iterator<Xid> keyIterator = xidMap.keySet().iterator(); LinkedList<Xid> xids = new LinkedList<>(); while ( keyIterator.hasNext() ) { xids.add( keyIterator.next() ); } // comparator only used here Collections.sort( xids, new Comparator<Xid>() { @Override public int compare( Xid o1, Xid o2 ) { TransactionStatus a = xidMap.get( o1 ).txStatus; TransactionStatus b = xidMap.get( o2 ).txStatus; return a.compareTo( b ); } } ); while ( !xids.isEmpty() ) { Xid xid = xids.removeFirst(); XidStatus status = xidMap.get( xid ); TransactionStatus txStatus = status.getTransactionStatus(); XaTransaction xaTransaction = txStatus.getTransaction(); int identifier = xaTransaction.getIdentifier(); if ( xaTransaction.isRecovered() ) { if ( txStatus.commitStarted() ) { msgLog.debug( "Marking 1PC [" + name + "] tx " + identifier + " as done" ); log.doneInternal( identifier ); xidMap.remove( xid ); recoveredTxCount--; } else if ( !txStatus.prepared() ) { msgLog.debug( "Rolling back non prepared tx [" + name + "]" + "txIdent[" + identifier + "]" ); log.doneInternal( xaTransaction.getIdentifier() ); xidMap.remove( xid ); recoveredTxCount--; } else { msgLog.debug( "2PC tx [" + name + "] " + txStatus + " txIdent[" + identifier + "]" ); } } } checkIfRecoveryComplete(); } private void checkIfRecoveryComplete() { if ( log.scanIsComplete() && recoveredTxCount == 0 ) { msgLog.logMessage( "XaResourceManager[" + name + "] checkRecoveryComplete " + xidMap.size() + " xids" ); // log.makeNewLog(); tf.recoveryComplete(); try { for ( TransactionInfo recoveredTx : sortByTxId( recoveredTransactions.values() ) ) { if ( recoveryVerifier != null && !recoveryVerifier.isValid( recoveredTx ) ) { throw new RecoveryVerificationException( recoveredTx.getIdentifier(), recoveredTx.getTxId() ); } if ( !recoveredTx.isOnePhase() ) { log.commitTwoPhase( recoveredTx.getIdentifier(), recoveredTx.getTxId(), ForceMode.forced ); } log.doneInternal( recoveredTx.getIdentifier() ); } recoveredTransactions.clear(); } catch ( IOException e ) { // TODO Why only printStackTrace? e.printStackTrace(); } catch ( XAException e ) { // TODO Why only printStackTrace? e.printStackTrace(); } msgLog.logMessage( "XaResourceManager[" + name + "] recovery completed." ); } } private Iterable<TransactionInfo> sortByTxId( Collection<TransactionInfo> set ) { List<TransactionInfo> list = new ArrayList<>( set ); Collections.sort( list ); return list; } // for testing, do not use! synchronized void reset() { xaResourceMap.clear(); xidMap.clear(); log.reset(); } /** * Returns <CODE>true</CODE> if recovered transactions exist. This method * is useful to invoke after the logical log has been opened to detirmine if * there are any recovered transactions waiting for the TM to tell them what * to do. * * @return True if recovered transactions exist */ public boolean hasRecoveredTransactions() { return recoveredTxCount > 0; } public synchronized void applyCommittedTransaction( ReadableByteChannel transaction, long txId ) throws IOException { long lastCommittedTxId = dataSource.getLastCommittedTxId(); if ( lastCommittedTxId + 1 == txId ) { log.applyTransaction( transaction ); } else if ( lastCommittedTxId + 1 < txId ) { throw new IOException( "Tried to apply transaction with txId=" + txId + " but last committed txId=" + lastCommittedTxId ); } } public synchronized long applyPreparedTransaction( ReadableByteChannel transaction ) throws IOException { try { long txId = TxIdGenerator.DEFAULT.generate( dataSource, 0 ); log.applyTransactionWithoutTxId( transaction, txId, getForceMode() ); return txId; } catch ( XAException e ) { throw new RuntimeException( e ); } } public synchronized long rotateLogicalLog() throws IOException { return log.rotate(); } XaDataSource getDataSource() { return dataSource; } private void commitKernelTx( XaTransaction xaTransaction ) throws XAException { if ( !(xaTransaction instanceof NeoStoreTransaction) ) { return; } try { NeoStoreTransaction neoStoreTransaction = (NeoStoreTransaction)xaTransaction; neoStoreTransaction.commitChangesToCache(); neoStoreTransaction.kernelTransaction().commit(); } catch ( TransactionFailureException e ) { throw e.unBoxedForCommit(); } } private void rollbackKernelTx( XaTransaction xaTransaction ) throws XAException { // Hack until the WriteTx/KernelTx structure is sorted out if ( !(xaTransaction instanceof NeoStoreTransaction) ) { return; } try { ((NeoStoreTransaction)xaTransaction).kernelTransaction().rollback(); } catch ( TransactionFailureException e ) { throw e.unBoxedForCommit(); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaResourceManager.java
643
public abstract class XaResourceHelpImpl implements XaResource { private int transactionTimeout = 120; private XaTransaction xaTx = null; private final XaResourceManager xaRm; private byte[] branchId = null; protected XaResourceHelpImpl( XaResourceManager xaRm, byte branchId[] ) { this.xaRm = xaRm; this.branchId = branchId; } /** * If the transaction commited successfully this method will return the * transaction. * * @return transaction if completed else <CODE>null</CODE> */ public XaTransaction getCompletedTx() { return xaTx; } /** * Should return true if <CODE>xares</CODE> is the same resource as * <CODE>this</CODE>. * * @return true if the resource is same */ public abstract boolean isSameRM( XAResource xares ); public void commit( Xid xid, boolean onePhase ) throws XAException { xaTx = xaRm.commit( xid, onePhase ); } public void end( Xid xid, int flags ) throws XAException { if ( flags == XAResource.TMSUCCESS ) { xaRm.end( this, xid ); } else if ( flags == XAResource.TMSUSPEND ) { xaRm.suspend( xid ); } else if ( flags == XAResource.TMFAIL ) { xaRm.fail( this, xid ); } } public void forget( Xid xid ) throws XAException { xaRm.forget( xid ); } public int getTransactionTimeout() { return transactionTimeout; } public boolean setTransactionTimeout( int timeout ) { transactionTimeout = timeout; return true; } public int prepare( Xid xid ) throws XAException { return xaRm.prepare( xid ); } public Xid[] recover( int flag ) throws XAException { return xaRm.recover( flag ); } public void rollback( Xid xid ) throws XAException { xaRm.rollback( xid ); } public void start( Xid xid, int flags ) throws XAException { xaTx = null; if ( flags == XAResource.TMNOFLAGS ) { xaRm.start( this, xid ); } else if ( flags == XAResource.TMRESUME ) { xaRm.resume( xid ); } else if ( flags == XAResource.TMJOIN ) { xaRm.join( this, xid ); } else { throw new XAException( "Unknown flag[" + flags + "]" ); } } public byte[] getBranchId() { return this.branchId; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaResourceHelpImpl.java
644
public class XaLogicalLogTokens { public static final char CLEAN = 'C'; public static final char LOG1 = '1'; public static final char LOG2 = '2'; }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogTokens.java
645
private static class VersionRespectingXaTransactionFactory extends XaTransactionFactory { private long currentVersion = 0; @Override public XaTransaction create( long lastCommittedTxWhenTransactionStarted, TransactionState state) { return mock( XaTransaction.class ); } @Override public void flushAll() { // Nothing to flush } @Override public long getCurrentVersion() { return currentVersion; } @Override public long getAndSetNewVersion() { return ++currentVersion; } @Override public void setVersion( long version ) { this.currentVersion = version; } @Override public long getLastCommittedTx() { return 0; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogTest.java
646
private class TxVersion implements Answer<Object> { private final boolean update; public static final boolean UPDATE_AND_GET = true, GET = false; TxVersion( boolean update ) { this.update = update; } @Override public Object answer( InvocationOnMock invocation ) throws Throwable { synchronized ( XaLogicalLogTest.this ) { if ( update ) { version++; } return version; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogTest.java
647
private static class FixedSizeXaCommandFactory extends XaCommandFactory { @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { short dataSize = IoPrimitiveUtils.readShort( byteChannel, buffer ); IoPrimitiveUtils.readBytes( byteChannel, new byte[dataSize] ); return new FixedSizeXaCommand( dataSize ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogTest.java
648
private static class FixedSizeXaCommand extends XaCommand { private final byte[] data; FixedSizeXaCommand( int payloadSize ) { this.data = new byte[payloadSize-2/*2 bytes for describing which size will follow*/]; } @Override public void execute() { // There's nothing to execute } @Override public void writeToFile( LogBuffer buffer ) throws IOException { buffer.putShort( (short) (data.length+2) ); buffer.put( data ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogTest.java
649
{ @Override public void reportInvocation( MethodInvocationReport methodInvocationReport ) { if ( methodInvocationReport.getInvocation().toString().startsWith( "channel.read(" ) ) { reads++; } } } ) );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogTest.java
650
{ @Override public StoreChannel answer( InvocationOnMock invocation ) throws Throwable { StoreFileChannel channel = (StoreFileChannel) invocation.callRealMethod(); return mock( channel.getClass(), withSettings() .spiedInstance( channel ) .name( "channel" ) .defaultAnswer( CALLS_REAL_METHODS ) .invocationListeners( new InvocationListener() { @Override public void reportInvocation( MethodInvocationReport methodInvocationReport ) { if ( methodInvocationReport.getInvocation().toString().startsWith( "channel.read(" ) ) { reads++; } } } ) ); } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogTest.java
651
public class XaLogicalLogTest { @Rule public final FailureOutput output = new FailureOutput(); private static final byte[] RESOURCE_ID = new byte[]{0x00, (byte) 0x99, (byte) 0xcc}; private long version; private int reads; @Test public void shouldNotReadExcessivelyFromTheFileChannelWhenRotatingLogWithNoOpenTransactions() throws Exception { // given XaTransactionFactory xaTf = mock( XaTransactionFactory.class ); when( xaTf.getAndSetNewVersion() ).thenAnswer( new TxVersion( TxVersion.UPDATE_AND_GET ) ); when( xaTf.getCurrentVersion() ).thenAnswer( new TxVersion( TxVersion.GET ) ); // spy on the file system abstraction so that we can spy on the file channel for the logical log FileSystemAbstraction fs = spy( ephemeralFs.get() ); File dir = TargetDirectory.forTest( fs, XaLogicalLogTest.class ).cleanDirectory( "log" ); // -- when opening the logical log, spy on the file channel we return and count invocations to channel.read(*) when( fs.open( new File( dir, "logical.log.1" ), "rw" ) ).thenAnswer( new Answer<StoreChannel>() { @Override public StoreChannel answer( InvocationOnMock invocation ) throws Throwable { StoreFileChannel channel = (StoreFileChannel) invocation.callRealMethod(); return mock( channel.getClass(), withSettings() .spiedInstance( channel ) .name( "channel" ) .defaultAnswer( CALLS_REAL_METHODS ) .invocationListeners( new InvocationListener() { @Override public void reportInvocation( MethodInvocationReport methodInvocationReport ) { if ( methodInvocationReport.getInvocation().toString().startsWith( "channel.read(" ) ) { reads++; } } } ) ); } } ); XaLogicalLog xaLogicalLog = new XaLogicalLog( new File( dir, "logical.log" ), mock( XaResourceManager.class ), mock( XaCommandFactory.class ), xaTf, fs, new Monitors(), new SingleLoggingService( StringLogger.wrap( output.writer() ) ), LogPruneStrategies.NO_PRUNING, mock( TransactionStateFactory.class ), mock( KernelHealth.class ), 25 * 1024 * 1024, ALLOW_ALL ); xaLogicalLog.open(); // -- set the log up with 10 transactions (with no commands, just start and commit) for ( int txId = 1; txId <= 10; txId++ ) { int identifier = xaLogicalLog.start( new XidImpl( getNewGlobalId( DEFAULT_SEED, 0 ), RESOURCE_ID ), -1, 0, 1337 ); xaLogicalLog.writeStartEntry( identifier ); xaLogicalLog.commitOnePhase( identifier, txId, ForceMode.forced ); xaLogicalLog.done( identifier ); } // when xaLogicalLog.rotate(); // then assertThat( "should not read excessively from the logical log file channel", reads, lessThan( 10 ) ); } @Test public void shouldRespectCustomLogRotationThreshold() throws Exception { // GIVEN long maxSize = 1000; ephemeralFs.get().mkdir( new File("asd") ); XaLogicalLog log = new XaLogicalLog( new File( "asd/log" ), mock( XaResourceManager.class ), new FixedSizeXaCommandFactory(), new VersionRespectingXaTransactionFactory(), ephemeralFs.get(), new Monitors(), new DevNullLoggingService(), NO_PRUNING, mock( TransactionStateFactory.class ), mock( KernelHealth.class ), maxSize, ALLOW_ALL ); log.open(); long initialLogVersion = log.getHighestLogVersion(); // WHEN for ( int i = 0; i < 10; i++ ) { int identifier = log.start( xid, -1, -1, 1337 ); log.writeStartEntry( identifier ); log.writeCommand( new FixedSizeXaCommand( 100 ), identifier ); log.commitOnePhase( identifier, i+1, forced ); log.done( identifier ); } // THEN assertEquals( initialLogVersion+1, log.getHighestLogVersion() ); } @Test public void shouldDetermineHighestArchivedLogVersionFromFileNamesIfTheyArePresent() throws Exception { // Given int lowAndIncorrectLogVersion = 0; EphemeralFileSystemAbstraction fs = ephemeralFs.get(); File dir = new File( "db" ); fs.mkdir( dir ); fs.create( new File(dir, "log.v100") ).close(); fs.create( new File(dir, "log.v101") ).close(); StoreChannel active = fs.create( new File(dir, "log.1" ) ); ByteBuffer buff = ByteBuffer.allocate( 128 ); LogIoUtils.writeLogHeader( buff, lowAndIncorrectLogVersion, 0 ); active.write( buff ); active.force( false ); active.close(); // When XaLogicalLog log = new XaLogicalLog( new File(dir, "log" ), mock( XaResourceManager.class ), new FixedSizeXaCommandFactory(), new VersionRespectingXaTransactionFactory(), ephemeralFs.get(), new Monitors(), new DevNullLoggingService(), NO_PRUNING, mock( TransactionStateFactory.class ), mock( KernelHealth.class ), 10, ALLOW_ALL ); log.open(); log.rotate(); // Then assertThat( fs.fileExists( new File( dir, "log.v102" ) ), equalTo( true ) ); } private static class FixedSizeXaCommand extends XaCommand { private final byte[] data; FixedSizeXaCommand( int payloadSize ) { this.data = new byte[payloadSize-2/*2 bytes for describing which size will follow*/]; } @Override public void execute() { // There's nothing to execute } @Override public void writeToFile( LogBuffer buffer ) throws IOException { buffer.putShort( (short) (data.length+2) ); buffer.put( data ); } } private static class FixedSizeXaCommandFactory extends XaCommandFactory { @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { short dataSize = IoPrimitiveUtils.readShort( byteChannel, buffer ); IoPrimitiveUtils.readBytes( byteChannel, new byte[dataSize] ); return new FixedSizeXaCommand( dataSize ); } } private class TxVersion implements Answer<Object> { private final boolean update; public static final boolean UPDATE_AND_GET = true, GET = false; TxVersion( boolean update ) { this.update = update; } @Override public Object answer( InvocationOnMock invocation ) throws Throwable { synchronized ( XaLogicalLogTest.this ) { if ( update ) { version++; } return version; } } } private static class VersionRespectingXaTransactionFactory extends XaTransactionFactory { private long currentVersion = 0; @Override public XaTransaction create( long lastCommittedTxWhenTransactionStarted, TransactionState state) { return mock( XaTransaction.class ); } @Override public void flushAll() { // Nothing to flush } @Override public long getCurrentVersion() { return currentVersion; } @Override public long getAndSetNewVersion() { return ++currentVersion; } @Override public void setVersion( long version ) { this.currentVersion = version; } @Override public long getLastCommittedTx() { return 0; } } public final @Rule EphemeralFileSystemRule ephemeralFs = new EphemeralFileSystemRule(); public final Xid xid = new XidImpl( "global".getBytes(), "resource".getBytes() ); }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogTest.java
652
public class XaLogicalLogRecoveryCheck { private final StoreChannel fileChannel; public XaLogicalLogRecoveryCheck( StoreChannel fileChannel ) { this.fileChannel = fileChannel; } public boolean recoveryRequired() throws IOException { return fileChannel.size() != 0; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogRecoveryCheck.java
653
public class XaLogicalLogFiles { private static final String ACTIVE_FILE_SUFFIX = ".active"; private static final String LOG_2_SUFFIX = ".2"; private static final String LOG_1_SUFFIX = ".1"; public static enum State { /** * Old < b8 xaframework with no log rotation */ LEGACY_WITHOUT_LOG_ROTATION, /** * No .active file to tell us the state of * affairs, and no legacy logical log file. * TODO: Describe this state better. */ NO_ACTIVE_FILE, /** * Cleanly shut down log files. */ CLEAN, /** * Log 1 is currently active. */ LOG_1_ACTIVE, /** * Log 2 is currently active. */ LOG_2_ACTIVE, /** * Log 1 is active, but log 2 is also * present. */ DUAL_LOGS_LOG_1_ACTIVE, /** * Log 2 is active, but log 1 is also * present. */ DUAL_LOGS_LOG_2_ACTIVE } private File logBaseName; private FileSystemAbstraction fileSystem; public XaLogicalLogFiles(File fileName, FileSystemAbstraction fileSystem) { this.logBaseName = fileName; this.fileSystem = fileSystem; } public State determineState() throws IOException { File activeFileName = new File( logBaseName.getPath() + ACTIVE_FILE_SUFFIX); if ( !fileSystem.fileExists( activeFileName ) ) { if ( fileSystem.fileExists( logBaseName ) ) { // old < b8 xaframework with no log rotation and we need to // do recovery on it return State.LEGACY_WITHOUT_LOG_ROTATION; } else { return State.NO_ACTIVE_FILE; } } else { StoreChannel fc = null; byte bytes[] = new byte[256]; ByteBuffer buf = ByteBuffer.wrap( bytes ); int read = 0; try { fc = fileSystem.open( activeFileName, "rw" ); read = fc.read( buf ); } finally { if(fc != null) fc.close(); } if ( read != 4 ) { throw new IllegalStateException( "Read " + read + " bytes from " + activeFileName + " but expected 4" ); } buf.flip(); char c = buf.asCharBuffer().get(); if ( c == CLEAN ) { return State.CLEAN; } else if ( c == LOG1 ) { if ( !fileSystem.fileExists( getLog1FileName() ) ) { throw new IllegalStateException( "Active marked as 1 but no " + getLog1FileName() + " exist" ); } if ( fileSystem.fileExists( getLog2FileName() ) ) { return State.DUAL_LOGS_LOG_1_ACTIVE; } return State.LOG_1_ACTIVE; } else if ( c == LOG2 ) { if ( !fileSystem.fileExists( getLog2FileName() ) ) { throw new IllegalStateException( "Active marked as 2 but no " + getLog2FileName() + " exist" ); } if ( fileSystem.fileExists( getLog1FileName() ) ) { return State.DUAL_LOGS_LOG_2_ACTIVE; } return State.LOG_2_ACTIVE; } else { throw new IllegalStateException( "Unknown active log: " + c ); } } } public File getLog1FileName() { return new File( logBaseName.getPath() + LOG_1_SUFFIX); } public File getLog2FileName() { return new File( logBaseName.getPath() + LOG_2_SUFFIX); } /** * Use the archived logical log files to determine the next-in-line logical log version. * If no log files are present, return fallbackVersion. */ public long determineNextLogVersion(long fallbackVersion) { /* This is for compensating for that, during rotation, renaming the active log * file and updating the log version via xaTf isn't atomic. First the file gets * renamed and then the version is updated. If a crash occurs in between those * two we need to detect and repair it the next startup... * and here's the code for doing that. */ long highestSeen = -1; for ( File file : fileSystem.listFiles( logBaseName.getParentFile() ) ) { String fileName = file.getName(); if( fileName.startsWith( logBaseName.getName() )) { Pattern p = Pattern.compile( "^.*\\.v([0-9]+)$" ); Matcher m = p.matcher(fileName); if(m.find()) { highestSeen = Math.max(highestSeen, Integer.parseInt(m.group(1))); } } } return highestSeen > -1 ? highestSeen + 1 : fallbackVersion; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLogFiles.java
654
protected class LogDeserializer { private final ReadableByteChannel byteChannel; LogEntry.Start startEntry; LogEntry.Commit commitEntry; private final List<LogEntry> logEntries; protected LogDeserializer( ReadableByteChannel byteChannel, ByteCounterMonitor monitor ) { this.byteChannel = new MonitoredReadableByteChannel( byteChannel, monitor ); this.logEntries = new LinkedList<LogEntry>(); } public boolean readAndWriteAndApplyEntry( int newXidIdentifier ) throws IOException { LogEntry entry = LogIoUtils.readEntry( sharedBuffer, byteChannel, cf ); if ( entry == null ) { try { intercept( logEntries ); apply(); return false; } catch ( Throwable e ) { startEntry = null; commitEntry = null; kernelHealth.panic( e ); throw launderedException( IOException.class, "Failure applying transaction", e ); } } entry.setIdentifier( newXidIdentifier ); logEntries.add( entry ); if ( entry instanceof LogEntry.Commit ) { assert startEntry != null; commitEntry = (LogEntry.Commit) entry; } else if ( entry instanceof LogEntry.Start ) { startEntry = (LogEntry.Start) entry; } return true; } protected void intercept( List<LogEntry> logEntries ) { // default do nothing } protected void apply() throws IOException { for ( LogEntry entry : logEntries ) { /* * You are wondering what is going on here. Let me take you on a journey * A transaction, call it A starts, prepares locally, goes to the master and commits there * but doesn't quite make it back here, meaning its application is pending, with only the * start, command and possibly prepare entries but not the commit, the Xid in xidmap * Another transaction, B, does an operation that requires going to master and pull updates - does * that, gets all transactions not present locally (hence, A as well) and injects it. * The Start entry is the first one extracted - if we try to apply it it will throw a Start * entry already injected exception, since the Xid will match an ongoing transaction. If we * had written that to the log recovery would be impossible, constantly throwing the same * exception. So first apply, then write to log. * However we cannot do that for every entry - commit must always be written to log first, then * applied because a crash in the mean time could cause partially applied transactions. * The start entry does not have this problem because if it fails nothing will ever be applied - * the same goes for commands but we don't care about those. */ if ( entry instanceof Start ) { ((Start) entry).setStartPosition( writeBuffer.getFileChannelPosition() ); applyEntry( entry ); LogIoUtils.writeLogEntry( entry, writeBuffer ); } else { LogIoUtils.writeLogEntry( entry, writeBuffer ); if ( entry instanceof LogEntry.Commit ) { /* * Just writeOut(), don't force or performance will be impacted severely. */ writeBuffer.writeOut(); } applyEntry( entry ); } } } protected Start getStartEntry() { return startEntry; } protected Commit getCommitEntry() { return commitEntry; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLog.java
655
{ @Override public LogBuffer createActiveLogFile( Config config, long prevCommittedId ) throws IllegalStateException, IOException { File activeLogFile = new XaLogicalLogFiles( logBasePath.apply( config ), fileSystem ).getLog1FileName(); StoreChannel channel = fileSystem.create( activeLogFile ); ByteBuffer scratch = ByteBuffer.allocateDirect( 128 ); LogIoUtils.writeLogHeader( scratch, 0, prevCommittedId ); while(scratch.hasRemaining()) { channel.write( scratch ); } scratch.clear(); return new DirectLogBuffer( channel, scratch ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLog.java
656
public class XaLogicalLog implements LogLoader { private StoreChannel fileChannel = null; private final ByteBuffer sharedBuffer; private LogBuffer writeBuffer = null; private long previousLogLastCommittedTx = -1; private long logVersion = 0; private final ArrayMap<Integer, LogEntry.Start> xidIdentMap = new ArrayMap<Integer, LogEntry.Start>( (byte) 4, false, true ); private final Map<Integer, XaTransaction> recoveredTxMap = new HashMap<Integer, XaTransaction>(); private int nextIdentifier = 1; private boolean scanIsComplete = false; private boolean nonCleanShutdown = false; private final File fileName; private final XaResourceManager xaRm; private final XaCommandFactory cf; private final XaTransactionFactory xaTf; private char currentLog = CLEAN; private boolean autoRotate; private long rotateAtSize; private boolean doingRecovery; private long lastRecoveredTx = -1; private final StringLogger msgLog; private final LogPositionCache positionCache = new LogPositionCache(); private final FileSystemAbstraction fileSystem; private final LogPruneStrategy pruneStrategy; private final XaLogicalLogFiles logFiles; private final PartialTransactionCopier partialTransactionCopier; private final InjectedTransactionValidator injectedTxValidator; private final TransactionStateFactory stateFactory; // Monitors for counting bytes read/written in various parts // We need separate monitors to differentiate between network/disk I/O protected final ByteCounterMonitor bufferMonitor; protected final ByteCounterMonitor logDeserializerMonitor; private final KernelHealth kernelHealth; public XaLogicalLog( File fileName, XaResourceManager xaRm, XaCommandFactory cf, XaTransactionFactory xaTf, FileSystemAbstraction fileSystem, Monitors monitors, Logging logging, LogPruneStrategy pruneStrategy, TransactionStateFactory stateFactory, KernelHealth kernelHealth, long rotateAtSize, InjectedTransactionValidator injectedTxValidator ) { this.fileName = fileName; this.xaRm = xaRm; this.cf = cf; this.xaTf = xaTf; this.fileSystem = fileSystem; this.kernelHealth = kernelHealth; this.bufferMonitor = monitors.newMonitor( ByteCounterMonitor.class, XaLogicalLog.class ); this.logDeserializerMonitor = monitors.newMonitor( ByteCounterMonitor.class, "logdeserializer" ); this.pruneStrategy = pruneStrategy; this.stateFactory = stateFactory; this.rotateAtSize = rotateAtSize; this.autoRotate = rotateAtSize > 0; this.logFiles = new XaLogicalLogFiles( fileName, fileSystem ); sharedBuffer = ByteBuffer.allocateDirect( 9 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE * 10 ); msgLog = logging.getMessagesLog( getClass() ); this.partialTransactionCopier = new PartialTransactionCopier( sharedBuffer, cf, msgLog, positionCache, this, xidIdentMap, monitors.newMonitor( ByteCounterMonitor.class, getClass(), "copier" ) ); this.injectedTxValidator = injectedTxValidator; } synchronized void open() throws IOException { switch ( logFiles.determineState() ) { case LEGACY_WITHOUT_LOG_ROTATION: open( fileName ); break; case NO_ACTIVE_FILE: open( logFiles.getLog1FileName() ); setActiveLog( LOG1 ); break; case CLEAN: File newLog = logFiles.getLog1FileName(); renameIfExists( newLog ); renameIfExists( logFiles.getLog2FileName() ); open( newLog ); setActiveLog( LOG1 ); break; case DUAL_LOGS_LOG_1_ACTIVE: fixDualLogFiles( logFiles.getLog1FileName(), logFiles.getLog2FileName() ); case LOG_1_ACTIVE: currentLog = LOG1; open( logFiles.getLog1FileName() ); break; case DUAL_LOGS_LOG_2_ACTIVE: fixDualLogFiles( logFiles.getLog2FileName(), logFiles.getLog1FileName() ); case LOG_2_ACTIVE: currentLog = LOG2; open( logFiles.getLog2FileName() ); break; default: throw new IllegalStateException( "FATAL: Unrecognized logical log state." ); } instantiateCorrectWriteBuffer(); } private void renameIfExists( File fileName ) throws IOException { if ( fileSystem.fileExists( fileName ) ) { renameLogFileToRightVersion( fileName, fileSystem.getFileSize( fileName ) ); xaTf.getAndSetNewVersion(); } } private void instantiateCorrectWriteBuffer() throws IOException { writeBuffer = instantiateCorrectWriteBuffer( fileChannel ); } private LogBuffer instantiateCorrectWriteBuffer( StoreChannel channel ) throws IOException { return new DirectMappedLogBuffer( channel, bufferMonitor ); } private void open( File fileToOpen ) throws IOException { fileChannel = fileSystem.open( fileToOpen, "rw" ); if ( new XaLogicalLogRecoveryCheck( fileChannel ).recoveryRequired() ) { nonCleanShutdown = true; doingRecovery = true; try { doInternalRecovery( fileToOpen ); } finally { doingRecovery = false; } } else { logVersion = xaTf.getCurrentVersion(); determineLogVersionFromArchivedFiles(); long lastTxId = xaTf.getLastCommittedTx(); LogIoUtils.writeLogHeader( sharedBuffer, logVersion, lastTxId ); previousLogLastCommittedTx = lastTxId; positionCache.putHeader( logVersion, previousLogLastCommittedTx ); fileChannel.write( sharedBuffer ); scanIsComplete = true; msgLog.info( openedLogicalLogMessage( fileToOpen, lastTxId, true ) ); } } private void determineLogVersionFromArchivedFiles() { long version = logFiles.determineNextLogVersion(/*default=*/logVersion); if(version != logVersion) { logVersion = version; xaTf.setVersion( version ); } } private String openedLogicalLogMessage( File fileToOpen, long lastTxId, boolean clean ) { return "Opened logical log [" + fileToOpen + "] version=" + logVersion + ", lastTxId=" + lastTxId + " (" + (clean ? "clean" : "recovered") + ")"; } public boolean scanIsComplete() { return scanIsComplete; } private int getNextIdentifier() { nextIdentifier++; if ( nextIdentifier < 0 ) { nextIdentifier = 1; } return nextIdentifier; } /** * @param highestKnownCommittedTx is the highest committed tx id when this transaction *started*. This is used * to perform prepare-time checks that need to know the state of the system when * the transaction started. Specifically, it is used by constraint validation, to * ensure that transactions that began before a constraint was enabled are checked * to ensure they do not violate the constraint. */ // returns identifier for transaction // [TX_START][xid[gid.length,bid.lengh,gid,bid]][identifier][format id] public synchronized int start( Xid xid, int masterId, int myId, long highestKnownCommittedTx ) { int xidIdent = getNextIdentifier(); long timeWritten = System.currentTimeMillis(); LogEntry.Start start = new LogEntry.Start( xid, xidIdent, masterId, myId, -1, timeWritten, highestKnownCommittedTx ); /* * We don't write the entry yet. We will store it and hope * that when the commands/commit/prepare/done entry are going to be * written, we will be asked to write the corresponding entry before. */ xidIdentMap.put( xidIdent, start ); return xidIdent; } public synchronized void writeStartEntry( int identifier ) throws XAException { kernelHealth.assertHealthy( XAException.class ); try { long position = writeBuffer.getFileChannelPosition(); LogEntry.Start start = xidIdentMap.get( identifier ); start.setStartPosition( position ); LogIoUtils.writeStart( writeBuffer, identifier, start.getXid(), start.getMasterId(), start.getLocalId(), start.getTimeWritten(), start.getLastCommittedTxWhenTransactionStarted() ); } catch ( IOException e ) { throw Exceptions.withCause( new XAException( "Logical log couldn't write transaction start entry: " + e ), e ); } } synchronized Start getStartEntry( int identifier ) { Start start = xidIdentMap.get( identifier ); if ( start == null ) { throw new IllegalArgumentException( "Start entry for " + identifier + " not found" ); } return start; } // [TX_PREPARE][identifier] public synchronized void prepare( int identifier ) throws XAException { LogEntry.Start startEntry = xidIdentMap.get( identifier ); assert startEntry != null; try { LogIoUtils.writePrepare( writeBuffer, identifier, System.currentTimeMillis() ); /* * Make content visible to all readers of the file channel, so that prepared transactions * can be extracted. Not really necessary, since getLogicalLogOrMyselfCommitted() looks for * force()d content (which is forced by commit{One,Two}Phase()) and getLogicalLogOrMyselfPrepared() * always calls writeOut(). Leaving it here for now. */ writeBuffer.writeOut(); } catch ( IOException e ) { throw Exceptions.withCause( new XAException( "Logical log unable to mark prepare [" + identifier + "] " ), e ); } } public void forget( int identifier ) { xidIdentMap.remove( identifier ); } // [DONE][identifier] public synchronized void done( int identifier ) throws XAException { assert xidIdentMap.get( identifier ) != null; try { LogIoUtils.writeDone( writeBuffer, identifier ); xidIdentMap.remove( identifier ); } catch ( IOException e ) { throw Exceptions.withCause( new XAException( "Logical log unable to mark as done [" + identifier + "] " ), e ); } } // [DONE][identifier] called from XaResourceManager during internal recovery synchronized void doneInternal( int identifier ) throws IOException { if ( writeBuffer != null ) { // For 2PC LogIoUtils.writeDone( writeBuffer, identifier ); } else { // For 1PC sharedBuffer.clear(); LogIoUtils.writeDone( sharedBuffer, identifier ); sharedBuffer.flip(); fileChannel.write( sharedBuffer ); } xidIdentMap.remove( identifier ); } // [TX_1P_COMMIT][identifier] public synchronized void commitOnePhase( int identifier, long txId, ForceMode forceMode ) throws XAException { LogEntry.Start startEntry = xidIdentMap.get( identifier ); assert startEntry != null; assert txId != -1; try { positionCache.cacheStartPosition( txId, startEntry, logVersion ); LogIoUtils.writeCommit( false, writeBuffer, identifier, txId, System.currentTimeMillis() ); forceMode.force( writeBuffer ); } catch ( IOException e ) { throw Exceptions.withCause( new XAException( "Logical log unable to mark 1P-commit [" + identifier + "] " ), e ); } } // [TX_2P_COMMIT][identifier] public synchronized void commitTwoPhase( int identifier, long txId, ForceMode forceMode ) throws XAException { LogEntry.Start startEntry = xidIdentMap.get( identifier ); assert startEntry != null; assert txId != -1; try { positionCache.cacheStartPosition( txId, startEntry, logVersion ); LogIoUtils.writeCommit( true, writeBuffer, identifier, txId, System.currentTimeMillis() ); forceMode.force( writeBuffer ); } catch ( IOException e ) { throw Exceptions.withCause( new XAException( "Logical log unable to mark 2PC [" + identifier + "] " ), e ); } } // [COMMAND][identifier][COMMAND_DATA] public synchronized void writeCommand( XaCommand command, int identifier ) throws IOException { checkLogRotation(); assert xidIdentMap.get( identifier ) != null; LogIoUtils.writeCommand( writeBuffer, identifier, command ); } private void applyEntry( LogEntry entry ) throws IOException { if ( entry instanceof LogEntry.Start ) { applyStartEntry( (LogEntry.Start) entry ); } else if ( entry instanceof LogEntry.Prepare ) { applyPrepareEntry( (LogEntry.Prepare) entry ); } else if ( entry instanceof LogEntry.Command ) { applyCommandEntry( (LogEntry.Command) entry ); } else if ( entry instanceof LogEntry.OnePhaseCommit ) { applyOnePhaseCommitEntry( (LogEntry.OnePhaseCommit) entry ); } else if ( entry instanceof LogEntry.TwoPhaseCommit ) { applyTwoPhaseCommitEntry( (LogEntry.TwoPhaseCommit) entry ); } else if ( entry instanceof LogEntry.Done ) { applyDoneEntry( (LogEntry.Done) entry ); } else { throw new RuntimeException( "Unrecognized log entry " + entry ); } } private void applyStartEntry( LogEntry.Start entry ) throws IOException { int identifier = entry.getIdentifier(); if ( identifier >= nextIdentifier ) { nextIdentifier = identifier + 1; } // re-create the transaction Xid xid = entry.getXid(); xidIdentMap.put( identifier, entry ); XaTransaction xaTx = xaTf.create( entry.getLastCommittedTxWhenTransactionStarted(), stateFactory.create( null ) ); xaTx.setIdentifier( identifier ); xaTx.setRecovered(); recoveredTxMap.put( identifier, xaTx ); xaRm.injectStart( xid, xaTx ); // force to make sure done record is there if 2PC tx and global log // marks tx as committed // fileChannel.force( false ); } private void applyPrepareEntry( LogEntry.Prepare prepareEntry ) throws IOException { // get the tx identifier int identifier = prepareEntry.getIdentifier(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { throw new IOException( "Unknown xid for identifier " + identifier ); } Xid xid = entry.getXid(); if ( xaRm.injectPrepare( xid ) ) { // read only we can remove xidIdentMap.remove( identifier ); recoveredTxMap.remove( identifier ); } } private void applyOnePhaseCommitEntry( LogEntry.OnePhaseCommit commit ) throws IOException { int identifier = commit.getIdentifier(); long txId = commit.getTxId(); LogEntry.Start startEntry = xidIdentMap.get( identifier ); if ( startEntry == null ) { throw new IOException( "Unknown xid for identifier " + identifier ); } Xid xid = startEntry.getXid(); try { XaTransaction xaTx = xaRm.getXaTransaction( xid ); xaTx.setCommitTxId( txId ); positionCache.cacheStartPosition( txId, startEntry, logVersion ); xaRm.injectOnePhaseCommit( xid ); registerRecoveredTransaction( txId ); } catch ( XAException e ) { throw new IOException( e ); } } private void registerRecoveredTransaction( long txId ) { if ( doingRecovery ) { lastRecoveredTx = txId; } } private void logRecoveryMessage( String string ) { if ( doingRecovery ) { msgLog.logMessage( string, true ); } } private void applyDoneEntry( LogEntry.Done done ) throws IOException { // get the tx identifier int identifier = done.getIdentifier(); LogEntry.Start entry = xidIdentMap.get( identifier ); if ( entry == null ) { throw new IOException( "Unknown xid for identifier " + identifier ); } Xid xid = entry.getXid(); xaRm.pruneXid( xid ); xidIdentMap.remove( identifier ); recoveredTxMap.remove( identifier ); } private void applyTwoPhaseCommitEntry( LogEntry.TwoPhaseCommit commit ) throws IOException { int identifier = commit.getIdentifier(); long txId = commit.getTxId(); LogEntry.Start startEntry = xidIdentMap.get( identifier ); if ( startEntry == null ) { throw new IOException( "Unknown xid for identifier " + identifier ); } Xid xid = startEntry.getXid(); if ( xid == null ) { throw new IOException( "Xid null for identifier " + identifier ); } try { XaTransaction xaTx = xaRm.getXaTransaction( xid ); xaTx.setCommitTxId( txId ); positionCache.cacheStartPosition( txId, startEntry, logVersion ); xaRm.injectTwoPhaseCommit( xid ); registerRecoveredTransaction( txId ); } catch ( XAException e ) { throw new IOException( e ); } } private void applyCommandEntry( LogEntry.Command entry ) throws IOException { int identifier = entry.getIdentifier(); XaCommand command = entry.getXaCommand(); if ( command == null ) { throw new IOException( "Null command for identifier " + identifier ); } command.setRecovered(); XaTransaction xaTx = recoveredTxMap.get( identifier ); xaTx.injectCommand( command ); } private void checkLogRotation() throws IOException { if ( autoRotate && writeBuffer.getFileChannelPosition() >= rotateAtSize ) { long currentPos = writeBuffer.getFileChannelPosition(); long firstStartEntry = getFirstStartEntry( currentPos ); // only rotate if no huge tx is running if ( (currentPos - firstStartEntry) < rotateAtSize / 2 ) { rotate(); } } } private void fixDualLogFiles( File activeLog, File oldLog ) throws IOException { StoreChannel activeLogChannel = fileSystem.open( activeLog, "r" ); long[] activeLogHeader = LogIoUtils.readLogHeader( ByteBuffer.allocate( 16 ), activeLogChannel, false ); activeLogChannel.close(); StoreChannel oldLogChannel = fileSystem.open( oldLog, "r" ); long[] oldLogHeader = LogIoUtils.readLogHeader( ByteBuffer.allocate( 16 ), oldLogChannel, false ); oldLogChannel.close(); if ( oldLogHeader == null ) { if ( !fileSystem.deleteFile( oldLog ) ) { throw new IOException( "Unable to delete " + oldLog ); } } else if ( activeLogHeader == null || activeLogHeader[0] > oldLogHeader[0] ) { // we crashed in rotate after setActive but did not move the old log to the right name // (and we do not know if keepLogs is true or not so play it safe by keeping it) File newName = getFileName( oldLogHeader[0] ); if ( !fileSystem.renameFile( oldLog, newName ) ) { throw new IOException( "Unable to rename " + oldLog + " to " + newName ); } } else { assert activeLogHeader[0] < oldLogHeader[0]; // we crashed in rotate before setActive, do the rotate work again and delete old if ( !fileSystem.deleteFile( oldLog ) ) { throw new IOException( "Unable to delete " + oldLog ); } } } private void renameLogFileToRightVersion( File logFileName, long endPosition ) throws IOException { if ( !fileSystem.fileExists( logFileName ) ) { throw new IOException( "Logical log[" + logFileName + "] not found" ); } StoreChannel channel = fileSystem.open( logFileName, "rw" ); long[] header = LogIoUtils.readLogHeader( ByteBuffer.allocate( 16 ), channel, false ); try { FileUtils.truncateFile( channel, endPosition ); } catch ( IOException e ) { msgLog.warn( "Failed to truncate log at correct size", e ); } channel.close(); File newName; if ( header == null ) { // header was never written newName = new File( getFileName( -1 ).getPath() + "_empty_header_log_" + System.currentTimeMillis()); } else { newName = getFileName( header[0] ); } if ( !fileSystem.renameFile( logFileName, newName ) ) { throw new IOException( "Failed to rename log to: " + newName ); } } private void releaseCurrentLogFile() throws IOException { if ( writeBuffer != null ) { writeBuffer.force(); } fileChannel.close(); fileChannel = null; } public synchronized void close() throws IOException { if ( fileChannel == null || !fileChannel.isOpen() ) { msgLog.debug( "Logical log: " + fileName + " already closed" ); return; } long endPosition = writeBuffer.getFileChannelPosition(); if ( xidIdentMap.size() > 0 ) { msgLog.info( "Close invoked with " + xidIdentMap.size() + " running transaction(s). " ); writeBuffer.force(); fileChannel.close(); msgLog.info( "Dirty log: " + fileName + "." + currentLog + " now closed. Recovery will be started automatically next " + "time it is opened." ); return; } releaseCurrentLogFile(); char logWas = currentLog; if ( currentLog != CLEAN ) // again special case, see above { setActiveLog( CLEAN ); } xaTf.flushAll(); File activeLogFileName = new File( fileName.getPath() + "." + logWas); renameLogFileToRightVersion( activeLogFileName, endPosition ); xaTf.getAndSetNewVersion(); pruneStrategy.prune( this ); msgLog.info( "Closed log " + fileName ); } static long[] readAndAssertLogHeader( ByteBuffer localBuffer, ReadableByteChannel channel, long expectedVersion ) throws IOException { long[] header = LogIoUtils.readLogHeader( localBuffer, channel, true ); if ( header[0] != expectedVersion ) { throw new IOException( "Wrong version in log. Expected " + expectedVersion + ", but got " + header[0] ); } return header; } StringLogger getStringLogger() { return msgLog; } private void doInternalRecovery( File logFileName ) throws IOException { msgLog.info( "Non clean shutdown detected on log [" + logFileName + "]. Recovery started ..." ); // get log creation time long[] header = readLogHeader( fileChannel, "Tried to do recovery on log with illegal format version" ); if ( header == null ) { msgLog.info( "Unable to read header information, " + "no records in logical log." ); msgLog.logMessage( "No log version found for " + logFileName, true ); fileChannel.close(); boolean success = fileSystem.renameFile( logFileName, new File( logFileName.getPath() + "_unknown_timestamp_" + System.currentTimeMillis() + ".log") ); assert success; fileChannel.close(); fileChannel = fileSystem.open( logFileName, "rw" ); return; } // Even though we use the archived files to tell the next-in-line log version, if there are no files present // we need a fallback. By default, we fall back to logVersion, so just set that and then run the relevant logic. logVersion = header[0]; determineLogVersionFromArchivedFiles(); // If the header contained the wrong version, we need to change it. This can happen during store copy or backup, // because those routines create artificial active files to trigger recovery. if(header[0] != logVersion) { ByteBuffer buff = ByteBuffer.allocate( 64 ); LogIoUtils.writeLogHeader( buff, logVersion, header[1] ); fileChannel.write( buff, 0 ); } long lastCommittedTx = header[1]; previousLogLastCommittedTx = lastCommittedTx; positionCache.putHeader( logVersion, previousLogLastCommittedTx ); msgLog.logMessage( "[" + logFileName + "] logVersion=" + logVersion + " with committed tx=" + lastCommittedTx, true ); long logEntriesFound = 0; long lastEntryPos = fileChannel.position(); fileChannel = new BufferedFileChannel( fileChannel, bufferMonitor ); LogEntry entry; while ( (entry = readEntry()) != null ) { applyEntry( entry ); logEntriesFound++; lastEntryPos = fileChannel.position(); } // make sure we overwrite any broken records fileChannel = ((BufferedFileChannel) fileChannel).getSource(); fileChannel.position( lastEntryPos ); msgLog.logMessage( "[" + logFileName + "] entries found=" + logEntriesFound + " lastEntryPos=" + lastEntryPos, true ); // zero out the slow way since windows don't support truncate very well sharedBuffer.clear(); while ( sharedBuffer.hasRemaining() ) { sharedBuffer.put( (byte) 0 ); } sharedBuffer.flip(); long endPosition = fileChannel.size(); do { long bytesLeft = fileChannel.size() - fileChannel.position(); if ( bytesLeft < sharedBuffer.capacity() ) { sharedBuffer.limit( (int) bytesLeft ); } fileChannel.write( sharedBuffer ); sharedBuffer.flip(); } while ( fileChannel.position() < endPosition ); fileChannel.position( lastEntryPos ); scanIsComplete = true; String recoveryCompletedMessage = openedLogicalLogMessage( logFileName, lastRecoveredTx, false ); msgLog.logMessage( recoveryCompletedMessage ); xaRm.checkXids(); if ( xidIdentMap.size() == 0 ) { msgLog.logMessage( "Recovery on log [" + logFileName + "] completed." ); } else { msgLog.logMessage( "Recovery on log [" + logFileName + "] completed with " + xidIdentMap + " prepared transactions found." ); for ( LogEntry.Start startEntry : xidIdentMap.values() ) { msgLog.debug( "[" + logFileName + "] 2PC xid[" + startEntry.getXid() + "]" ); } } recoveredTxMap.clear(); } // for testing, do not use! void reset() { xidIdentMap.clear(); recoveredTxMap.clear(); } private LogEntry readEntry() throws IOException { long position = fileChannel.position(); LogEntry entry = LogIoUtils.readEntry( sharedBuffer, fileChannel, cf ); if ( entry instanceof LogEntry.Start ) { ((LogEntry.Start) entry).setStartPosition( position ); } return entry; } private final ArrayMap<Thread, Integer> txIdentMap = new ArrayMap<Thread, Integer>( (byte) 5, true, true ); void registerTxIdentifier( int identifier ) { txIdentMap.put( Thread.currentThread(), identifier ); } void unregisterTxIdentifier() { txIdentMap.remove( Thread.currentThread() ); } /** * If the current thread is committing a transaction the identifier of that * {@link XaTransaction} can be obtained invoking this method. * * @return the identifier of the transaction committing or <CODE>-1</CODE> * if current thread isn't committing any transaction */ public int getCurrentTxIdentifier() { Integer intValue = txIdentMap.get( Thread.currentThread() ); if ( intValue != null ) { return intValue; } return -1; } public ReadableByteChannel getLogicalLog( long version ) throws IOException { return getLogicalLog( version, 0 ); } public ReadableByteChannel getLogicalLog( long version, long position ) throws IOException { File name = getFileName( version ); if ( !fileSystem.fileExists( name ) ) { throw new NoSuchLogVersionException( version ); } StoreChannel channel = fileSystem.open( name, "r" ); channel.position( position ); return new BufferedFileChannel( channel, bufferMonitor ); } private void extractPreparedTransactionFromLog( int identifier, StoreChannel logChannel, LogBuffer targetBuffer ) throws IOException { LogEntry.Start startEntry = xidIdentMap.get( identifier ); logChannel.position( startEntry.getStartPosition() ); LogEntry entry; boolean found = false; long startedAt = sharedBuffer.position(); while ( (entry = LogIoUtils.readEntry( sharedBuffer, logChannel, cf )) != null ) { // TODO For now just skip Prepare entries if ( entry.getIdentifier() != identifier ) { continue; } if ( entry instanceof LogEntry.Prepare ) { break; } if ( entry instanceof LogEntry.Start || entry instanceof LogEntry.Command ) { LogIoUtils.writeLogEntry( entry, targetBuffer ); found = true; } else { throw new RuntimeException( "Expected start or command entry but found: " + entry ); } } // position now minus position before is how much we read from disk bufferMonitor.bytesRead( sharedBuffer.position() - startedAt ); if ( !found ) { throw new IOException( "Transaction for internal identifier[" + identifier + "] not found in current log" ); } } public synchronized ReadableByteChannel getPreparedTransaction( int identifier ) throws IOException { StoreChannel logChannel = (StoreChannel) getLogicalLogOrMyselfPrepared( logVersion, 0 ); InMemoryLogBuffer localBuffer = new InMemoryLogBuffer(); extractPreparedTransactionFromLog( identifier, logChannel, localBuffer ); logChannel.close(); return localBuffer; } public synchronized void getPreparedTransaction( int identifier, LogBuffer targetBuffer ) throws IOException { StoreChannel logChannel = (StoreChannel) getLogicalLogOrMyselfPrepared( logVersion, 0 ); extractPreparedTransactionFromLog( identifier, logChannel, targetBuffer ); logChannel.close(); } public LogExtractor getLogExtractor( long startTxId, long endTxIdHint ) throws IOException { return new LogExtractor( positionCache, this, cf, startTxId, endTxIdHint ); } public static final int MASTER_ID_REPRESENTING_NO_MASTER = -1; public synchronized Pair<Integer, Long> getMasterForCommittedTransaction( long txId ) throws IOException { if ( txId == 1 ) { return Pair.of( MASTER_ID_REPRESENTING_NO_MASTER, 0L ); } TxPosition cache = positionCache.getStartPosition( txId ); if ( cache != null ) { return Pair.of( cache.masterId, cache.checksum ); } LogExtractor extractor = getLogExtractor( txId, txId ); try { if ( extractor.extractNext( NullLogBuffer.INSTANCE ) != -1 ) { return Pair.of( extractor.getLastStartEntry().getMasterId(), extractor.getLastTxChecksum() ); } throw new NoSuchTransactionException( txId ); } finally { extractor.close(); } } /** * Return a file channel over the log file for {@code version} positioned * at {@code position}. If the log version is the current one all * committed transactions are guaranteed to be present but nothing that * hasn't been flushed yet. * * @param version The version of the log to get a channel over * @param position The position to which to set the channel * @return The channel * @throws IOException If an IO error occurs when reading the log file */ @Override public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position ) throws IOException { synchronized ( this ) { if ( version == logVersion ) { File currentLogName = getCurrentLogFileName(); StoreChannel channel = fileSystem.open( currentLogName, "r" ); channel.position( position ); return new BufferedFileChannel( channel, bufferMonitor ); } } if ( version < logVersion ) { return getLogicalLog( version, position ); } else { throw new RuntimeException( "Version[" + version + "] is higher then current log version[" + logVersion + "]" ); } } /** * Return a file channel over the log file for {@code version} positioned * at {@code position}. If the log version is the current one all * content is guaranteed to be present, including content just in the write * buffer. * <p/> * Non synchronized, though it accesses writeBuffer. Use this method only * through synchronized blocks or trouble will come your way. * * @param version The version of the log to get a channel over * @param position The position to which to set the channel * @return The channel * @throws IOException If an IO error occurs when reading the log file */ private ReadableByteChannel getLogicalLogOrMyselfPrepared( long version, long position ) throws IOException { if ( version < logVersion ) { return getLogicalLog( version, position ); } else if ( version == logVersion ) { File currentLogName = getCurrentLogFileName(); StoreChannel channel = fileSystem.open( currentLogName, "r" ); channel = new BufferedFileChannel( channel, bufferMonitor ); /* * this method is called **during** commit{One,Two}Phase - i.e. before the log buffer * is forced and in the case of 1PC without the writeOut() done in prepare (as in 2PC). * So, we need to writeOut(). The content of the buffer is written out to the file channel * so that the new channel returned above will see the new content. This logical log can * continue using the writeBuffer like nothing happened - the data is in the channel and * will eventually be forced. * * See SlaveTxIdGenerator#generate(). */ writeBuffer.writeOut(); channel.position( position ); return channel; } else { throw new RuntimeException( "Version[" + version + "] is higher then current log version[" + logVersion + "]" ); } } private File getCurrentLogFileName() { return currentLog == LOG1 ? logFiles.getLog1FileName() : logFiles.getLog2FileName(); } public long getLogicalLogLength( long version ) { return fileSystem.getFileSize( getFileName( version ) ); } public boolean hasLogicalLog( long version ) { return fileSystem.fileExists( getFileName( version ) ); } public boolean deleteLogicalLog( long version ) { File file = getFileName( version ); return fileSystem.fileExists( file ) ? fileSystem.deleteFile( file ) : false; } protected LogDeserializer getLogDeserializer( ReadableByteChannel byteChannel ) { return new LogDeserializer( byteChannel, logDeserializerMonitor ); } /** * @param logBasePath should be the log file base name, relative to the neo4j store directory. */ public LogBufferFactory createLogWriter(final Function<Config, File> logBasePath) { return new LogBufferFactory() { @Override public LogBuffer createActiveLogFile( Config config, long prevCommittedId ) throws IllegalStateException, IOException { File activeLogFile = new XaLogicalLogFiles( logBasePath.apply( config ), fileSystem ).getLog1FileName(); StoreChannel channel = fileSystem.create( activeLogFile ); ByteBuffer scratch = ByteBuffer.allocateDirect( 128 ); LogIoUtils.writeLogHeader( scratch, 0, prevCommittedId ); while(scratch.hasRemaining()) { channel.write( scratch ); } scratch.clear(); return new DirectLogBuffer( channel, scratch ); } }; } protected class LogDeserializer { private final ReadableByteChannel byteChannel; LogEntry.Start startEntry; LogEntry.Commit commitEntry; private final List<LogEntry> logEntries; protected LogDeserializer( ReadableByteChannel byteChannel, ByteCounterMonitor monitor ) { this.byteChannel = new MonitoredReadableByteChannel( byteChannel, monitor ); this.logEntries = new LinkedList<LogEntry>(); } public boolean readAndWriteAndApplyEntry( int newXidIdentifier ) throws IOException { LogEntry entry = LogIoUtils.readEntry( sharedBuffer, byteChannel, cf ); if ( entry == null ) { try { intercept( logEntries ); apply(); return false; } catch ( Throwable e ) { startEntry = null; commitEntry = null; kernelHealth.panic( e ); throw launderedException( IOException.class, "Failure applying transaction", e ); } } entry.setIdentifier( newXidIdentifier ); logEntries.add( entry ); if ( entry instanceof LogEntry.Commit ) { assert startEntry != null; commitEntry = (LogEntry.Commit) entry; } else if ( entry instanceof LogEntry.Start ) { startEntry = (LogEntry.Start) entry; } return true; } protected void intercept( List<LogEntry> logEntries ) { // default do nothing } protected void apply() throws IOException { for ( LogEntry entry : logEntries ) { /* * You are wondering what is going on here. Let me take you on a journey * A transaction, call it A starts, prepares locally, goes to the master and commits there * but doesn't quite make it back here, meaning its application is pending, with only the * start, command and possibly prepare entries but not the commit, the Xid in xidmap * Another transaction, B, does an operation that requires going to master and pull updates - does * that, gets all transactions not present locally (hence, A as well) and injects it. * The Start entry is the first one extracted - if we try to apply it it will throw a Start * entry already injected exception, since the Xid will match an ongoing transaction. If we * had written that to the log recovery would be impossible, constantly throwing the same * exception. So first apply, then write to log. * However we cannot do that for every entry - commit must always be written to log first, then * applied because a crash in the mean time could cause partially applied transactions. * The start entry does not have this problem because if it fails nothing will ever be applied - * the same goes for commands but we don't care about those. */ if ( entry instanceof Start ) { ((Start) entry).setStartPosition( writeBuffer.getFileChannelPosition() ); applyEntry( entry ); LogIoUtils.writeLogEntry( entry, writeBuffer ); } else { LogIoUtils.writeLogEntry( entry, writeBuffer ); if ( entry instanceof LogEntry.Commit ) { /* * Just writeOut(), don't force or performance will be impacted severely. */ writeBuffer.writeOut(); } applyEntry( entry ); } } } protected Start getStartEntry() { return startEntry; } protected Commit getCommitEntry() { return commitEntry; } } private long[] readLogHeader( ReadableByteChannel source, String message ) throws IOException { try { return LogIoUtils.readLogHeader( sharedBuffer, source, true ); } catch ( IllegalLogFormatException e ) { msgLog.logMessage( message, e ); throw e; } } public synchronized void applyTransactionWithoutTxId( ReadableByteChannel byteChannel, long nextTxId, ForceMode forceMode ) throws IOException { kernelHealth.assertHealthy( IOException.class ); int xidIdent = 0; LogEntry.Start startEntry = null; if ( nextTxId != (xaTf.getLastCommittedTx() + 1) ) { throw new IllegalStateException( "Tried to apply tx " + nextTxId + " but expected transaction " + (xaTf.getCurrentVersion() + 1) ); } logRecoveryMessage( "applyTxWithoutTxId log version: " + logVersion + ", committing tx=" + nextTxId + ") @ pos " + writeBuffer.getFileChannelPosition() ); scanIsComplete = false; LogDeserializer logApplier = getLogDeserializer( byteChannel ); xidIdent = getNextIdentifier(); long startEntryPosition = writeBuffer.getFileChannelPosition(); exhaust( logApplier, xidIdent ); byteChannel.close(); startEntry = logApplier.getStartEntry(); if ( startEntry == null ) { throw new IOException( "Unable to find start entry" ); } try { injectedTxValidator.assertInjectionAllowed( startEntry.getLastCommittedTxWhenTransactionStarted() ); } catch ( XAException e ) { throw new IOException( e ); } startEntry.setStartPosition( startEntryPosition ); LogEntry.OnePhaseCommit commit = new LogEntry.OnePhaseCommit( xidIdent, nextTxId, System.currentTimeMillis() ); LogIoUtils.writeLogEntry( commit, writeBuffer ); // need to manually force since xaRm.commit will not do it (transaction marked as recovered) forceMode.force( writeBuffer ); Xid xid = startEntry.getXid(); try { XaTransaction xaTx = xaRm.getXaTransaction( xid ); xaTx.setCommitTxId( nextTxId ); positionCache.cacheStartPosition( nextTxId, startEntry, logVersion ); xaRm.commit( xid, true ); LogEntry doneEntry = new LogEntry.Done( startEntry.getIdentifier() ); LogIoUtils.writeLogEntry( doneEntry, writeBuffer ); xidIdentMap.remove( startEntry.getIdentifier() ); recoveredTxMap.remove( startEntry.getIdentifier() ); } catch ( XAException e ) { throw new IOException( e ); } scanIsComplete = true; logRecoveryMessage( "Applied external tx and generated tx id=" + nextTxId ); checkLogRotation(); } private void exhaust( LogDeserializer logApplier, int xidIdent ) throws IOException { while ( logApplier.readAndWriteAndApplyEntry( xidIdent ) ) { // Just loop through } } public synchronized void applyTransaction( ReadableByteChannel byteChannel ) throws IOException { kernelHealth.assertHealthy( IOException.class ); scanIsComplete = false; LogDeserializer logApplier = getLogDeserializer( byteChannel ); int xidIdent = getNextIdentifier(); long startEntryPosition = writeBuffer.getFileChannelPosition(); boolean successfullyApplied = false; try { exhaust( logApplier, xidIdent ); successfullyApplied = true; } finally { if ( !successfullyApplied && logApplier.getStartEntry() != null && xidIdentMap.get( xidIdent ) != null ) { // Unmap this identifier if tx not applied correctly try { xaRm.forget( logApplier.getStartEntry().getXid() ); } catch ( XAException e ) { throw new IOException( e ); } finally { xidIdentMap.remove( xidIdent ); } } } byteChannel.close(); scanIsComplete = true; LogEntry.Start startEntry = logApplier.getStartEntry(); if ( startEntry == null ) { throw new IOException( "Unable to find start entry" ); } startEntry.setStartPosition( startEntryPosition ); positionCache.cacheStartPosition( logApplier.getCommitEntry().getTxId(), startEntry, logVersion ); checkLogRotation(); } /** * Rotates this logical log. The pending transactions are moved over to a * new log buffer and the internal structures updated to reflect the new * file offsets. Additional side effects include a force() of the store and increment of the log * version. * <p/> * Outline of how rotation happens: * <p/> * <li>The store is flushed - can't have pending changes if there is no log * that contains the commands</li> * <p/> * <li>Switch current filename with old and check that new doesn't exist and * the versioned backup isn't there also</li> * <p/> * <li>Force the current log buffer</li> * <p/> * <li>Create new log file, write header</li> * <p/> * <li>Find the position for the first pending transaction. From there start * scanning, transferring the entries of the pending transactions from the * old log to the new, updating the start positions in the in-memory tables</li> * <p/> * <li>Keep or delete old log</li> * <p/> * <li>Update the log version stored</li> * <p/> * <li>Instantiate the new log buffer</li> * * @return the last tx in the produced log * @throws IOException I/O error. */ public synchronized long rotate() throws IOException { xaTf.flushAll(); File newLogFile = logFiles.getLog2FileName(); File currentLogFile = logFiles.getLog1FileName(); char newActiveLog = LOG2; long currentVersion = xaTf.getCurrentVersion(); File oldCopy = getFileName( currentVersion ); if ( currentLog == CLEAN || currentLog == LOG2 ) { newActiveLog = LOG1; newLogFile = logFiles.getLog1FileName(); currentLogFile = logFiles.getLog2FileName(); } else { assert currentLog == LOG1; } assertFileDoesntExist( newLogFile, "New log file" ); assertFileDoesntExist( oldCopy, "Copy log file" ); long endPosition = writeBuffer.getFileChannelPosition(); msgLog.logMessage( "Rotating [" + currentLogFile + "] @ version=" + currentVersion + " to " + newLogFile + " from position " + endPosition, true ); writeBuffer.force(); StoreChannel newLog = fileSystem.open( newLogFile, "rw" ); long lastTx = xaTf.getLastCommittedTx(); LogIoUtils.writeLogHeader( sharedBuffer, currentVersion+1, lastTx ); previousLogLastCommittedTx = lastTx; if ( newLog.write( sharedBuffer ) != 16 ) { throw new IOException( "Unable to write log version to new" ); } fileChannel.position( 0 ); readAndAssertLogHeader( sharedBuffer, fileChannel, currentVersion ); fileChannel.position( endPosition ); if ( xidIdentMap.size() > 0 ) { long firstEntryPosition = getFirstStartEntry( endPosition ); fileChannel.position( firstEntryPosition ); msgLog.logMessage( "Rotate log first start entry @ pos=" + firstEntryPosition + " out of " + xidIdentMap ); } LogBuffer newLogBuffer = instantiateCorrectWriteBuffer( newLog ); partialTransactionCopier.copy(/*from = */fileChannel, /* to= */newLogBuffer, /* targetLogVersion= */logVersion+1); newLogBuffer.force(); newLog.position( newLogBuffer.getFileChannelPosition() ); msgLog.logMessage( "Rotate: old log scanned, newLog @ pos=" + newLog.position(), true ); newLog.force( false ); releaseCurrentLogFile(); setActiveLog( newActiveLog ); renameLogFileToRightVersion( currentLogFile, endPosition ); xaTf.getAndSetNewVersion(); this.logVersion = xaTf.getCurrentVersion(); if ( xaTf.getCurrentVersion() != (currentVersion + 1) ) { throw new IOException( "Version change failed, expected " + (currentVersion + 1) + ", but was " + xaTf.getCurrentVersion() ); } pruneStrategy.prune( this ); fileChannel = newLog; positionCache.putHeader( logVersion, lastTx ); instantiateCorrectWriteBuffer(); msgLog.logMessage( "Log rotated, newLog @ pos=" + writeBuffer.getFileChannelPosition() + ", version " + logVersion + " and last tx " + previousLogLastCommittedTx, true ); return lastTx; } private void assertFileDoesntExist( File file, String description ) throws IOException { if ( fileSystem.fileExists( file ) ) { throw new IOException( description + ": " + file + " already exist" ); } } /** * Gets the file position of the first of the start entries searching * from {@code endPosition} and to smallest positions. * * @param endPosition The largest possible position for the Start entries * @return The smallest possible position for the Start entries, at most * {@code endPosition} */ private long getFirstStartEntry( long endPosition ) { long firstEntryPosition = endPosition; for ( LogEntry.Start entry : xidIdentMap.values() ) { if ( entry.getStartPosition() > 0 && entry.getStartPosition() < firstEntryPosition ) { firstEntryPosition = entry.getStartPosition(); } } return firstEntryPosition; } private void setActiveLog( char c ) throws IOException { if ( c != CLEAN && c != LOG1 && c != LOG2 ) { throw new IllegalArgumentException( "Log must be either clean, " + "1 or 2" ); } if ( c == currentLog ) { throw new IllegalStateException( "Log should not be equal to " + "current " + currentLog ); } ByteBuffer bb = ByteBuffer.wrap( new byte[4] ); bb.asCharBuffer().put( c ).flip(); StoreChannel fc = fileSystem.open( new File( fileName.getPath() + ".active"), "rw" ); int wrote = fc.write( bb ); if ( wrote != 4 ) { throw new IllegalStateException( "Expected to write 4 -> " + wrote ); } fc.force( false ); fc.close(); currentLog = c; } @Deprecated public void setAutoRotateLogs( boolean autoRotate ) { this.autoRotate = autoRotate; } @Deprecated public boolean isLogsAutoRotated() { return this.autoRotate; } @Deprecated public void setLogicalLogTargetSize( long size ) { this.rotateAtSize = size; } @Deprecated public long getLogicalLogTargetSize() { return this.rotateAtSize; } @Override public File getFileName( long version ) { return getHistoryFileName( fileName, version ); } public File getBaseFileName() { return fileName; } public Pattern getHistoryFileNamePattern() { return getHistoryFileNamePattern( fileName.getName() ); } public static Pattern getHistoryFileNamePattern( String baseFileName ) { return Pattern.compile( baseFileName + "\\.v\\d+" ); } public static File getHistoryFileName( File baseFile, long version ) { return new File( baseFile.getPath() + ".v" + version ); } public static long getHistoryLogVersion( File historyLogFile ) { // Get version based on the name String name = historyLogFile.getName(); String toFind = ".v"; int index = name.lastIndexOf( toFind ); if ( index == -1 ) { throw new RuntimeException( "Invalid log file '" + historyLogFile + "'" ); } return Integer.parseInt( name.substring( index + toFind.length() ) ); } public static long getHighestHistoryLogVersion( FileSystemAbstraction fileSystem, File storeDir, String baseFileName ) { Pattern logFilePattern = getHistoryFileNamePattern( baseFileName ); long highest = -1; for ( File file : fileSystem.listFiles( storeDir ) ) { if ( logFilePattern.matcher( file.getName() ).matches() ) { highest = max( highest, getHistoryLogVersion( file ) ); } } return highest; } public boolean wasNonClean() { return nonCleanShutdown; } @Override public long getHighestLogVersion() { return logVersion; } @Override public Long getFirstCommittedTxId( long version ) { if ( version == 0 ) { return 1L; } // First committed tx for version V = last committed tx version V-1 + 1 Long header = positionCache.getHeader( version - 1 ); if ( header != null ) // It existed in cache { return header + 1; } // Wasn't cached, go look for it synchronized ( this ) { if ( version > logVersion ) { throw new IllegalArgumentException( "Too high version " + version + ", active is " + logVersion ); } else if ( version == logVersion ) { throw new IllegalArgumentException( "Last committed tx for the active log isn't determined yet" ); } else if ( version == logVersion - 1 ) { return previousLogLastCommittedTx; } else { File file = getFileName( version ); if ( fileSystem.fileExists( file ) ) { try { long[] headerLongs = LogIoUtils.readLogHeader( fileSystem, file ); return headerLongs[1] + 1; } catch ( IOException e ) { throw new RuntimeException( e ); } } } } return null; } @Override public long getLastCommittedTxId() { return xaTf.getLastCommittedTx(); } @Override public Long getFirstStartRecordTimestamp( long version ) throws IOException { ReadableByteChannel log = null; try { ByteBuffer buffer = LogExtractor.newLogReaderBuffer(); log = getLogicalLog( version ); LogIoUtils.readLogHeader( buffer, log, true ); LogEntry entry = null; while ( (entry = LogIoUtils.readEntry( buffer, log, cf )) != null ) { if ( entry instanceof LogEntry.Start ) { return ((LogEntry.Start) entry).getTimeWritten(); } } return -1L; } finally { if ( log != null ) { log.close(); } } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaLogicalLog.java
657
public class XaFactory { private Config config; private final TxIdGenerator txIdGenerator; private final AbstractTransactionManager txManager; private final FileSystemAbstraction fileSystemAbstraction; private final Monitors monitors; private final Logging logging; private final RecoveryVerifier recoveryVerifier; private final LogPruneStrategy pruneStrategy; private final KernelHealth kernelHealth; public XaFactory( Config config, TxIdGenerator txIdGenerator, AbstractTransactionManager txManager, FileSystemAbstraction fileSystemAbstraction, Monitors monitors, Logging logging, RecoveryVerifier recoveryVerifier, LogPruneStrategy pruneStrategy, KernelHealth kernelHealth ) { this.config = config; this.txIdGenerator = txIdGenerator; this.txManager = txManager; this.fileSystemAbstraction = fileSystemAbstraction; this.monitors = monitors; this.logging = logging; this.recoveryVerifier = recoveryVerifier; this.pruneStrategy = pruneStrategy; this.kernelHealth = kernelHealth; } public XaContainer newXaContainer( XaDataSource xaDataSource, File logicalLog, XaCommandFactory cf, InjectedTransactionValidator injectedTxValidator, XaTransactionFactory tf, TransactionStateFactory stateFactory, TransactionInterceptorProviders providers, boolean readOnly ) { if ( logicalLog == null || cf == null || tf == null ) { throw new IllegalArgumentException( "Null parameter, " + "LogicalLog[" + logicalLog + "] CommandFactory[" + cf + "TransactionFactory[" + tf + "]" ); } // TODO The dependencies between XaRM, LogicalLog and XaTF should be resolved to avoid the setter XaResourceManager rm = new XaResourceManager( xaDataSource, tf, txIdGenerator, txManager, recoveryVerifier, logicalLog.getName(), monitors ); long rotateAtSize = config.get( logical_log_rotation_threshold ); XaLogicalLog log; if( readOnly) { log = new NoOpLogicalLog( logging ); } else if ( providers.shouldInterceptDeserialized() && providers.hasAnyInterceptorConfigured() ) { log = new InterceptingXaLogicalLog( logicalLog, rm, cf, tf, providers, monitors, fileSystemAbstraction, logging, pruneStrategy, stateFactory, kernelHealth, rotateAtSize, injectedTxValidator ); } else { log = new XaLogicalLog( logicalLog, rm, cf, tf, fileSystemAbstraction, monitors, logging, pruneStrategy, stateFactory, kernelHealth, rotateAtSize, injectedTxValidator ); } // TODO These setters should be removed somehow rm.setLogicalLog( log ); tf.setLogicalLog( log ); return new XaContainer(rm, log); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaFactory.java
658
private static class XidStatus { private boolean active = true; private final TransactionStatus txStatus; XidStatus( XaTransaction xaTransaction ) { txStatus = new TransactionStatus( xaTransaction ); } void setActive( boolean active ) { this.active = active; } boolean getActive() { return this.active; } TransactionStatus getTransactionStatus() { return txStatus; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaResourceManager.java
659
public abstract class XaTransaction { /** * Returns <CODE>true</CODE> if read only transaction, that is no * modifications will be made once the transaction commits. * * @return true if read only transaction */ public abstract boolean isReadOnly(); /** * When a command is added to transaction it will be passed via this method. * The <CODE>XaTransaction</CODE> needs to hold all the commands in memory * until it receives the <CODE>doCommit</CODE> or <CODE>doRollback</CODE> * call. * * @param command * The command to be added to transaction */ protected abstract void doAddCommand( XaCommand command ); /** * Rollbacks the transaction, loop through all commands and invoke <CODE>rollback()</CODE>. * * @throws XAException * If unable to rollback */ protected abstract void doRollback() throws XAException; /** * Called when transaction is beeing prepared. * * @throws XAException * If unable to prepare */ protected abstract void doPrepare() throws XAException; /** * Commits the transaction, loop through all commands and invoke * <CODE>execute()</CODE>. * * @throws XAException * If unable to commit */ protected abstract void doCommit() throws XAException; private int identifier = -1; private final XaLogicalLog log; private final TransactionState state; private boolean isRecovered = false; private boolean committed = false; private boolean rolledback = false; private boolean prepared = false; private long commitTxId = -1; public XaTransaction( XaLogicalLog log, TransactionState state ) { if ( log == null ) { throw new IllegalArgumentException( "LogicalLog is null" ); } this.log = log; this.state = state; } /** * If this transaction is created during a recovery scan of the logical log * method will be called to mark the transaction "recovered". */ protected void setRecovered() { isRecovered = true; } /** * Returns <CODE>true</CODE> if this is a "recovered transaction". * * @return <CODE>true</CODE> if transaction was created during a recovery * else <CODE>false</CODE> is returned */ public boolean isRecovered() { return isRecovered; } public final void setIdentifier( int identifier ) { assert this.identifier == -1; this.identifier = identifier; } /** * Returns the "internal" identifier for this transaction. See * {@link XaLogicalLog#getCurrentTxIdentifier}. * * @return The transaction identifier */ public final int getIdentifier() { assert identifier != -1; return identifier; } /** * Adds the command to transaction. First writes the command to the logical * log then calls {@link #doAddCommand}. Also check * {@link XaConnectionHelpImpl} class documentation example. * * @param command * The command to add to transaction * @throws RuntimeException * If problem writing command to logical log or this transaction * is committed or rolled back */ public final void addCommand( XaCommand command ) { if ( committed ) { throw new TransactionFailureException( "Cannot add command to committed transaction" ); } if ( rolledback ) { throw new TransactionFailureException( "Cannot add command to rolled back transaction" ); } doAddCommand( command ); try { log.writeCommand( command, getIdentifier() ); } catch ( IOException e ) { throw new TransactionFailureException( "Unable to write command to logical log.", e ); } } /** * Used during recovery, calls {@link #doAddCommand}. Injects the command * into the transaction without writing to the logical log. * * @param command * The command that will be injected */ protected void injectCommand( XaCommand command ) { doAddCommand( command ); } /** * Rollbacks the transaction, calls {@link #doRollback}. * * @throws XAException * If unable to rollback */ public final void rollback() throws XAException { if ( committed ) { throw new XAException( "Cannot rollback partialy commited transaction. Recover and " + "commit" ); } rolledback = true; doRollback(); } /** * Called before prepare marker is written to logical log. Calls * {@link #doPrepare()}. * * @throws XAException * if unable to prepare */ public final void prepare() throws XAException { if ( committed ) { throw new XAException( "Cannot prepare comitted transaction" ); } if ( rolledback ) { throw new XAException( "Cannot prepare rolled back transaction" ); } prepared = true; doPrepare(); } /** * First registers the transaction identifier (see * {@link XaLogicalLog#getCurrentTxIdentifier} then calls {@link #doCommit}. * * @throws XAException * If unable to commit */ public final void commit() throws XAException { if ( !prepared && !isRecovered() ) { throw new XAException( "Cannot commit unprepared transaction" ); } log.registerTxIdentifier( getIdentifier() ); try { committed = true; doCommit(); } finally { log.unregisterTxIdentifier(); } } public synchronized long getCommitTxId() { return commitTxId; } public synchronized void setCommitTxId( long commitTxId ) { this.commitTxId = commitTxId; } public final TxIdGenerator getTxIdGenerator() { return state.getTxIdGenerator(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaTransaction.java
660
public abstract class XaTransactionFactory { private XaLogicalLog log; /** * Create a {@link XaTransaction} with <CODE>identifier</CODE> as internal * transaction id. * * @param identifier the identifier of the transaction * @param state the transaction state for this transaction. * @return A new xa transaction */ public abstract XaTransaction create( long lastCommittedTxWhenTransactionStarted, TransactionState state ); public abstract void flushAll(); public void setLogicalLog( XaLogicalLog log ) { this.log = log; } protected XaLogicalLog getLogicalLog() { return log; } /** * This method will be called when all recovered transactions have been * resolved to a safe state (rolledback or committed). This implementation * does nothing so override if you need to do something when recovery is * complete. */ public void recoveryComplete() { } public abstract long getCurrentVersion(); public abstract long getAndSetNewVersion(); public abstract void setVersion( long version ); public abstract long getLastCommittedTx(); }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaTransactionFactory.java
661
{ public boolean isReturnableNode( TraversalPosition position ) { Relationship last = position.lastRelationshipTraversed(); if ( last != null && last.isType( type ) ) { return true; } return false; } }, type, Direction.OUTGOING
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_CircularGraphTest.java
662
public class DepthPitfallGraphTest extends TraversalTestBase { /* Layout: * _(2)--__ * / \ * (1)-(3)-_ (6) * |\_ \ / * | (4)__ \/ * \_______(5) */ private static final String[] THE_WORLD_AS_WE_KNOW_IT = new String[] { "1 TO 2", "1 TO 3", "1 TO 4", "5 TO 3", "1 TO 5", "4 TO 5", "2 TO 6", "5 TO 6" }; private static final String[] NODE_UNIQUE_PATHS = new String[] { "1", "1,2", "1,2,6", "1,2,6,5", "1,2,6,5,3", "1,2,6,5,4", "1,3", "1,3,5", "1,3,5,4", "1,3,5,6", "1,3,5,6,2", "1,4", "1,4,5", "1,4,5,3", "1,4,5,6", "1,4,5,6,2", "1,5", "1,5,3", "1,5,4", "1,5,6", "1,5,6,2" }; private static final String[] RELATIONSHIP_UNIQUE_EXTRA_PATHS = new String[] { "1,2,6,5,1", "1,2,6,5,1,3", "1,2,6,5,1,3,5", "1,2,6,5,1,3,5,4", "1,2,6,5,1,3,5,4,1", "1,2,6,5,1,4", "1,2,6,5,1,4,5", "1,2,6,5,1,4,5,3", "1,2,6,5,1,4,5,3,1", "1,2,6,5,3,1", "1,2,6,5,3,1,4", "1,2,6,5,3,1,4,5", "1,2,6,5,3,1,4,5,1", "1,2,6,5,3,1,5", "1,2,6,5,3,1,5,4", "1,2,6,5,3,1,5,4,1", "1,2,6,5,4,1", "1,2,6,5,4,1,3", "1,2,6,5,4,1,3,5", "1,2,6,5,4,1,3,5,1", "1,2,6,5,4,1,5", "1,2,6,5,4,1,5,3", "1,2,6,5,4,1,5,3,1", "1,3,5,1", "1,3,5,1,2", "1,3,5,1,2,6", "1,3,5,1,2,6,5", "1,3,5,1,2,6,5,4", "1,3,5,1,2,6,5,4,1", "1,3,5,1,4", "1,3,5,1,4,5", "1,3,5,1,4,5,6", "1,3,5,1,4,5,6,2", "1,3,5,1,4,5,6,2,1", "1,3,5,4,1", "1,3,5,4,1,2", "1,3,5,4,1,2,6", "1,3,5,4,1,2,6,5", "1,3,5,4,1,2,6,5,1", "1,3,5,4,1,5", "1,3,5,4,1,5,6", "1,3,5,4,1,5,6,2", "1,3,5,4,1,5,6,2,1", "1,3,5,6,2,1", "1,3,5,6,2,1,4", "1,3,5,6,2,1,4,5", "1,3,5,6,2,1,4,5,1", "1,3,5,6,2,1,5", "1,3,5,6,2,1,5,4", "1,3,5,6,2,1,5,4,1", "1,4,5,1", "1,4,5,1,2", "1,4,5,1,2,6", "1,4,5,1,2,6,5", "1,4,5,1,2,6,5,3", "1,4,5,1,2,6,5,3,1", "1,4,5,1,3", "1,4,5,1,3,5", "1,4,5,1,3,5,6", "1,4,5,1,3,5,6,2", "1,4,5,1,3,5,6,2,1", "1,4,5,3,1", "1,4,5,3,1,2", "1,4,5,3,1,2,6", "1,4,5,3,1,2,6,5", "1,4,5,3,1,2,6,5,1", "1,4,5,3,1,5", "1,4,5,3,1,5,6", "1,4,5,3,1,5,6,2", "1,4,5,3,1,5,6,2,1", "1,4,5,6,2,1", "1,4,5,6,2,1,3", "1,4,5,6,2,1,3,5", "1,4,5,6,2,1,3,5,1", "1,4,5,6,2,1,5", "1,4,5,6,2,1,5,3", "1,4,5,6,2,1,5,3,1", "1,5,3,1", "1,5,3,1,2", "1,5,3,1,2,6", "1,5,3,1,2,6,5", "1,5,3,1,2,6,5,4", "1,5,3,1,2,6,5,4,1", "1,5,3,1,4", "1,5,3,1,4,5", "1,5,3,1,4,5,6", "1,5,3,1,4,5,6,2", "1,5,3,1,4,5,6,2,1", "1,5,4,1", "1,5,4,1,2", "1,5,4,1,2,6", "1,5,4,1,2,6,5", "1,5,4,1,2,6,5,3", "1,5,4,1,2,6,5,3,1", "1,5,4,1,3", "1,5,4,1,3,5", "1,5,4,1,3,5,6", "1,5,4,1,3,5,6,2", "1,5,4,1,3,5,6,2,1", "1,5,6,2,1", "1,5,6,2,1,3", "1,5,6,2,1,3,5", "1,5,6,2,1,3,5,4", "1,5,6,2,1,3,5,4,1", "1,5,6,2,1,4", "1,5,6,2,1,4,5", "1,5,6,2,1,4,5,3", "1,5,6,2,1,4,5,3,1" }; @Before public void setup() { createGraph( THE_WORLD_AS_WE_KNOW_IT ); } @Test public void testSmallestPossibleInit() throws Exception { Traverser traversal = traversal().traverse( node( "1" ) ); int count = 0; Transaction transaction = beginTx(); try { for ( Path position : traversal ) { count++; assertNotNull( position ); assertNotNull( position.endNode() ); if ( position.length() > 0 ) { assertNotNull( position.lastRelationship() ); } assertNotNull( position.length() ); } assertFalse( "empty traversal", count == 0 ); } finally { transaction.finish(); } } @Test public void testAllNodesAreReturnedOnceDepthFirst() throws Exception { testAllNodesAreReturnedOnce( traversal().depthFirst() ); } @Test public void testAllNodesAreReturnedOnceBreadthFirst() throws Exception { testAllNodesAreReturnedOnce( traversal().breadthFirst() ); } private void testAllNodesAreReturnedOnce( TraversalDescription traversal ) { Traverser traverser = traversal.uniqueness( Uniqueness.NODE_GLOBAL ).traverse( node( "1" ) ); expectNodes( traverser, "1", "2", "3", "4", "5", "6" ); } @Test public void testNodesAreReturnedOnceWhenSufficientRecentlyUniqueDepthFirst() throws Exception { testNodesAreReturnedOnceWhenSufficientRecentlyUnique( traversal().depthFirst() ); } @Test public void testNodesAreReturnedOnceWhenSufficientRecentlyUniqueBreadthFirst() throws Exception { testNodesAreReturnedOnceWhenSufficientRecentlyUnique( traversal().breadthFirst() ); } private void testNodesAreReturnedOnceWhenSufficientRecentlyUnique( TraversalDescription description ) { Traverser traverser = description.uniqueness( Uniqueness.NODE_RECENT, 6 ).traverse( node( "1" ) ); expectNodes( traverser, "1", "2", "3", "4", "5", "6" ); } @Test public void testAllRelationshipsAreReturnedOnceDepthFirst() throws Exception { testAllRelationshipsAreReturnedOnce( traversal().depthFirst() ); } @Test public void testAllRelationshipsAreReturnedOnceBreadthFirst() throws Exception { testAllRelationshipsAreReturnedOnce( traversal().breadthFirst() ); } private void testAllRelationshipsAreReturnedOnce( TraversalDescription description ) throws Exception { Traverser traverser = traversal().uniqueness( Uniqueness.RELATIONSHIP_GLOBAL ).traverse( node( "1" ) ); expectRelationships( traverser, THE_WORLD_AS_WE_KNOW_IT ); } @Test public void testRelationshipsAreReturnedOnceWhenSufficientRecentlyUniqueDepthFirst() throws Exception { testRelationshipsAreReturnedOnceWhenSufficientRecentlyUnique( traversal().depthFirst() ); } @Test public void testRelationshipsAreReturnedOnceWhenSufficientRecentlyUniqueBreadthFirst() throws Exception { testRelationshipsAreReturnedOnceWhenSufficientRecentlyUnique( traversal().breadthFirst() ); } private void testRelationshipsAreReturnedOnceWhenSufficientRecentlyUnique( TraversalDescription description ) throws Exception { Traverser traverser = description.uniqueness( Uniqueness.RELATIONSHIP_RECENT, THE_WORLD_AS_WE_KNOW_IT.length ).traverse( node( "1" ) ); expectRelationships( traverser, THE_WORLD_AS_WE_KNOW_IT ); } @Test public void testAllUniqueNodePathsAreReturnedDepthFirst() throws Exception { testAllUniqueNodePathsAreReturned( traversal().depthFirst() ); } @Test public void testAllUniqueNodePathsAreReturnedBreadthFirst() throws Exception { testAllUniqueNodePathsAreReturned( traversal().breadthFirst() ); } private void testAllUniqueNodePathsAreReturned( TraversalDescription description ) throws Exception { Traverser traverser = description.uniqueness( Uniqueness.NODE_PATH ).traverse( node( "1" ) ); expectPaths( traverser, NODE_UNIQUE_PATHS ); } @Test public void testAllUniqueRelationshipPathsAreReturnedDepthFirst() throws Exception { testAllUniqueRelationshipPathsAreReturned( traversal().depthFirst() ); } @Test public void testAllUniqueRelationshipPathsAreReturnedBreadthFirst() throws Exception { testAllUniqueRelationshipPathsAreReturned( traversal().breadthFirst() ); } private void testAllUniqueRelationshipPathsAreReturned( TraversalDescription description ) throws Exception { Set<String> expected = new HashSet<String>( Arrays.asList( NODE_UNIQUE_PATHS ) ); expected.addAll( Arrays.asList( RELATIONSHIP_UNIQUE_EXTRA_PATHS ) ); Traverser traverser = description.uniqueness( Uniqueness.RELATIONSHIP_PATH ).traverse( node( "1" ) ); expectPaths( traverser, expected ); } @Test public void canPruneTraversalAtSpecificDepthDepthFirst() { canPruneTraversalAtSpecificDepth( traversal().depthFirst() ); } @Test public void canPruneTraversalAtSpecificDepthBreadthFirst() { canPruneTraversalAtSpecificDepth( traversal().breadthFirst() ); } private void canPruneTraversalAtSpecificDepth( TraversalDescription description ) { Traverser traverser = description.uniqueness( Uniqueness.NONE ).evaluator( toDepth( 1 ) ).traverse( node( "1" ) ); expectNodes( traverser, "1", "2", "3", "4", "5" ); } @Test public void canPreFilterNodesDepthFirst() { canPreFilterNodes( traversal().depthFirst() ); } @Test public void canPreFilterNodesBreadthFirst() { canPreFilterNodes( traversal().breadthFirst() ); } private void canPreFilterNodes( TraversalDescription description ) { Traverser traverser = description.uniqueness( Uniqueness.NONE ).evaluator( atDepth( 2 ) ).traverse( node( "1" ) ); expectPaths( traverser, "1,2,6", "1,3,5", "1,4,5", "1,5,3", "1,5,4", "1,5,6" ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_DepthPitfallGraphTest.java
663
public class DepthOneTraversalTest extends TraversalTestBase { private Transaction tx; @Before public void createTheGraph() { createGraph( "0 ROOT 1", "1 KNOWS 2", "2 KNOWS 3", "2 KNOWS 4", "4 KNOWS 5", "5 KNOWS 6", "3 KNOWS 1" ); tx = beginTx(); } @After public void tearDown() { tx.finish(); } private void shouldGetBothNodesOnDepthOne( TraversalDescription description ) { description = description.evaluator( atDepth( 1 ) ); expectNodes( description.traverse( getNodeWithName( "3" ) ), "1", "2" ); } @Test public void shouldGetBothNodesOnDepthOneForDepthFirst() { shouldGetBothNodesOnDepthOne( traversal().depthFirst() ); } @Test public void shouldGetBothNodesOnDepthOneForBreadthFirst() { shouldGetBothNodesOnDepthOne( traversal().breadthFirst() ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_DepthOneTraversalTest.java
664
{ @Override public void close() { iterator.close(); } @Override protected T fetchNextOrNull() { return iterator.hasNext() ? convert( iterator.next() ) : null; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_DefaultTraverser.java
665
private static abstract class ResourcePathIterableWrapper<T> implements ResourceIterable<T> { private final ResourceIterable<Path> iterableToWrap; protected ResourcePathIterableWrapper( ResourceIterable<Path> iterableToWrap ) { this.iterableToWrap = iterableToWrap; } protected ResourceIterator<Path> pathIterator() { return iterableToWrap.iterator(); } @Override public ResourceIterator<T> iterator() { final ResourceIterator<Path> iterator = pathIterator(); return new PrefetchingResourceIterator<T>() { @Override public void close() { iterator.close(); } @Override protected T fetchNextOrNull() { return iterator.hasNext() ? convert( iterator.next() ) : null; } }; } protected abstract T convert( Path path ); }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_DefaultTraverser.java
666
{ @Override public void close() { pathIterator.close(); } @Override protected Relationship fetchNextOrNull() { while ( pathIterator.hasNext() ) { Path path = pathIterator.next(); if ( path.length() > 0 ) { return path.lastRelationship(); } } return null; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_DefaultTraverser.java
667
{ @Override public ResourceIterator<Relationship> iterator() { final ResourceIterator<Path> pathIterator = pathIterator(); return new PrefetchingResourceIterator<Relationship>() { @Override public void close() { pathIterator.close(); } @Override protected Relationship fetchNextOrNull() { while ( pathIterator.hasNext() ) { Path path = pathIterator.next(); if ( path.length() > 0 ) { return path.lastRelationship(); } } return null; } }; } @Override protected Relationship convert( Path path ) { return path.lastRelationship(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_DefaultTraverser.java
668
{ @Override protected Node convert( Path path ) { return path.endNode(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_DefaultTraverser.java
669
public class DefaultTraverser implements Traverser { private final Factory<TraverserIterator> traverserIteratorFactory; private TraversalMetadata lastIterator; DefaultTraverser(Factory<TraverserIterator> traverserIteratorFactory ) { this.traverserIteratorFactory = traverserIteratorFactory; } @Override public ResourceIterable<Node> nodes() { return new ResourcePathIterableWrapper<Node>( this ) { @Override protected Node convert( Path path ) { return path.endNode(); } }; } @Override public ResourceIterable<Relationship> relationships() { return new ResourcePathIterableWrapper<Relationship>( this ) { @Override public ResourceIterator<Relationship> iterator() { final ResourceIterator<Path> pathIterator = pathIterator(); return new PrefetchingResourceIterator<Relationship>() { @Override public void close() { pathIterator.close(); } @Override protected Relationship fetchNextOrNull() { while ( pathIterator.hasNext() ) { Path path = pathIterator.next(); if ( path.length() > 0 ) { return path.lastRelationship(); } } return null; } }; } @Override protected Relationship convert( Path path ) { return path.lastRelationship(); } }; } @Override public ResourceIterator<Path> iterator() { TraverserIterator traverserIterator = traverserIteratorFactory.newInstance(); lastIterator = traverserIterator; return traverserIterator; } @Override public TraversalMetadata metadata() { return lastIterator; } private static abstract class ResourcePathIterableWrapper<T> implements ResourceIterable<T> { private final ResourceIterable<Path> iterableToWrap; protected ResourcePathIterableWrapper( ResourceIterable<Path> iterableToWrap ) { this.iterableToWrap = iterableToWrap; } protected ResourceIterator<Path> pathIterator() { return iterableToWrap.iterator(); } @Override public ResourceIterator<T> iterator() { final ResourceIterator<Path> iterator = pathIterator(); return new PrefetchingResourceIterator<T>() { @Override public void close() { iterator.close(); } @Override protected T fetchNextOrNull() { return iterator.hasNext() ? convert( iterator.next() ) : null; } }; } protected abstract T convert( Path path ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_DefaultTraverser.java
670
{ public boolean isStopNode( TraversalPosition position ) { Relationship last = position.lastRelationshipTraversed(); if ( last != null && last.isType( type ) ) { Node node = position.currentNode(); long currentTime = (Long) node.getProperty( "timestamp" ); return currentTime >= timestamp; } return false; } }, new ReturnableEvaluator()
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_CircularGraphTest.java
671
abstract class AbstractTraverserIterator extends PrefetchingResourceIterator<Path> implements TraverserIterator { protected int numberOfPathsReturned; protected int numberOfRelationshipsTraversed; private final Resource resource; protected AbstractTraverserIterator( Resource resource ) { this.resource = resource; } @Override public int getNumberOfPathsReturned() { return numberOfPathsReturned; } @Override public int getNumberOfRelationshipsTraversed() { return numberOfRelationshipsTraversed; } @Override public void relationshipTraversed() { numberOfRelationshipsTraversed++; } @Override public void unnecessaryRelationshipTraversed() { numberOfRelationshipsTraversed++; } @Override public void close() { resource.close(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_AbstractTraverserIterator.java
672
public class CircularGraphTest extends TraversalTestBase { @Before public void createTheGraph() { createGraph( "1 TO 2", "2 TO 3", "3 TO 1" ); } @Test public void testCircularBug() { final long timestamp = 3; Transaction tx = beginTx(); try { getNodeWithName( "2" ).setProperty( "timestamp", 1L ); getNodeWithName( "3" ).setProperty( "timestamp", 2L ); tx.success(); } finally { tx.finish(); } Transaction tx2 = beginTx(); try { final RelationshipType type = DynamicRelationshipType.withName( "TO" ); Traverser t = node( "1" ).traverse( Order.DEPTH_FIRST, new StopEvaluator() { public boolean isStopNode( TraversalPosition position ) { Relationship last = position.lastRelationshipTraversed(); if ( last != null && last.isType( type ) ) { Node node = position.currentNode(); long currentTime = (Long) node.getProperty( "timestamp" ); return currentTime >= timestamp; } return false; } }, new ReturnableEvaluator() { public boolean isReturnableNode( TraversalPosition position ) { Relationship last = position.lastRelationshipTraversed(); if ( last != null && last.isType( type ) ) { return true; } return false; } }, type, Direction.OUTGOING ); Iterator<Node> nodes = t.iterator(); assertEquals( "2", nodes.next().getProperty( "name" ) ); assertEquals( "3", nodes.next().getProperty( "name" ) ); assertFalse( nodes.hasNext() ); } finally { tx2.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_CircularGraphTest.java
673
private static class Side { private final MonoDirectionalTraversalDescription description; public Side( MonoDirectionalTraversalDescription description ) { this.description = description; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_BidirectionalTraverserIterator.java
674
{ @Override public TraversalBranch next( TraversalContext metadata ) { throw new UnsupportedOperationException(); } @Override public Direction currentSide() { return Direction.OUTGOING; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_BidirectionalTraverserIterator.java
675
{ @Override public boolean accept( Path path ) { return uniqueness.checkFull( path ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_BidirectionalTraverserIterator.java
676
class BidirectionalTraverserIterator extends AbstractTraverserIterator { private final BranchCollisionDetector collisionDetector; private Iterator<Path> foundPaths; private SideSelector selector; private final Map<Direction, Side> sides = new EnumMap<>( Direction.class ); private final BidirectionalUniquenessFilter uniqueness; private final Predicate<Path> uniquenessPredicate = new Predicate<Path>() { @Override public boolean accept( Path path ) { return uniqueness.checkFull( path ); } }; private static class Side { private final MonoDirectionalTraversalDescription description; public Side( MonoDirectionalTraversalDescription description ) { this.description = description; } } BidirectionalTraverserIterator( Resource resource, MonoDirectionalTraversalDescription start, MonoDirectionalTraversalDescription end, SideSelectorPolicy sideSelector, org.neo4j.graphdb.traversal.BranchCollisionPolicy collisionPolicy, PathEvaluator collisionEvaluator, int maxDepth, Iterable<Node> startNodes, Iterable<Node> endNodes ) { super( resource ); this.sides.put( Direction.OUTGOING, new Side( start ) ); this.sides.put( Direction.INCOMING, new Side( end ) ); this.uniqueness = makeSureStartAndEndHasSameUniqueness( start, end ); // A little chicken-and-egg problem. This happens when constructing the start/end // selectors and they initially call evaluate() and isUniqueFirst, where the selector is used. // Solved this way for now, to have it return the start side to begin with. this.selector = alwaysOutgoingSide(); BranchSelector startSelector = start.branchOrdering.create( new AsOneStartBranch( this, startNodes, start.initialState ), start.expander ); BranchSelector endSelector = end.branchOrdering.create( new AsOneStartBranch( this, endNodes, end.initialState ), end.expander ); this.selector = sideSelector.create( startSelector, endSelector, maxDepth ); this.collisionDetector = collisionPolicy.create( collisionEvaluator ); } private BidirectionalUniquenessFilter makeSureStartAndEndHasSameUniqueness( MonoDirectionalTraversalDescription start, MonoDirectionalTraversalDescription end ) { if ( !start.uniqueness.equals( end.uniqueness ) ) { throw new IllegalArgumentException( "Start and end uniqueness factories differ, they need to be the " + "same currently. Start side has " + start.uniqueness + ", end side has " + end.uniqueness ); } boolean parameterDiffers = start.uniquenessParameter == null || end.uniquenessParameter == null ? start.uniquenessParameter != end.uniquenessParameter : !start.uniquenessParameter.equals( end.uniquenessParameter ); if ( parameterDiffers ) { throw new IllegalArgumentException( "Start and end uniqueness parameters differ, they need to be the " + "same currently. Start side has " + start.uniquenessParameter + ", " + "end side has " + end.uniquenessParameter ); } UniquenessFilter uniqueness = start.uniqueness.create( start.uniquenessParameter ); if ( !(uniqueness instanceof BidirectionalUniquenessFilter) ) { throw new IllegalArgumentException( "You must supply a BidirectionalUniquenessFilter, " + "not just a UniquenessFilter." ); } return (BidirectionalUniquenessFilter) uniqueness; } private SideSelector alwaysOutgoingSide() { return new SideSelector() { @Override public TraversalBranch next( TraversalContext metadata ) { throw new UnsupportedOperationException(); } @Override public Direction currentSide() { return Direction.OUTGOING; } }; } @Override protected Path fetchNextOrNull() { if ( foundPaths != null ) { if ( foundPaths.hasNext() ) { numberOfPathsReturned++; Path next = foundPaths.next(); return next; } foundPaths = null; } TraversalBranch result = null; while ( true ) { result = selector.next( this ); if ( result == null ) { close(); return null; } Iterable<Path> pathCollisions = collisionDetector.evaluate( result, selector.currentSide() ); if ( pathCollisions != null ) { foundPaths = uniquenessFiltered( pathCollisions.iterator() ); if ( foundPaths.hasNext() ) { numberOfPathsReturned++; Path next = foundPaths.next(); return next; } } } } private Iterator<Path> uniquenessFiltered( Iterator<Path> paths ) { return new FilteringIterator<>( paths, uniquenessPredicate ); } private Side currentSideDescription() { return sides.get( selector.currentSide() ); } @Override public Evaluation evaluate( TraversalBranch branch, BranchState state ) { return currentSideDescription().description.evaluator.evaluate( branch, state ); } @Override public boolean isUniqueFirst( TraversalBranch branch ) { return uniqueness.checkFirst( branch ); } @Override public boolean isUnique( TraversalBranch branch ) { return uniqueness.check( branch ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_BidirectionalTraverserIterator.java
677
return new DefaultTraverser( new Factory<TraverserIterator>(){ @Override public TraverserIterator newInstance() { return new BidirectionalTraverserIterator( statementFactory.instance(), start, end, sideSelector, collisionPolicy, collisionEvaluator, maxDepth, startNodes, endNodes); } });
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_BidirectionalTraversalDescriptionImpl.java
678
public class BidirectionalTraversalDescriptionImpl implements BidirectionalTraversalDescription { final MonoDirectionalTraversalDescription start; final MonoDirectionalTraversalDescription end; final PathEvaluator collisionEvaluator; final SideSelectorPolicy sideSelector; final org.neo4j.graphdb.traversal.BranchCollisionPolicy collisionPolicy; final Provider<? extends Resource> statementFactory; final int maxDepth; private BidirectionalTraversalDescriptionImpl( MonoDirectionalTraversalDescription start, MonoDirectionalTraversalDescription end, org.neo4j.graphdb.traversal.BranchCollisionPolicy collisionPolicy, PathEvaluator collisionEvaluator, SideSelectorPolicy sideSelector, Provider<? extends Resource> statementFactory, int maxDepth ) { this.start = start; this.end = end; this.collisionPolicy = collisionPolicy; this.collisionEvaluator = collisionEvaluator; this.sideSelector = sideSelector; this.statementFactory = statementFactory; this.maxDepth = maxDepth; } public BidirectionalTraversalDescriptionImpl(Provider<? extends Resource> statementFactory) { // TODO Proper defaults. this( new MonoDirectionalTraversalDescription(), new MonoDirectionalTraversalDescription(), STANDARD, Evaluators.all(), ALTERNATING, statementFactory, Integer.MAX_VALUE ); } public BidirectionalTraversalDescriptionImpl() { this( NO_STATEMENT ); } @Override public BidirectionalTraversalDescription startSide( TraversalDescription startSideDescription ) { assertIsMonoDirectional( startSideDescription ); return new BidirectionalTraversalDescriptionImpl( (MonoDirectionalTraversalDescription)startSideDescription, this.end, this.collisionPolicy, this.collisionEvaluator, this.sideSelector, statementFactory, this.maxDepth ); } @Override public BidirectionalTraversalDescription endSide( TraversalDescription endSideDescription ) { assertIsMonoDirectional( endSideDescription ); return new BidirectionalTraversalDescriptionImpl( this.start, (MonoDirectionalTraversalDescription)endSideDescription, this.collisionPolicy, this.collisionEvaluator, this.sideSelector, statementFactory, this.maxDepth ); } @Override public BidirectionalTraversalDescription mirroredSides( TraversalDescription sideDescription ) { assertIsMonoDirectional( sideDescription ); return new BidirectionalTraversalDescriptionImpl( (MonoDirectionalTraversalDescription)sideDescription, (MonoDirectionalTraversalDescription)sideDescription.reverse(), collisionPolicy, collisionEvaluator, sideSelector, statementFactory, maxDepth ); } @Override public BidirectionalTraversalDescription collisionPolicy( org.neo4j.graphdb.traversal.BranchCollisionPolicy collisionPolicy ) { return new BidirectionalTraversalDescriptionImpl( this.start, this.end, collisionPolicy, this.collisionEvaluator, this.sideSelector, statementFactory, this.maxDepth ); } @Override public BidirectionalTraversalDescription collisionPolicy( BranchCollisionPolicy collisionPolicy ) { return new BidirectionalTraversalDescriptionImpl( this.start, this.end, collisionPolicy, this.collisionEvaluator, this.sideSelector, statementFactory, this.maxDepth ); } @Override public BidirectionalTraversalDescription collisionEvaluator( PathEvaluator collisionEvaluator ) { nullCheck( collisionEvaluator, Evaluator.class, "RETURN_ALL" ); return new BidirectionalTraversalDescriptionImpl( this.start, this.end, this.collisionPolicy, addEvaluator( this.collisionEvaluator, collisionEvaluator ), this.sideSelector, statementFactory, maxDepth ); } @Override public BidirectionalTraversalDescription collisionEvaluator( Evaluator collisionEvaluator ) { return collisionEvaluator( new Evaluator.AsPathEvaluator( collisionEvaluator ) ); } @Override public BidirectionalTraversalDescription sideSelector( SideSelectorPolicy sideSelector, int maxDepth ) { return new BidirectionalTraversalDescriptionImpl( this.start, this.end, this.collisionPolicy, this.collisionEvaluator, sideSelector, statementFactory, maxDepth ); } @Override public Traverser traverse( Node start, Node end ) { return traverse( Arrays.asList( start ), Arrays.asList( end ) ); } @Override public Traverser traverse( final Iterable<Node> startNodes, final Iterable<Node> endNodes ) { return new DefaultTraverser( new Factory<TraverserIterator>(){ @Override public TraverserIterator newInstance() { return new BidirectionalTraverserIterator( statementFactory.instance(), start, end, sideSelector, collisionPolicy, collisionEvaluator, maxDepth, startNodes, endNodes); } }); } /** * We currently only support mono-directional traversers as "inner" traversers, so we need to check specifically * for this when the user specifies traversers to work with. */ private void assertIsMonoDirectional( TraversalDescription traversal ) { if( !( traversal instanceof MonoDirectionalTraversalDescription ) ) { throw new IllegalArgumentException( "The bi-directional traversals currently do not support using " + "anything but mono-directional traversers as start and stop points. Please provide a regular " + "mono-directional traverser instead." ); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_BidirectionalTraversalDescriptionImpl.java
679
class AsOneStartBranch implements TraversalBranch { private Iterator<TraversalBranch> branches; private int expanded; private final TraversalContext context; private final InitialBranchState initialState; AsOneStartBranch( TraversalContext context, Iterable<Node> nodes, InitialBranchState initialState ) { this.context = context; this.initialState = initialState; this.branches = toBranches( nodes ); } private Iterator<TraversalBranch> toBranches( Iterable<Node> nodes ) { List<TraversalBranch> result = new ArrayList<TraversalBranch>(); for ( Node node : nodes ) result.add( new StartNodeTraversalBranch( context, this, node, initialState ) ); return result.iterator(); } @Override public TraversalBranch parent() { return null; } @Override public int length() { return -1; } @Override public Node endNode() { throw new UnsupportedOperationException(); } @Override public Relationship lastRelationship() { throw new UnsupportedOperationException(); } @Override public TraversalBranch next( PathExpander expander, TraversalContext metadata ) { if ( branches.hasNext() ) { expanded++; return branches.next().next( expander, metadata ); } return null; } @Override public int expanded() { return expanded; } @Override public boolean continues() { return true; } @Override public boolean includes() { return false; } @Override public void evaluation( Evaluation eval ) { throw new UnsupportedOperationException(); } @Override public void initialize( PathExpander expander, TraversalContext metadata ) { } @Override public Node startNode() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> relationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> reverseRelationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> nodes() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> reverseNodes() { throw new UnsupportedOperationException(); } @Override public Iterator<PropertyContainer> iterator() { throw new UnsupportedOperationException(); } @Override public void prune() { branches = Collections.<TraversalBranch>emptyList().iterator(); } @Override public Object state() { throw new UnsupportedOperationException(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_AsOneStartBranch.java
680
public class TestUniqueness extends TraversalTestBase { @Test public void nodeLevelUniqueness() throws Exception { /* * (b) * / | \ * (e)==(a)--(c) * \ | * (d) */ createGraph( "a TO b", "a TO c", "a TO d", "a TO e", "a TO e", "b TO e", "d TO e", "c TO b" ); RelationshipType to = withName( "TO" ); Transaction tx = beginTx(); try { Node a = getNodeWithName( "a" ); Node e = getNodeWithName( "e" ); Path[] paths = splitPathsOnePerLevel( traversal().relationships( to, OUTGOING ) .uniqueness( NODE_LEVEL ).evaluator( includeWhereEndNodeIs( e ) ).traverse( a ) ); NodePathRepresentation pathRepresentation = new NodePathRepresentation( NAME_PROPERTY_REPRESENTATION ); assertEquals( "a,e", pathRepresentation.represent( paths[1] ) ); String levelTwoPathRepresentation = pathRepresentation.represent( paths[2] ); assertTrue( levelTwoPathRepresentation.equals( "a,b,e" ) || levelTwoPathRepresentation.equals( "a,d,e" ) ); assertEquals( "a,c,b,e", pathRepresentation.represent( paths[3] ) ); tx.success(); } finally { tx.finish(); } } @Test public void nodeGlobalUniqueness() { /* * (a)-TO->(b)-TO->(c) * \----TO---->/ */ createGraph( "a TO b", "a TO c", "b TO c" ); RelationshipType to = withName( "TO" ); Transaction tx = beginTx(); try { Node a = getNodeWithName( "a" ); Node c = getNodeWithName( "c" ); Iterator<Path> path = traversal().relationships( to, OUTGOING ).uniqueness( NODE_GLOBAL ).evaluator( includeWhereEndNodeIs( c ) ).traverse( a ).iterator(); Path thePath = path.next(); assertFalse( path.hasNext() ); NodePathRepresentation pathRepresentation = new NodePathRepresentation( NAME_PROPERTY_REPRESENTATION ); assertEquals( "a,b,c", pathRepresentation.represent( thePath ) ); tx.success(); } finally { tx.finish(); } } @Test public void relationshipLevelAndGlobalUniqueness() throws Exception { /* * (a)=TO=>(b)=TO=>(c)-TO->(d) * \====TO====>/ */ createGraph( "a TO b", "b TO c", "a TO b", "b TO c", "a TO c", "a TO c", "c TO d" ); RelationshipType to = withName( "TO" ); Transaction tx = beginTx(); try { Node a = getNodeWithName( "a" ); Node d = getNodeWithName( "d" ); Iterator<Path> paths = traversal().relationships( to, OUTGOING ).uniqueness( Uniqueness.NONE ).evaluator( includeWhereEndNodeIs( d ) ).traverse( a ).iterator(); int count = 0; while ( paths.hasNext() ) { count++; paths.next(); } assertEquals( "wrong number of paths calculated, the test assumption is wrong", 6, count ); // Now do the same traversal but with unique per level relationships paths = traversal().relationships( to, OUTGOING ).uniqueness( RELATIONSHIP_LEVEL ).evaluator( includeWhereEndNodeIs( d ) ).traverse( a ).iterator(); count = 0; while ( paths.hasNext() ) { count++; paths.next(); } /* * And yet again, but this time with global uniqueness, it should present only one path, since * c TO d is contained on all paths. */ paths = traversal().relationships( to, OUTGOING ).uniqueness( RELATIONSHIP_GLOBAL ).evaluator( includeWhereEndNodeIs( d ) ).traverse( a ).iterator(); count = 0; while ( paths.hasNext() ) { count++; paths.next(); } assertEquals( "wrong number of paths calculated with relationship global uniqueness", 1, count ); } finally { tx.finish(); } } private Path[] splitPathsOnePerLevel( Traverser traverser ) { Path[] paths = new Path[10]; for ( Path path : traverser ) { int depth = path.length(); if ( paths[depth] != null ) { fail( "More than one path one depth " + depth ); } paths[depth] = path; } return paths; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_traversal_TestUniqueness.java
681
{ @Override public boolean hasNext() { return false; } @Override public Relationship next() { throw new UnsupportedOperationException(); } @Override public void remove() { throw new UnsupportedOperationException(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_traversal_TraversalBranchImpl.java
682
public class MultipleCauseException extends Exception { private static final long serialVersionUID = -5556701516106141749L; private static final String ALSO_CAUSED_BY = "Also caused by: "; private final List<Throwable> causes = new ArrayList<>(); public MultipleCauseException( String message, Throwable firstCause ) { super( message, firstCause ); causes.add( firstCause ); } public MultipleCauseException( String message, List<Throwable> causes ) { super( message, causes.get( 0 ) ); for (Throwable cause : causes) { addCause( cause ); } } public List<Throwable> getCauses() { return causes; } public void addCause( Throwable cause ) { causes.add( cause ); } @Override public void printStackTrace( PrintStream out ) { super.printStackTrace( out ); printAllButFirstCauseStackTrace( out ); } @Override public void printStackTrace( PrintWriter out ) { super.printStackTrace( out ); printAllButFirstCauseStackTrace( out ); } private void printAllButFirstCauseStackTrace( PrintStream out ) { Iterator<Throwable> causeIterator = causes.iterator(); if ( causeIterator.hasNext() ) { causeIterator.next(); // Skip first (already printed by default // PrintStackTrace) while ( causeIterator.hasNext() ) { out.print( ALSO_CAUSED_BY ); causeIterator.next().printStackTrace( out ); } } } private void printAllButFirstCauseStackTrace( PrintWriter out ) { Iterator<Throwable> causeIterator = causes.iterator(); if ( causeIterator.hasNext() ) { causeIterator.next(); // Skip first (already printed by default // PrintStackTrace) while ( causeIterator.hasNext() ) { out.print( ALSO_CAUSED_BY ); causeIterator.next().printStackTrace( out ); } } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_MultipleCauseException.java
683
{ @Override public boolean remove( Object o ) { throw new UnsupportedOperationException(); } @Override public Iterator<Entry<K, V>> iterator() { return new UnsupportedRemoveIterator<Entry<K,V>>( actual.entrySet().iterator() ) { @Override public Entry<K, V> next() { final Entry<K, V> actualNext = super.next(); return new Entry<K,V>() { @Override public K getKey() { return actualNext.getKey(); } @Override public V getValue() { return actualNext.getValue(); } @Override public V setValue( V value ) { throw new UnsupportedOperationException(); } @Override public boolean equals( Object obj ) { return actualNext.equals( obj ); } @Override public int hashCode() { return actualNext.hashCode(); } }; } }; } @Override public int size() { return actual.size(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_CopyOnWriteHashMap.java
684
NO_ADDED_ELEMENTS { @Override void computeNext( DiffApplyingPrimitiveLongIterator self ) { self.endReached(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DiffApplyingPrimitiveLongIterator.java
685
ADDED_ELEMENTS { @Override void computeNext( DiffApplyingPrimitiveLongIterator self ) { self.computeNextFromAddedElements(); } },
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DiffApplyingPrimitiveLongIterator.java
686
FILTERED_SOURCE { @Override void computeNext( DiffApplyingPrimitiveLongIterator self ) { self.computeNextFromSourceAndFilter(); } },
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DiffApplyingPrimitiveLongIterator.java
687
NO_ADDED_ELEMENTS { @Override void computeNext( DiffApplyingPrimitiveIntIterator self ) { self.endReached(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DiffApplyingPrimitiveIntIterator.java
688
ADDED_ELEMENTS { @Override void computeNext( DiffApplyingPrimitiveIntIterator self ) { self.computeNextFromAddedElements(); } },
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DiffApplyingPrimitiveIntIterator.java
689
FILTERED_SOURCE { @Override void computeNext( DiffApplyingPrimitiveIntIterator self ) { self.computeNextFromSourceAndFilter(); } },
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DiffApplyingPrimitiveIntIterator.java
690
{ @Override public void run() { print( out, interestThreshold ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
691
public static class StackTracer { private final Map<Stack, AtomicInteger> uniqueStackTraces = new HashMap<>(); private boolean considerMessages = true; public void add( Throwable t ) { Stack key = new Stack( t, considerMessages ); AtomicInteger count = uniqueStackTraces.get( key ); if ( count == null ) { count = new AtomicInteger(); uniqueStackTraces.put( key, count ); } count.incrementAndGet(); } public void print( PrintStream out, int interestThreshold ) { System.out.println( "Printing stack trace counts:" ); long total = 0; for ( Map.Entry<Stack, AtomicInteger> entry : uniqueStackTraces.entrySet() ) { if ( entry.getValue().get() >= interestThreshold ) { out.println( entry.getValue() + " times:" ); entry.getKey().stackTrace.printStackTrace( out ); } total += entry.getValue().get(); } out.println( "------" ); out.println( "Total:" + total ); } public StackTracer printAtShutdown( final PrintStream out, final int interestThreshold ) { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { print( out, interestThreshold ); } } ); return this; } public StackTracer ignoreMessages() { considerMessages = false; return this; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
692
private static class Stack { private final Throwable stackTrace; private final StackTraceElement[] elements; private final boolean considerMessage; Stack( Throwable stackTrace, boolean considerMessage ) { this.stackTrace = stackTrace; this.considerMessage = considerMessage; this.elements = stackTrace.getStackTrace(); } @Override public int hashCode() { int hashCode = stackTrace.getMessage() == null || !considerMessage ? 31 : stackTrace.getMessage().hashCode(); for ( StackTraceElement element : stackTrace.getStackTrace() ) { hashCode = hashCode * 9 + element.hashCode(); } return hashCode; } @Override public boolean equals( Object obj ) { if ( !( obj instanceof Stack) ) { return false; } Stack o = (Stack) obj; if ( considerMessage ) { if ( stackTrace.getMessage() == null ) { if ( o.stackTrace.getMessage() != null ) { return false; } } else if ( !stackTrace.getMessage().equals( o.stackTrace.getMessage() ) ) { return false; } } if ( elements.length != o.elements.length ) { return false; } for ( int i = 0; i < elements.length; i++ ) { if ( !elements[i].equals( o.elements[i] ) ) { return false; } } return true; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
693
{ @Override public void run() { print( out ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
694
public static class CallCounter<T> { private final Map<T, AtomicInteger> calls = new HashMap<>(); private final String name; public CallCounter( String name ) { this.name = name; } public CallCounter<T> printAtShutdown( final PrintStream out ) { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { print( out ); } } ); return this; } public void inc( T key ) { AtomicInteger count = calls.get( key ); if ( count == null ) { count = new AtomicInteger(); calls.put( key, count ); } count.incrementAndGet(); } private void print( PrintStream out ) { out.println( "Calls made regarding " + name + ":" ); for ( Map.Entry<T, AtomicInteger> entry : calls.entrySet() ) { out.println( "\t" + entry.getKey() + ": " + entry.getValue() ); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
695
{ @Override public boolean accept( StackTraceElement item ) { return item.getClassName().equals( cls.getName() ) && item.getMethodName().equals( methodName ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
696
{ @Override public boolean accept( StackTraceElement item ) { return item.getClassName().equals( className ) && item.getMethodName().equals( methodName ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
697
{ @Override public boolean accept( StackTraceElement item ) { return item.getClassName().equals( cls.getName() ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
698
{ @Override public boolean accept( StackTraceElement item ) { return item.getClassName().contains( classNamePart ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java
699
{ @Override public boolean accept( StackTraceElement item ) { return item.getClassName().equals( className ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_util_DebugUtil.java