    @Test
    public void testCircularBug()
    {
        final long timestamp = 3;
        try ( Transaction tx = beginTx() )
        {
            getNodeWithName( "2" ).setProperty( "timestamp", 1L );
            getNodeWithName( "3" ).setProperty( "timestamp", 2L );
            tx.success();
        }

        try ( Transaction tx2 = beginTx() )
        {
            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() );
        }
    }

    @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();
        }
    }

Try With Resources try(Transaction tx2=beginTx()) in method public testCircularBug() : void from class org.neo4j.kernel.impl.traversal.CircularGraphTest


    @Test
    public void testSmallestPossibleInit() throws Exception
    {
        Traverser traversal = traversal().traverse( node( "1" ) );
        int count = 0;
        try (Transaction transaction = beginTx())
        {
            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 );
        }
    }

    @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();
        }
    }

Try With Resources try(Transaction transaction=beginTx()) in method public testSmallestPossibleInit() : void from class org.neo4j.kernel.impl.traversal.DepthPitfallGraphTest


    private void execute( TraversalDescription traversal, Uniqueness uniqueness )
    {
        try (Transaction transaction = beginTx())
        {
            Traverser traverser = traversal.uniqueness( uniqueness ).traverse( node( "1" ) );
            assertFalse( "empty traversal", count( traverser ) == 0 );
        }
    }

    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();
        }
    }

Try With Resources try(Transaction transaction=beginTx()) in method private execute(traversal TraversalDescription, uniqueness Uniqueness) : void from class org.neo4j.kernel.impl.traversal.SmallestGraphEverTest


    @Test
    public void testTraverseRelationshipsWithStartNodeNotIncluded() throws Exception
    {
        try (Transaction transaction = beginTx())
        {
            TraversalDescription traversal = traversal().evaluator( excludeStartPosition() );
            assertEquals( 1, count( traversal.traverse( node( "1" ) ).relationships() ) );
        }
    }

    @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();
        }
    }

Try With Resources try(Transaction transaction=beginTx()) in method public testTraverseRelationshipsWithStartNodeNotIncluded() : void from class org.neo4j.kernel.impl.traversal.SmallestGraphEverTest


    @Test
    public void depthAsState() throws Exception
    {
        /*
         * (a) -> (b) -> (c) -> (d)
         *          \           ^
         *           v         /
         *           (e) -> (f) -> (g) -> (h)
         */
        createGraph( "a to b", "b to c", "c to d", "b to e", "e to f", "f to d", "f to g", "g to h" );

        try (Transaction tx = beginTx())
        {
            DepthStateExpander expander = new DepthStateExpander();
            count( traversal().expand( expander, initialState( 0 ) ).traverse( getNodeWithName( "a" ) ) );
            tx.success();
        }
    }

    @Test
    public void depthAsState() throws Exception
    {
        /*
         * (a) -> (b) -> (c) -> (d)
         *          \           ^
         *           v         /
         *           (e) -> (f) -> (g) -> (h)
         */
        createGraph( "a to b", "b to c", "c to d", "b to e", "e to f", "f to d", "f to g", "g to h" );

        Transaction tx = beginTx();
        try
        {
            DepthStateExpander expander = new DepthStateExpander();
            count( traversal().expand( expander, initialState( 0 ) ).traverse( getNodeWithName( "a" ) ) );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public depthAsState() : void from class org.neo4j.kernel.impl.traversal.TestBranchState


    @Test
    public void everyOtherDepthAsState() throws Exception
    {
        /*
         * (a) -> (b) -> (c) -> (e)
         */
        createGraph( "a to b", "b to c", "c to d", "d to e" );
        try ( Transaction tx = beginTx() )
        {

        /*
         * Asserts that state continues down branches even when expander doesn't
         * set new state for every step.
         */
            IncrementEveryOtherDepthCountingExpander expander = new IncrementEveryOtherDepthCountingExpander();
            count( traversal().expand( expander, initialState( 0 ) ).traverse( getNodeWithName( "a" ) ) );
            tx.success();
        }
    }

    @Test
    public void everyOtherDepthAsState() throws Exception
    {
        /*
         * (a) -> (b) -> (c) -> (e)
         */
        createGraph( "a to b", "b to c", "c to d", "d to e" );
        Transaction tx = beginTx();
        try
        {

        /*
         * Asserts that state continues down branches even when expander doesn't
         * set new state for every step.
         */
            IncrementEveryOtherDepthCountingExpander expander = new IncrementEveryOtherDepthCountingExpander();
            count( traversal().expand( expander, initialState( 0 ) ).traverse( getNodeWithName( "a" ) ) );
            tx.success();
        }

        finally

        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public everyOtherDepthAsState() : void from class org.neo4j.kernel.impl.traversal.TestBranchState


    @Test
    public void evaluateState() throws Exception
    {
        /*
         * (a)-1->(b)-2->(c)-3->(d)
         *   \           ^
         *    4         6
         *    (e)-5->(f)
         */
        createGraph( "a TO b", "b TO c", "c TO d", "a TO e", "e TO f", "f TO c" );

        try ( Transaction tx = beginTx() )
        {
            PathEvaluator<Integer> evaluator = new PathEvaluator.Adapter<Integer>()
            {
                @Override
                public Evaluation evaluate( Path path, BranchState<Integer> state )
                {
                    return ofIncludes( path.endNode().getProperty( "name" ).equals( "c" ) && state.getState() == 3 );
                }
            };

            expectPaths( traversal( NODE_PATH ).expand( new RelationshipWeightExpander(), new InitialBranchState.State<Integer>( 1, 1 ) )
                    .evaluator( evaluator ).traverse( getNodeWithName( "a" ) ), "a,b,c" );
            tx.success();
        }
    }

    @Test
    public void evaluateState() throws Exception
    {
        /*
         * (a)-1->(b)-2->(c)-3->(d)
         *   \           ^
         *    4         6
         *    (e)-5->(f)
         */
        createGraph( "a TO b", "b TO c", "c TO d", "a TO e", "e TO f", "f TO c" );

        Transaction tx = beginTx();
        try
        {
            PathEvaluator<Integer> evaluator = new PathEvaluator.Adapter<Integer>()
            {
                @Override
                public Evaluation evaluate( Path path, BranchState<Integer> state )
                {
                    return ofIncludes( path.endNode().getProperty( "name" ).equals( "c" ) && state.getState() == 3 );
                }
            };

            expectPaths( traversal( NODE_PATH ).expand( new RelationshipWeightExpander(), new InitialBranchState.State<Integer>( 1, 1 ) )
                    .evaluator( evaluator ).traverse( getNodeWithName( "a" ) ), "a,b,c" );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public evaluateState() : void from class org.neo4j.kernel.impl.traversal.TestBranchState


    private void testCIsReturnedOnDepthTwo( TraversalDescription description )
    {
        try ( Transaction transaction = beginTx() )
        {
            description = description.expand( PathExpanders.forTypeAndDirection( ONE, OUTGOING ) );
            int i = 0;
            for ( Path position : description.traverse( node( "A" ) ) )
            {
                assertEquals( i++, position.length() );
            }
        }
    }

    private void testCIsReturnedOnDepthTwo( TraversalDescription description )
    {
        Transaction transaction = beginTx();
        try
        {
            description = description.expand( PathExpanders.forTypeAndDirection( ONE, OUTGOING ) );
            int i = 0;
            for ( Path position : description.traverse( node( "A" ) ) )
            {
                assertEquals( i++, position.length() );
            }
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=beginTx()) in method private testCIsReturnedOnDepthTwo(description TraversalDescription) : void from class org.neo4j.kernel.impl.traversal.TestMultiRelTypesAndDirections


    @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" );

        try ( Transaction tx = beginTx() )
        {
            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 );
        }
    }

    @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();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public myFriendsAsWellAsYourFriends() : void from class org.neo4j.kernel.impl.traversal.TestMultipleStartNodes


    @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" );

        try ( Transaction tx = beginTx() )
        {
            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" );
        }
    }

    @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();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public specificPath() : void from class org.neo4j.kernel.impl.traversal.TestPathDescription


    @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" );

        try ( Transaction tx = beginTx() )
        {
            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();
        }
    }

    @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();
        }

    }

Try With Resources try(Transaction tx=beginTx()) in method public traverseThroughNodeWithLoop() : void from class org.neo4j.kernel.impl.traversal.TestTraversalWithLoops


    @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" );
        try ( Transaction tx = beginTx() )
        {
            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();
        }
    }

    @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();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public nodeLevelUniqueness() : void from class org.neo4j.kernel.impl.traversal.TestUniqueness


    @Test
    public void nodeGlobalUniqueness()
    {
        /*
         * (a)-TO->(b)-TO->(c)
         *   \----TO---->/
         */
        createGraph( "a TO b", "a TO c", "b TO c" );
        RelationshipType to = withName( "TO" );

        try ( Transaction tx = beginTx() )
        {
            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();
        }
    }

    @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();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public nodeGlobalUniqueness() : void from class org.neo4j.kernel.impl.traversal.TestUniqueness


    @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" );

        try ( Transaction tx = beginTx() )
        {
            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 );
        }
    }

    @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();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public relationshipLevelAndGlobalUniqueness() : void from class org.neo4j.kernel.impl.traversal.TestUniqueness


    private Map<String, Node> createGraph( GraphDefinition graph )
    {
        try ( Transaction tx = beginTx() )
        {
            Map<String, Node> result = graph.create( getGraphDb() );
            tx.success();
            return result;
        }
    }

    private Map<String, Node> createGraph( GraphDefinition graph )
    {
        Transaction tx = beginTx();
        try
        {
            Map<String, Node> result = graph.create( getGraphDb() );
            tx.success();
            return result;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method private createGraph(graph GraphDefinition) : Map<String,Node> from class org.neo4j.kernel.impl.traversal.TraversalTestBase


    protected <T> void expect( Iterable<? extends T> items,
            Representation<T> representation, Set<String> expected )
    {
        Collection<String> encounteredItems = new ArrayList<String>();
        try (Transaction tx = beginTx())
        {
            for ( T item : items )
            {
                String repr = representation.represent( item );
                assertTrue( repr + " not expected ", expected.remove( repr ) );
                encounteredItems.add( repr );
            }
            tx.success();
        }

        if ( !expected.isEmpty() )
        {
            fail( "The exepected elements " + expected + " were not returned. Returned were: " + encounteredItems );
        }
    }

    protected <T> void expect( Iterable<? extends T> items,
            Representation<T> representation, Set<String> expected )
    {
        Transaction tx = beginTx();
        Collection<String> encounteredItems = new ArrayList<String>();
        try
        {
            for ( T item : items )
            {
                String repr = representation.represent( item );
                assertTrue( repr + " not expected ", expected.remove( repr ) );
                encounteredItems.add( repr );
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }

        if ( !expected.isEmpty() )
        {
            fail( "The exepected elements " + expected + " were not returned. Returned were: " + encounteredItems );
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method protected expect(items Iterable<? extends T>, representation Representation<T>, expected Set<String>) : void from class org.neo4j.kernel.impl.traversal.TraversalTestBase


    @Test
    public void nodesIteratorReturnAllNodes() throws Exception
    {
        try ( Transaction transaction = beginTx() )
        {
            Traverser traverser = traversal().traverse( node( "1" ) );
            int count = 0;
            for ( Node node : traverser.nodes() )
            {
                assertNotNull( "returned nodes should not be null. node #"
                               + count, node );
                count++;
            }
            assertEquals( 13, count );
        }
    }

    @Test
    public void nodesIteratorReturnAllNodes() throws Exception
    {
        Transaction transaction = beginTx();
        try
        {
            Traverser traverser = traversal().traverse( node( "1" ) );
            int count = 0;
            for ( Node node : traverser.nodes() )
            {
                assertNotNull( "returned nodes should not be null. node #"
                               + count, node );
                count++;
            }
            assertEquals( 13, count );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=beginTx()) in method public nodesIteratorReturnAllNodes() : void from class org.neo4j.kernel.impl.traversal.TreeGraphTest


    @Test
    public void relationshipsIteratorReturnAllNodes() throws Exception
    {
        try ( Transaction transaction = beginTx() )
        {
            Traverser traverser = traversal().traverse( node( "1" ) );
            int count = 0;
            for ( Relationship relationship : traverser.relationships() )
            {
                assertNotNull(
                        "returned relationships should not be. relationship #"
                                + count, relationship );
                count++;
            }
            assertEquals( 12, count );
        }
    }

    @Test
    public void relationshipsIteratorReturnAllNodes() throws Exception
    {
        Transaction transaction = beginTx();
        try
        {
            Traverser traverser = traversal().traverse( node( "1" ) );
            int count = 0;
            for ( Relationship relationship : traverser.relationships() )
            {
                assertNotNull(
                        "returned relationships should not be. relationship #"
                                + count, relationship );
                count++;
            }
            assertEquals( 12, count );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=beginTx()) in method public relationshipsIteratorReturnAllNodes() : void from class org.neo4j.kernel.impl.traversal.TreeGraphTest


    @Test
    public void pathsIteratorReturnAllNodes() throws Exception
    {

        try ( Transaction transaction = beginTx() )
        {
            Traverser traverser = traversal().traverse( node( "1" ) );
            int count = 0;
            for ( Path path : traverser )
            {
                assertNotNull( "returned paths should not be null. path #"
                               + count, path );
                count++;
            }
            assertEquals( 13, count );
        }
    }

    @Test
    public void pathsIteratorReturnAllNodes() throws Exception
    {
        Transaction transaction = beginTx();
        try
        {
            Traverser traverser = traversal().traverse( node( "1" ) );
            int count = 0;
            for ( Path path : traverser )
            {
                assertNotNull( "returned paths should not be null. path #"
                               + count, path );
                count++;
            }
            assertEquals( 13, count );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=beginTx()) in method public pathsIteratorReturnAllNodes() : void from class org.neo4j.kernel.impl.traversal.TreeGraphTest


    @Test
    public void testDepthFirstTraversalReturnsNodesOnCorrectDepths()
            throws Exception
    {

        try ( Transaction transaction = beginTx() )
        {
            Traverser traverser = traversal().depthFirst().traverse( node( "1" ) );
            int i = 0;
            for ( Path pos : traverser )
            {
                assertEquals( expectedDepth( i++ ), pos.length() );
            }
            assertEquals( 13, i );
        }
    }

    @Test
    public void testDepthFirstTraversalReturnsNodesOnCorrectDepths()
            throws Exception
    {
        Transaction transaction = beginTx();
        try
        {
            Traverser traverser = traversal().depthFirst().traverse( node( "1" ) );
            int i = 0;
            for ( Path pos : traverser )
            {
                assertEquals( expectedDepth( i++ ), pos.length() );
            }
            assertEquals( 13, i );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=beginTx()) in method public testDepthFirstTraversalReturnsNodesOnCorrectDepths() : void from class org.neo4j.kernel.impl.traversal.TreeGraphTest


    @Test
    public void testPostorderBreadthFirstReturnsDeeperNodesFirst()
    {
        Traverser traverser = traversal().order( POSTORDER_BREADTH_FIRST ).traverse( node( "1" ) );
        Stack<Set<String>> levels = new Stack<>();
        levels.push( new HashSet<>( asList( "1" ) ) );
        levels.push( new HashSet<>( asList( "2", "3", "4" ) ) );
        levels.push( new HashSet<>( asList( "5", "6", "7", "8",
                "9", "A", "B", "C", "D" ) ) );
        try ( Transaction tx = beginTx() )
        {
            assertLevels( traverser, levels );
            tx.success();
        }
    }

    @Test
    public void testPostorderBreadthFirstReturnsDeeperNodesFirst()
    {
        Traverser traverser = traversal().order( POSTORDER_BREADTH_FIRST ).traverse( node( "1" ) );
        Stack<Set<String>> levels = new Stack<>();
        levels.push( new HashSet<>( asList( "1" ) ) );
        levels.push( new HashSet<>( asList( "2", "3", "4" ) ) );
        levels.push( new HashSet<>( asList( "5", "6", "7", "8",
                "9", "A", "B", "C", "D" ) ) );
        Transaction tx = beginTx();
        try
        {
            assertLevels( traverser, levels );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=beginTx()) in method public testPostorderBreadthFirstReturnsDeeperNodesFirst() : void from class org.neo4j.kernel.impl.traversal.TreeGraphTest


        @Override
        public Map<String, Node> create( GraphDatabaseService graphdb )
        {
            // don't bother with creating a transaction
            return new HashMap<>();
        }

        @Override
        public Map<String, Node> create( GraphDatabaseService graphdb )
        {
            // don't bother with creating a transaction
            return new HashMap<String, Node>();
        }

Replace Generic With Diamond HashMap<String,Node> with HashMap<> in method public create(graphdb GraphDatabaseService) : Map<String,Node> from class org.neo4j.test.GraphDescription.EMPTY.new GraphDescription


    @Override
    public Map<String, Node> create( GraphDatabaseService graphdb )
    {
        Map<String, Node> result = new HashMap<>();
        try ( Transaction tx = graphdb.beginTx() )
        {
            graphdb.index().getRelationshipAutoIndexer().setEnabled( autoIndexRelationships );
            for ( NODE def : nodes )
            {
                Node node = init( graphdb.createNode(), def.setNameProperty() ? def.name() : null, def.properties(), graphdb.index().getNodeAutoIndexer(), autoIndexNodes );
                for ( LABEL label : def.labels() )
                {
                    node.addLabel( label( label.value() ) );
                }
                result.put( def.name(), node );
            }
            for ( REL def : rels )
            {
                init( result.get( def.start() ).createRelationshipTo( result.get( def.end() ),
                        DynamicRelationshipType.withName( def.type() ) ), def.setNameProperty() ? def.name() : null,
                        def.properties(), graphdb.index().getRelationshipAutoIndexer(), autoIndexRelationships );
            }
            tx.success();
        }
        return result;
    }

    @Override
    public Map<String, Node> create( GraphDatabaseService graphdb )
    {
        Map<String, Node> result = new HashMap<String, Node>();
        Transaction tx = graphdb.beginTx();
        try
        {
            graphdb.index().getRelationshipAutoIndexer().setEnabled( autoIndexRelationships );
            for ( NODE def : nodes )
            {
                Node node = init( graphdb.createNode(), def.setNameProperty() ? def.name() : null, def.properties(), graphdb.index().getNodeAutoIndexer(), autoIndexNodes );
                for ( LABEL label : def.labels() )
                {
                    node.addLabel( label( label.value() ) );
                }
                result.put( def.name(), node );
            }
            for ( REL def : rels )
            {
                init( result.get( def.start() ).createRelationshipTo( result.get( def.end() ),
                        DynamicRelationshipType.withName( def.type() ) ), def.setNameProperty() ? def.name() : null,
                        def.properties(), graphdb.index().getRelationshipAutoIndexer(), autoIndexRelationships );
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
        return result;
    }

Try With Resources try(Transaction tx=graphdb.beginTx()) in method public create(graphdb GraphDatabaseService) : Map<String,Node> from class org.neo4j.test.GraphDescription


    public static void destroy( Map<String, Node> nodes )
    {
        if ( nodes.isEmpty() ) return;
        GraphDatabaseService db = nodes.values().iterator().next().getGraphDatabase();
        try ( Transaction tx = db.beginTx() )
        {
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
            {
                for ( Relationship rel : node.getRelationships() )
                    rel.delete();
                node.delete();
            }
            tx.success();
        }
    }

    public static void destroy( Map<String, Node> nodes )
    {
        if ( nodes.isEmpty() ) return;
        GraphDatabaseService db = nodes.values().iterator().next().getGraphDatabase();
        Transaction tx = db.beginTx();
        try
        {
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
            {
                for ( Relationship rel : node.getRelationships() )
                    rel.delete();
                node.delete();
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method public destroy(nodes Map<String,Node>) : void from class org.neo4j.test.GraphDescription


    private static void createIfAbsent( Map<String, NODE> nodes, String name, String ... labels )
    {
        if ( !nodes.containsKey( name ) )
        {
            nodes.put( name, new DefaultNode( name, labels ) );
        }
        else
        {
            NODE preexistingNode = nodes.get( name );
            // Join with any new labels
            HashSet<String> joinedLabels = new HashSet<>( asList( labels ) );
            for ( LABEL label : preexistingNode.labels() )
            {
                joinedLabels.add( label.value() );
            }

            String[] labelNameArray = joinedLabels.toArray(new String[joinedLabels.size()]);
            nodes.put( name, new NodeWithAddedLabels(preexistingNode, labelNameArray));
        }
    }

    private static void createIfAbsent( Map<String, NODE> nodes, String name, String ... labels )
    {
        if ( !nodes.containsKey( name ) )
        {
            nodes.put( name, new DefaultNode( name, labels ) );
        }
        else
        {
            NODE preexistingNode = nodes.get( name );
            // Join with any new labels
            HashSet<String> joinedLabels = new HashSet<String>( asList( labels ));
            for ( LABEL label : preexistingNode.labels() )
            {
                joinedLabels.add( label.value() );
            }

            String[] labelNameArray = joinedLabels.toArray(new String[joinedLabels.size()]);
            nodes.put( name, new NodeWithAddedLabels(preexistingNode, labelNameArray));
        }
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method private createIfAbsent(nodes Map<String,NODE>, name String, labels String...) : void from class org.neo4j.test.GraphDescription


    private void createASocialNetwork( GraphDatabaseService db )
    {
        try ( Transaction tx = db.beginTx() )
        {
            jw = db.createNode();
            jw.setProperty( "name", "jim" );
            Node sp = db.createNode();
            sp.setProperty( "name", "savas" );
            Node bg = db.createNode();
            bg.setProperty( "name", "bill" );
            Node th = db.createNode();
            th.setProperty( "name", "tony" );
            Node rj = db.createNode();
            rj.setProperty( "name", "rhodri" );
            rj.setProperty( "hobby", "family" );
            Node nj = db.createNode();
            nj.setProperty( "name", "ned" );
            nj.setProperty( "hobby", "cs" );
            Node ml = db.createNode();
            ml.setProperty( "name", "mark" );
            Node mf = db.createNode();
            mf.setProperty( "name", "martin" );
            Node rp = db.createNode();
            rp.setProperty( "name", "rebecca" );
            Node rs = db.createNode();
            rs.setProperty( "name", "roy" );
            Node sc = db.createNode();
            sc.setProperty( "name", "steve" );
            sc.setProperty( "hobby", "cloud" );
            Node sw = db.createNode();
            sw.setProperty( "name", "stuart" );
            sw.setProperty( "hobby", "cs" );

            jw.createRelationshipTo( sp, KNOWS );
            jw.createRelationshipTo( mf, KNOWS );
            jw.createRelationshipTo( rj, KNOWS );
            rj.createRelationshipTo( nj, KNOWS );

            mf.createRelationshipTo( rp, KNOWS );
            mf.createRelationshipTo( rs, KNOWS );

            sp.createRelationshipTo( bg, KNOWS );
            sp.createRelationshipTo( th, KNOWS );
            sp.createRelationshipTo( mf, KNOWS );
            sp.createRelationshipTo( ml, WORKED_FOR );

            ml.createRelationshipTo( sc, KNOWS );
            ml.createRelationshipTo( sw, KNOWS );

            jw.setProperty( "hobby", "cs" );
            sp.setProperty( "hobby", "cs" );
            bg.setProperty( "hobby", "cs" );
            ml.setProperty( "hobby", "cs" );
            mf.setProperty( "hobby", "cs" );

            rp.setProperty( "hobby", "lisp" );
            rs.setProperty( "hobby", "socialism" );
            th.setProperty( "hobby", "fishing" );
            tx.success();
        }
    }

    private void createASocialNetwork( GraphDatabaseService db )
    {
        Transaction tx = db.beginTx();
        try
        {
            jw = db.createNode();
            jw.setProperty( "name", "jim" );
            Node sp = db.createNode();
            sp.setProperty( "name", "savas" );
            Node bg = db.createNode();
            bg.setProperty( "name", "bill" );
            Node th = db.createNode();
            th.setProperty( "name", "tony" );
            Node rj = db.createNode();
            rj.setProperty( "name", "rhodri" );
            rj.setProperty( "hobby", "family" );
            Node nj = db.createNode();
            nj.setProperty( "name", "ned" );
            nj.setProperty( "hobby", "cs" );
            Node ml = db.createNode();
            ml.setProperty( "name", "mark" );
            Node mf = db.createNode();
            mf.setProperty( "name", "martin" );
            Node rp = db.createNode();
            rp.setProperty( "name", "rebecca" );
            Node rs = db.createNode();
            rs.setProperty( "name", "roy" );
            Node sc = db.createNode();
            sc.setProperty( "name", "steve" );
            sc.setProperty( "hobby", "cloud" );
            Node sw = db.createNode();
            sw.setProperty( "name", "stuart" );
            sw.setProperty( "hobby", "cs" );

            jw.createRelationshipTo( sp, KNOWS );
            jw.createRelationshipTo( mf, KNOWS );
            jw.createRelationshipTo( rj, KNOWS );
            rj.createRelationshipTo( nj, KNOWS );

            mf.createRelationshipTo( rp, KNOWS );
            mf.createRelationshipTo( rs, KNOWS );

            sp.createRelationshipTo( bg, KNOWS );
            sp.createRelationshipTo( th, KNOWS );
            sp.createRelationshipTo( mf, KNOWS );
            sp.createRelationshipTo( ml, WORKED_FOR );

            ml.createRelationshipTo( sc, KNOWS );
            ml.createRelationshipTo( sw, KNOWS );

            jw.setProperty( "hobby", "cs" );
            sp.setProperty( "hobby", "cs" );
            bg.setProperty( "hobby", "cs" );
            ml.setProperty( "hobby", "cs" );
            mf.setProperty( "hobby", "cs" );

            rp.setProperty( "hobby", "lisp" );
            rs.setProperty( "hobby", "socialism" );
            th.setProperty( "hobby", "fishing" );
            tx.success();
        }
        finally
        {
            tx.finish();
        }

    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createASocialNetwork(db GraphDatabaseService) : void from class org.neo4j.server.plugins.CloneSubgraphPluginTest


    private int nodeCount()
    {
        try ( Transaction tx = server.getDatabase().getGraph().beginTx() )
        {
            int count = 0;
            for ( @SuppressWarnings("unused") Node node : GlobalGraphOperations.at( server.getDatabase().getGraph() )
                                                                               .getAllNodes() )
            {
                count++;
            }
            return count;
        }
    }

    private int nodeCount()
    {
        Transaction tx = server.getDatabase().getGraph().beginTx();
        try
        {
            int count = 0;
            for ( @SuppressWarnings("unused") Node node : GlobalGraphOperations.at( server.getDatabase().getGraph() )
                                                                               .getAllNodes() )
            {
                count++;
            }
            return count;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=server.getDatabase().getGraph().beginTx()) in method private nodeCount() : int from class org.neo4j.server.plugins.CloneSubgraphPluginTest


    @PluginTarget( Node.class )
    public Path pathToReference( @Source Node me )
    {
        PathFinder<Path> finder = GraphAlgoFactory.shortestPath( PathExpanders.allTypesAndDirections(), 6 );
        try ( Transaction tx = me.getGraphDatabase().beginTx() )
        {
            Node other;
            if ( me.hasRelationship( DynamicRelationshipType.withName( "friend" ) ) )
            {
                other = me.getRelationships( DynamicRelationshipType.withName( "friend" ) )
                        .iterator()
                        .next()
                        .getOtherNode( me );
            }
            else
            {
                other = me.getGraphDatabase().createNode();
            }
            Path path = finder.findSinglePath( other, me );

            tx.success();
            return path;
        }
    }

    @PluginTarget( Node.class )
    public Path pathToReference( @Source Node me )
    {
        PathFinder<Path> finder = GraphAlgoFactory.shortestPath( PathExpanders.allTypesAndDirections(), 6 );
        Transaction tx = me.getGraphDatabase().beginTx();
        try
        {
            Node other;
            if ( me.hasRelationship( DynamicRelationshipType.withName( "friend" ) ) )
            {
                other = me.getRelationships( DynamicRelationshipType.withName( "friend" ) )
                        .iterator()
                        .next()
                        .getOtherNode( me );
            }
            else
            {
                other = me.getGraphDatabase().createNode();
            }
            Path path = finder.findSinglePath( other, me );

            tx.success();
            return path;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=me.getGraphDatabase().beginTx()) in method public pathToReference(me Node) : Path from class org.neo4j.server.plugins.FunctionalTestPlugin


    @PluginTarget( Node.class )
    public Node clonedSubgraph( @Source Node startNode, @Parameter( name = "depth", optional = false ) Integer depth )
    {
        GraphDatabaseService graphDb = startNode.getGraphDatabase();
        try ( Transaction tx = graphDb.beginTx() )
        {
            Traverser traverse = traverseToDepth( startNode, depth );
            Iterator<Node> nodes = traverse.nodes()
                    .iterator();

            HashMap<Node, Node> clonedNodes = cloneNodes( graphDb, nodes );

            for ( Node oldNode : clonedNodes.keySet() )
            {
                // give me the matching new node
                Node newStartNode = clonedNodes.get( oldNode );

                // Now let's go through the relationships and copy them over
                Iterator<Relationship> oldRelationships = oldNode.getRelationships( Direction.OUTGOING )
                        .iterator();
                while ( oldRelationships.hasNext() )
                {
                    Relationship oldRelationship = oldRelationships.next();

                    Node newEndNode = clonedNodes.get( oldRelationship.getEndNode() );
                    if ( newEndNode != null )
                    {
                        Relationship newRelationship = newStartNode.createRelationshipTo( newEndNode,
                                oldRelationship.getType() );

                        cloneProperties( oldRelationship, newRelationship );
                    }
                }
            }

            tx.success();

            return clonedNodes.get( startNode );

        }
    }

    @PluginTarget( Node.class )
    public Node clonedSubgraph( @Source Node startNode, @Parameter( name = "depth", optional = false ) Integer depth )
    {
        GraphDatabaseService graphDb = startNode.getGraphDatabase();
        Transaction tx = graphDb.beginTx();
        try
        {
            Traverser traverse = traverseToDepth( startNode, depth );
            Iterator<Node> nodes = traverse.nodes()
                    .iterator();

            HashMap<Node, Node> clonedNodes = cloneNodes( graphDb, nodes );

            for ( Node oldNode : clonedNodes.keySet() )
            {
                // give me the matching new node
                Node newStartNode = clonedNodes.get( oldNode );

                // Now let's go through the relationships and copy them over
                Iterator<Relationship> oldRelationships = oldNode.getRelationships( Direction.OUTGOING )
                        .iterator();
                while ( oldRelationships.hasNext() )
                {
                    Relationship oldRelationship = oldRelationships.next();

                    Node newEndNode = clonedNodes.get( oldRelationship.getEndNode() );
                    if ( newEndNode != null )
                    {
                        Relationship newRelationship = newStartNode.createRelationshipTo( newEndNode,
                                oldRelationship.getType() );

                        cloneProperties( oldRelationship, newRelationship );
                    }
                }
            }

            tx.success();

            return clonedNodes.get( startNode );

        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public clonedSubgraph(startNode Node, depth Integer) : Node from class org.neo4j.server.plugins.GraphCloner


    private HashMap<Node, Node> cloneNodes( GraphDatabaseService graphDb, Iterator<Node> nodes )
    {
        HashMap<Node, Node> result = new HashMap<>();

        while ( nodes.hasNext() )
        {
            Node next = nodes.next();
            result.put( next, cloneNodeData( graphDb, next ) );
        }

        return result;
    }

    private HashMap<Node, Node> cloneNodes( GraphDatabaseService graphDb, Iterator<Node> nodes )
    {
        HashMap<Node, Node> result = new HashMap<Node, Node>();

        while ( nodes.hasNext() )
        {
            Node next = nodes.next();
            result.put( next, cloneNodeData( graphDb, next ) );
        }

        return result;
    }

Replace Generic With Diamond HashMap<Node,Node> with HashMap<> in method private cloneNodes(graphDb GraphDatabaseService, nodes Iterator<Node>) : HashMap<Node,Node> from class org.neo4j.server.plugins.GraphCloner


    @Test
    public void dumpJmxInfo() throws Exception
    {
        List<Triplet<String, String, String>> beanItems = new ArrayList<>();
        AsciiDocListGenerator listGenerator = new AsciiDocListGenerator( "jmx-list", "MBeans exposed by Neo4j", false );

        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        SortedMap<String, ObjectName> neo4jBeans = new TreeMap<>(
                String.CASE_INSENSITIVE_ORDER );

        for ( String query : QUERIES )
        {
            Set<ObjectInstance> beans = mBeanServer.queryMBeans(
                    new ObjectName( query ), null );
            for ( ObjectInstance bean : beans )
            {
                ObjectName objectName = bean.getObjectName();
                String name = objectName.getKeyProperty( BEAN_NAME );
                if ( EXCLUDES.contains( name ) )
                {
                    continue;
                }
                String name0 = objectName.getKeyProperty( BEAN_NAME0 );
                if ( name0 != null )
                {
                    name += '/' + name0;
                }
                neo4jBeans.put( name, bean.getObjectName() );
            }

        }
        assertEquals( "Sanity checking the number of beans found;",
                EXPECTED_NUMBER_OF_BEANS, neo4jBeans.size() );
        for ( Map.Entry<String, ObjectName> beanEntry : neo4jBeans.entrySet() )
        {
            ObjectName objectName = beanEntry.getValue();
            String name = beanEntry.getKey();
            Set<ObjectInstance> mBeans = mBeanServer.queryMBeans( objectName,
                    null );
            if ( mBeans.size() != 1 )
            {
                throw new IllegalStateException( "Unexpected size ["
                        + mBeans.size()
                        + "] of query result for ["
                        + objectName + "]." );
            }
            ObjectInstance bean = mBeans.iterator()
                    .next();
            MBeanInfo info = mBeanServer.getMBeanInfo( objectName );
            String description = info.getDescription()
                    .replace( '\n', ' ' );

            String id = getId( name );
            beanItems.add( Triplet.of( id, name, description ) );

            writeDetailsToFile( id, objectName, bean, info, description );
        }
        Writer fw = null;
        try
        {
            fw = AsciiDocGenerator.getFW( "target/docs/ops", "JMX List" );
            fw.write( listGenerator.generateListAndTableCombo( beanItems ) );
        }
        finally
        {
            if ( fw != null )
            {
                fw.close();
            }
        }
    }

    @Test
    public void dumpJmxInfo() throws Exception
    {
        List<Triplet<String, String, String>> beanItems = new ArrayList<>();
        AsciiDocListGenerator listGenerator = new AsciiDocListGenerator( "jmx-list", "MBeans exposed by Neo4j", false );

        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        SortedMap<String, ObjectName> neo4jBeans = new TreeMap<String, ObjectName>(
                String.CASE_INSENSITIVE_ORDER );

        for ( String query : QUERIES )
        {
            Set<ObjectInstance> beans = mBeanServer.queryMBeans(
                    new ObjectName( query ), null );
            for ( ObjectInstance bean : beans )
            {
                ObjectName objectName = bean.getObjectName();
                String name = objectName.getKeyProperty( BEAN_NAME );
                if ( EXCLUDES.contains( name ) )
                {
                    continue;
                }
                String name0 = objectName.getKeyProperty( BEAN_NAME0 );
                if ( name0 != null )
                {
                    name += '/' + name0;
                }
                neo4jBeans.put( name, bean.getObjectName() );
            }

        }
        assertEquals( "Sanity checking the number of beans found;",
                EXPECTED_NUMBER_OF_BEANS, neo4jBeans.size() );
        for ( Map.Entry<String, ObjectName> beanEntry : neo4jBeans.entrySet() )
        {
            ObjectName objectName = beanEntry.getValue();
            String name = beanEntry.getKey();
            Set<ObjectInstance> mBeans = mBeanServer.queryMBeans( objectName,
                    null );
            if ( mBeans.size() != 1 )
            {
                throw new IllegalStateException( "Unexpected size ["
                        + mBeans.size()
                        + "] of query result for ["
                        + objectName + "]." );
            }
            ObjectInstance bean = mBeans.iterator()
                    .next();
            MBeanInfo info = mBeanServer.getMBeanInfo( objectName );
            String description = info.getDescription()
                    .replace( '\n', ' ' );

            String id = getId( name );
            beanItems.add( Triplet.of( id, name, description ) );

            writeDetailsToFile( id, objectName, bean, info, description );
        }
        Writer fw = null;
        try
        {
            fw = AsciiDocGenerator.getFW( "target/docs/ops", "JMX List" );
            fw.write( listGenerator.generateListAndTableCombo( beanItems ) );
        }
        finally
        {
            if ( fw != null )
            {
                fw.close();
            }
        }
    }

Replace Generic With Diamond TreeMap<String,ObjectName> with TreeMap<> in method public dumpJmxInfo() : void from class jmx.JmxDocTest


    private void writeAttributesTable( String description,
                                       StringBuilder beanInfo, MBeanAttributeInfo[] attributes,
                                       boolean nonHtml )
    {
        addNonHtmlCondition( beanInfo, nonHtml );
        beanInfo.append(
                "[options=\"header\", cols=\"20m,36,20m,7,7\"]\n" + "|===\n"
                        + "|Name|Description|Type|Read|Write\n" + "5.1+^e|" )
                .append( description )
                .append( '\n' );
        SortedSet<String> attributeInfo = new TreeSet<>(
                String.CASE_INSENSITIVE_ORDER );
        for ( MBeanAttributeInfo attrInfo : attributes )
        {
            StringBuilder attributeRow = new StringBuilder( 512 );
            String type = getType( attrInfo.getType() );
            Descriptor descriptor = attrInfo.getDescriptor();
            type = getCompositeType( type, descriptor, nonHtml );
            attributeRow.append( '|' )
                    .append( makeBreakable( attrInfo.getName(), nonHtml ) )
                    .append( '|' )
                    .append( attrInfo.getDescription()
                            .replace( '\n', ' ' ) )
                    .append( '|' )
                    .append( type )
                    .append( '|' )
                    .append( attrInfo.isReadable() ? "yes" : "no" )
                    .append( '|' )
                    .append( attrInfo.isWritable() ? "yes" : "no" )
                    .append( '\n' );
            attributeInfo.add( attributeRow.toString() );
        }
        for ( String row : attributeInfo )
        {
            beanInfo.append( row );
        }
        beanInfo.append( "|===\n" );
        beanInfo.append( ENDIF );
    }

    private void writeAttributesTable( String description,
                                       StringBuilder beanInfo, MBeanAttributeInfo[] attributes,
                                       boolean nonHtml )
    {
        addNonHtmlCondition( beanInfo, nonHtml );
        beanInfo.append(
                "[options=\"header\", cols=\"20m,36,20m,7,7\"]\n" + "|===\n"
                        + "|Name|Description|Type|Read|Write\n" + "5.1+^e|" )
                .append( description )
                .append( '\n' );
        SortedSet<String> attributeInfo = new TreeSet<String>(
                String.CASE_INSENSITIVE_ORDER );
        for ( MBeanAttributeInfo attrInfo : attributes )
        {
            StringBuilder attributeRow = new StringBuilder( 512 );
            String type = getType( attrInfo.getType() );
            Descriptor descriptor = attrInfo.getDescriptor();
            type = getCompositeType( type, descriptor, nonHtml );
            attributeRow.append( '|' )
                    .append( makeBreakable( attrInfo.getName(), nonHtml ) )
                    .append( '|' )
                    .append( attrInfo.getDescription()
                            .replace( '\n', ' ' ) )
                    .append( '|' )
                    .append( type )
                    .append( '|' )
                    .append( attrInfo.isReadable() ? "yes" : "no" )
                    .append( '|' )
                    .append( attrInfo.isWritable() ? "yes" : "no" )
                    .append( '\n' );
            attributeInfo.add( attributeRow.toString() );
        }
        for ( String row : attributeInfo )
        {
            beanInfo.append( row );
        }
        beanInfo.append( "|===\n" );
        beanInfo.append( ENDIF );
    }

Replace Generic With Diamond TreeSet<String> with TreeSet<> in method private writeAttributesTable(description String, beanInfo StringBuilder, attributes MBeanAttributeInfo[], nonHtml boolean) : void from class jmx.JmxDocTest


    private long findNode( GraphDatabaseService db, String name )
    {
        try ( Transaction transaction = db.beginTx() )
        {
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
                if ( name.equals( node.getProperty( "name", null ) ) )
                    return node.getId();
            fail( "Didn't find node '" + name + "' in " + db );
            return -1; // will never happen
        }
    }

    private long findNode( GraphDatabaseService db, String name )
    {
        Transaction transaction = db.beginTx();

        try
        {
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
                if ( name.equals( node.getProperty( "name", null ) ) )
                    return node.getId();
            fail( "Didn't find node '" + name + "' in " + db );
            return -1; // will never happen
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method private findNode(db GraphDatabaseService, name String) : long from class org.neo4j.ha.ForeignStoreIdIT


    private long createNode( GraphDatabaseService db, String name )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            node.setProperty( "name", name );
            tx.success();
            return node.getId();
        }
    }

    private long createNode( GraphDatabaseService db, String name )
    {
        Transaction tx = db.beginTx();
        try
        {
            Node node = db.createNode();
            node.setProperty( "name", name );
            tx.success();
            return node.getId();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createNode(db GraphDatabaseService, name String) : long from class org.neo4j.ha.ForeignStoreIdIT


    @Test
    public void testInstanceCanBeReplacedToReestablishQuorum() throws Throwable
    {
        File root = TargetDirectory.forTest( getClass() ).cleanDirectory(
                "testInstanceCanBeReplacedToReestablishQuorum"
        );
        ClusterManager clusterManager = new ClusterManager( clusterOfSize( 3 ), root,
                MapUtil.stringMap( HaSettings.tx_push_factor.name(), "2", HaSettings.state_switch_timeout.name(), "5s" ) );
        clusterManager.start();
        ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();

        HighlyAvailableGraphDatabase master = cluster.getMaster();

        cluster.await( ClusterManager.masterSeesAllSlavesAsAvailable() );

        doTx( master );

        final CountDownLatch latch1 = new CountDownLatch( 1 );
        waitOnHeartbeatFail( master, latch1 );

        HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
        cluster.fail( slave1 );

        latch1.await();
        slave1.shutdown();

        doTx( master );

        final CountDownLatch latch2 = new CountDownLatch( 1 );
        waitOnHeartbeatFail( master, latch2 );

        HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( slave1 );
        cluster.fail( slave2 );

        latch2.await();

        // The master should stop saying that it's master
        assertFalse( master.isMaster() );

        try
        {
            doTx( master );
            fail( "After both slaves fail txs should not go through" );
        }
        catch ( TransactionFailureException e )
        {
            assertEquals( "Timeout waiting for cluster to elect master", e.getMessage() );
        }

        // This is not a hack, this simulates a period of inactivity in the cluster.
        Thread.sleep( 120000 ); // TODO Define "inactivity" and await that condition instead of 120 seconds.

        final CountDownLatch latch3 = new CountDownLatch( 1 );
        final CountDownLatch latch4 = new CountDownLatch( 1 );
        final CountDownLatch latch5 = new CountDownLatch( 1 );
        waitOnHeartbeatAlive( master, latch3 );
        waitOnRoleIsAvailable( master, latch4, HighAvailabilityModeSwitcher.MASTER );
        waitOnRoleIsAvailable( master, latch5, HighAvailabilityModeSwitcher.SLAVE );

        HighlyAvailableGraphDatabase replacement =
                (HighlyAvailableGraphDatabase) new TestHighlyAvailableGraphDatabaseFactory().
                newHighlyAvailableDatabaseBuilder( new File( root, "replacement" ).getAbsolutePath() ).
                setConfig( ClusterSettings.cluster_server, ":5010" ).
                setConfig( HaSettings.ha_server, ":6010" ).
                setConfig( ClusterSettings.server_id, "3" ).
                setConfig( ClusterSettings.initial_hosts, cluster.getInitialHostsConfigString() ).
                setConfig( HaSettings.tx_push_factor, "0" ).
                newGraphDatabase();

        latch3.await();
        latch4.await();
        latch5.await();

        assertTrue( master.isMaster() );
        assertFalse( replacement.isMaster() );

        Node finalNode = doTx( master );

        try (Transaction transaction = replacement.beginTx())
        {
            replacement.getNodeById( finalNode.getId() );
        }

        clusterManager.stop();
        replacement.shutdown();
    }

    @Test
    public void testInstanceCanBeReplacedToReestablishQuorum() throws Throwable
    {
        File root = TargetDirectory.forTest( getClass() ).cleanDirectory(
                "testInstanceCanBeReplacedToReestablishQuorum"
        );
        ClusterManager clusterManager = new ClusterManager( clusterOfSize( 3 ), root,
                MapUtil.stringMap( HaSettings.tx_push_factor.name(), "2", HaSettings.state_switch_timeout.name(), "5s" ) );
        clusterManager.start();
        ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();

        HighlyAvailableGraphDatabase master = cluster.getMaster();

        cluster.await( ClusterManager.masterSeesAllSlavesAsAvailable() );

        doTx( master );

        final CountDownLatch latch1 = new CountDownLatch( 1 );
        waitOnHeartbeatFail( master, latch1 );

        HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
        cluster.fail( slave1 );

        latch1.await();
        slave1.shutdown();

        doTx( master );

        final CountDownLatch latch2 = new CountDownLatch( 1 );
        waitOnHeartbeatFail( master, latch2 );

        HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( slave1 );
        cluster.fail( slave2 );

        latch2.await();

        // The master should stop saying that it's master
        assertFalse( master.isMaster() );

        try
        {
            doTx( master );
            fail( "After both slaves fail txs should not go through" );
        }
        catch ( TransactionFailureException e )
        {
            assertEquals( "Timeout waiting for cluster to elect master", e.getMessage() );
        }

        // This is not a hack, this simulates a period of inactivity in the cluster.
        Thread.sleep( 120000 ); // TODO Define "inactivity" and await that condition instead of 120 seconds.

        final CountDownLatch latch3 = new CountDownLatch( 1 );
        final CountDownLatch latch4 = new CountDownLatch( 1 );
        final CountDownLatch latch5 = new CountDownLatch( 1 );
        waitOnHeartbeatAlive( master, latch3 );
        waitOnRoleIsAvailable( master, latch4, HighAvailabilityModeSwitcher.MASTER );
        waitOnRoleIsAvailable( master, latch5, HighAvailabilityModeSwitcher.SLAVE );

        HighlyAvailableGraphDatabase replacement =
                (HighlyAvailableGraphDatabase) new TestHighlyAvailableGraphDatabaseFactory().
                newHighlyAvailableDatabaseBuilder( new File( root, "replacement" ).getAbsolutePath() ).
                setConfig( ClusterSettings.cluster_server, ":5010" ).
                setConfig( HaSettings.ha_server, ":6010" ).
                setConfig( ClusterSettings.server_id, "3" ).
                setConfig( ClusterSettings.initial_hosts, cluster.getInitialHostsConfigString() ).
                setConfig( HaSettings.tx_push_factor, "0" ).
                newGraphDatabase();

        latch3.await();
        latch4.await();
        latch5.await();

        assertTrue( master.isMaster() );
        assertFalse( replacement.isMaster() );

        Node finalNode = doTx( master );

        Transaction transaction = replacement.beginTx();
        try
        {
            replacement.getNodeById( finalNode.getId() );
        }
        finally
        {
            transaction.finish();
        }

        clusterManager.stop();
        replacement.shutdown();
    }

Try With Resources try(Transaction transaction=replacement.beginTx()) in method public testInstanceCanBeReplacedToReestablishQuorum() : void from class org.neo4j.ha.QuorumWritesIT


    private void createNode( GraphDatabaseService db, String name )
    {
        try ( Transaction tx = db.beginTx() )
        {
            db.createNode();//.setProperty( "name", name );
            tx.success();
        }
    }

    private void createNode( GraphDatabaseService db, String name )
    {
        Transaction tx = db.beginTx();
        try
        {
            db.createNode();//.setProperty( "name", name );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createNode(db GraphDatabaseService, name String) : void from class org.neo4j.ha.TestBranchedData


    private long addNode( int dbId )
    {
        HighlyAvailableGraphDatabase db = dbs[dbId];
        long result = -1;
        try ( Transaction tx = db.beginTx() )
        {
            result = db.createNode().getId();
            tx.success();
        }
        return result;
    }

    private long addNode( int dbId )
    {
        HighlyAvailableGraphDatabase db = dbs[dbId];
        long result = -1;
        Transaction tx = db.beginTx();
        try
        {
            result = db.createNode().getId();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
        return result;
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private addNode(dbId int) : long from class org.neo4j.ha.TestPullUpdatesApplied


    @Test
    public void slaveShouldNotBeAbleToModifyNodeDeletedOnMaster() throws Exception
    {
        // GIVEN
        // -- node created on slave
        HighlyAvailableGraphDatabase aSlave = cluster.getAnySlave();
        Node node = createNode( aSlave );
        // -- that node delete on master, but the slave doesn't see it yet
        deleteNode( cluster.getMaster(), node.getId() );

        // WHEN
        try (Transaction slaveTransaction = aSlave.beginTx())
        {
            node.setProperty( "name", "test" );
            fail( "Shouldn't be able to modify a node deleted on master" );
        }
        catch ( NotFoundException e )
        {
            // THEN
            // -- the transactions gotten back in the response should delete that node
        }
    }

    @Test
    public void slaveShouldNotBeAbleToModifyNodeDeletedOnMaster() throws Exception
    {
        // GIVEN
        // -- node created on slave
        HighlyAvailableGraphDatabase aSlave = cluster.getAnySlave();
        Node node = createNode( aSlave );
        // -- that node delete on master, but the slave doesn't see it yet
        deleteNode( cluster.getMaster(), node.getId() );

        // WHEN
        Transaction tx = aSlave.beginTx();
        try
        {
            node.setProperty( "name", "test" );
            fail( "Shouldn't be able to modify a node deleted on master" );
        }
        catch ( NotFoundException e )
        {
            // THEN
            // -- the transactions gotten back in the response should delete that node
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction slaveTransaction=aSlave.beginTx()) in method public slaveShouldNotBeAbleToModifyNodeDeletedOnMaster() : void from class org.neo4j.ha.TransactionConstraintsIT


    @Ignore( "Known issue where locks acquired from Transaction#acquireXXXLock() methods doesn't get properly released when calling Lock#release() method" )
    @Test
    public void manuallyAcquireAndReleaseTransactionLock() throws Exception
    {
        // GIVEN
        // -- a slave acquiring a lock on an ubiquitous node
        HighlyAvailableGraphDatabase master = cluster.getMaster();
        OtherThreadExecutor<HighlyAvailableGraphDatabase> masterWorker = new OtherThreadExecutor<>( "master worker", master );
        final Node node = createNode( master );
        cluster.sync();
        HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
        try ( Transaction slaveTx = slave.beginTx() )
        {
            Lock lock = slaveTx.acquireWriteLock( slave.getNodeById( node.getId() ) );

            // WHEN
            // -- the lock is manually released (tx still running)
            lock.release();

            // THEN
            // -- that entity should be able to be locked from another member
            Transaction masterTx = masterWorker.execute( new BeginTx() );
            masterWorker.execute( new AcquireWriteLock( masterTx, new Callable<Node>()
            {
                @Override
                public Node call() throws Exception
                {
                    return node;
                }
            } ), 1, SECONDS );
        }
        finally
        {
            masterWorker.close();
        }
    }

    @Ignore( "Known issue where locks acquired from Transaction#acquireXXXLock() methods doesn't get properly released when calling Lock#release() method" )
    @Test
    public void manuallyAcquireAndReleaseTransactionLock() throws Exception
    {
        // GIVEN
        // -- a slave acquiring a lock on an ubiquitous node
        HighlyAvailableGraphDatabase master = cluster.getMaster();
        OtherThreadExecutor<HighlyAvailableGraphDatabase> masterWorker = new OtherThreadExecutor<>( "master worker", master );
        final Node node = createNode( master );
        cluster.sync();
        HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
        Transaction slaveTx = slave.beginTx();
        try
        {
            Lock lock = slaveTx.acquireWriteLock( slave.getNodeById( node.getId() ) );

            // WHEN
            // -- the lock is manually released (tx still running)
            lock.release();

            // THEN
            // -- that entity should be able to be locked from another member
            Transaction masterTx = masterWorker.execute( new BeginTx() );
            masterWorker.execute( new AcquireWriteLock( masterTx, new Callable<Node>()
            {
                @Override
                public Node call() throws Exception
                {
                    return node;
                }
            } ), 1, SECONDS );
        }
        finally
        {
            slaveTx.finish();
            masterWorker.close();
        }
    }

Try With Resources try(Transaction slaveTx=slave.beginTx()) in method public manuallyAcquireAndReleaseTransactionLock() : void from class org.neo4j.ha.TransactionConstraintsIT


    @Test
    public void shouldAllowCreationOfNonConflictingDataOnSeparateHosts() throws Exception
    {
        // given
        ClusterManager.ManagedCluster cluster = startClusterSeededWith(
                databaseWithUniquenessConstraint( "Label1", "key1" ) );

        HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
        HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );

        // when
        Future<Boolean> created;

        try ( Transaction tx = slave1.beginTx() )
        {
            slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );

            created = otherThread.execute( createNode( slave2, "Label1", "key1", "value2" ) );
            tx.success();
        }

        // then
        assertTrue( "creating non-conflicting data should pass", created.get() );
    }

    @Test
    public void shouldAllowCreationOfNonConflictingDataOnSeparateHosts() throws Exception
    {
        // given
        ClusterManager.ManagedCluster cluster = startClusterSeededWith(
                databaseWithUniquenessConstraint( "Label1", "key1" ) );

        HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
        HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );

        // when
        Future<Boolean> created;
        Transaction tx = slave1.beginTx();
        try
        {
            slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );

            created = otherThread.execute( createNode( slave2, "Label1", "key1", "value2" ) );
            tx.success();
        }
        finally
        {
            tx.finish();
        }

        // then
        assertTrue( "creating non-conflicting data should pass", created.get() );
    }

Try With Resources try(Transaction tx=slave1.beginTx()) in method public shouldAllowCreationOfNonConflictingDataOnSeparateHosts() : void from class org.neo4j.ha.UniquenessConstraintValidationHAIT


    @Test
    public void shouldPreventConcurrentCreationOfConflictingDataOnSeparateHosts() throws Exception
    {
        // given
        ClusterManager.ManagedCluster cluster = startClusterSeededWith(
                databaseWithUniquenessConstraint( "Label1", "key1" ) );

        HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
        HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );

        // when
        Future<Boolean> created;
        try ( Transaction tx = slave1.beginTx() )
        {
            slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );

            created = otherThread.execute( createNode( slave2, "Label1", "key1", "value1" ) );

            assertThat( otherThread, isWaiting() );

            tx.success();
        }

        // then
        assertFalse( "creating violating data should fail", created.get() );
    }

    @Test
    public void shouldPreventConcurrentCreationOfConflictingDataOnSeparateHosts() throws Exception
    {
        // given
        ClusterManager.ManagedCluster cluster = startClusterSeededWith(
                databaseWithUniquenessConstraint( "Label1", "key1" ) );

        HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
        HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );

        // when
        Future<Boolean> created;
        Transaction tx = slave1.beginTx();
        try
        {
            slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );

            created = otherThread.execute( createNode( slave2, "Label1", "key1", "value1" ) );

            assertThat( otherThread, isWaiting() );

            tx.success();
        }
        finally
        {
            tx.finish();
        }

        // then
        assertFalse( "creating violating data should fail", created.get() );
    }

Try With Resources try(Transaction tx=slave1.beginTx()) in method public shouldPreventConcurrentCreationOfConflictingDataOnSeparateHosts() : void from class org.neo4j.ha.UniquenessConstraintValidationHAIT


    @Test
    public void shouldPreventConcurrentCreationOfConflictingNonStringPropertyOnMasterAndSlave() throws Exception
    {
        // given
        ClusterManager.ManagedCluster cluster = startClusterSeededWith(
                databaseWithUniquenessConstraint( "Label1", "key1" ) );

        HighlyAvailableGraphDatabase master = cluster.getMaster();
        HighlyAvailableGraphDatabase slave = cluster.getAnySlave();

        // when
        Future<Boolean> created;
        try ( Transaction tx = master.beginTx() )
        {
            master.createNode( label( "Label1" ) ).setProperty( "key1", 0x0099CC );

            created = otherThread.execute( createNode( slave, "Label1", "key1", 0x0099CC ) );

            assertThat( otherThread, isWaiting() );

            tx.success();
        }

        // then
        assertFalse( "creating violating data should fail", created.get() );
    }

    @Test
    public void shouldPreventConcurrentCreationOfConflictingNonStringPropertyOnMasterAndSlave() throws Exception
    {
        // given
        ClusterManager.ManagedCluster cluster = startClusterSeededWith(
                databaseWithUniquenessConstraint( "Label1", "key1" ) );

        HighlyAvailableGraphDatabase master = cluster.getMaster();
        HighlyAvailableGraphDatabase slave = cluster.getAnySlave();

        // when
        Future<Boolean> created;
        Transaction tx = master.beginTx();
        try
        {
            master.createNode( label( "Label1" ) ).setProperty( "key1", 0x0099CC );

            created = otherThread.execute( createNode( slave, "Label1", "key1", 0x0099CC ) );

            assertThat( otherThread, isWaiting() );

            tx.success();
        }
        finally
        {
            tx.finish();
        }

        // then
        assertFalse( "creating violating data should fail", created.get() );
    }

Try With Resources try(Transaction tx=master.beginTx()) in method public shouldPreventConcurrentCreationOfConflictingNonStringPropertyOnMasterAndSlave() : void from class org.neo4j.ha.UniquenessConstraintValidationHAIT


    @Test
    public void shouldAllowOtherHostToCompleteIfFirstHostRollsBackTransaction() throws Exception
    {
        // given
        ClusterManager.ManagedCluster cluster = startClusterSeededWith(
                databaseWithUniquenessConstraint( "Label1", "key1" ) );

        HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
        HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );

        // when
        Future<Boolean> created;

        try ( Transaction tx = slave1.beginTx() )
        {
            slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );

            created = otherThread.execute( createNode( slave2, "Label1", "key1", "value1" ) );

            assertThat( otherThread, isWaiting() );

            tx.failure();
        }

        // then
        assertTrue( "creating data that conflicts only with rolled back data should pass", created.get() );
    }

    @Test
    public void shouldAllowOtherHostToCompleteIfFirstHostRollsBackTransaction() throws Exception
    {
        // given
        ClusterManager.ManagedCluster cluster = startClusterSeededWith(
                databaseWithUniquenessConstraint( "Label1", "key1" ) );

        HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
        HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );

        // when
        Future<Boolean> created;
        Transaction tx = slave1.beginTx();
        try
        {
            slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );

            created = otherThread.execute( createNode( slave2, "Label1", "key1", "value1" ) );

            assertThat( otherThread, isWaiting() );

            tx.failure();
        }
        finally
        {
            tx.finish();
        }

        // then
        assertTrue( "creating data that conflicts only with rolled back data should pass", created.get() );
    }

Try With Resources try(Transaction tx=slave1.beginTx()) in method public shouldAllowOtherHostToCompleteIfFirstHostRollsBackTransaction() : void from class org.neo4j.ha.UniquenessConstraintValidationHAIT


    private File databaseWithUniquenessConstraint( String label, String propertyKey )
    {
        File storeDir = new File( targetDir.directory(), "seed" );
        GraphDatabaseService graphDb = new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir.getAbsolutePath() );
        try
        {
            try ( Transaction tx = graphDb.beginTx() )
            {
                graphDb.schema().constraintFor( label( label ) ).assertPropertyIsUnique( propertyKey ).create();

                tx.success();
            }
        }
        finally
        {
            graphDb.shutdown();
        }
        return storeDir;
    }

    private File databaseWithUniquenessConstraint( String label, String propertyKey )
    {
        File storeDir = new File( targetDir.directory(), "seed" );
        GraphDatabaseService graphDb = new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir.getAbsolutePath() );
        try
        {
            Transaction tx = graphDb.beginTx();
            try
            {
                graphDb.schema().constraintFor( label( label ) ).assertPropertyIsUnique( propertyKey ).create();

                tx.success();
            }
            finally
            {
                tx.finish();
            }
        }
        finally
        {
            graphDb.shutdown();
        }
        return storeDir;
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method private databaseWithUniquenessConstraint(label String, propertyKey String) : File from class org.neo4j.ha.UniquenessConstraintValidationHAIT


    private void commitSmallTx( GraphDatabaseService db )
    {
        try ( Transaction transaction = db.beginTx() )
        {
            db.createNode();
            transaction.success();
        }
    }

    private void commitSmallTx( GraphDatabaseService db )
    {
        Transaction tx = db.beginTx();
        try
        {
            db.createNode();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method private commitSmallTx(db GraphDatabaseService) : void from class org.neo4j.kernel.ha.BiggerThanLogTxIT


                @Override
                public void run()
                {
                    try
                    {
                        barrier.await();
                        dbs[ finalI-1 ] = startDbAtBase( finalI, initialHosts );
                    }
                    catch ( InterruptedException | BrokenBarrierException e )
                    {
                        throw new RuntimeException( e );
                    }
                }

                @Override
                public void run()
                {
                    try
                    {
                        barrier.await();
                        dbs[ finalI-1 ] = startDbAtBase( finalI, initialHosts );
                    }
                    catch ( InterruptedException e )
                    {
                        throw new RuntimeException( e );
                    }
                    catch ( BrokenBarrierException e )
                    {
                        throw new RuntimeException( e );
                    }
                }

Merge Catch [catch(InterruptedException e), catch(BrokenBarrierException e)] to catch(InterruptedException|BrokenBarrierException e) in method public run() : void from class org.neo4j.kernel.ha.ConcurrentInstanceStartupIT.concurrentStartupShouldWork.t.new Thread.new Runnable


    private long getNamedNode( HighlyAvailableGraphDatabase db, String name )
    {
        try ( Transaction transaction = db.beginTx() )
        {
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
            {
                if ( name.equals( node.getProperty( "name", null ) ) )
                {
                    return node.getId();
                }
            }
            fail( "Couldn't find named node '" + name + "' at " + db );
            // The lone above will prevent this return from happening
            return -1;
        }
    }

    private long getNamedNode( HighlyAvailableGraphDatabase db, String name )
    {
        Transaction transaction = db.beginTx();
        try
        {
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
            {
                if ( name.equals( node.getProperty( "name", null ) ) )
                {
                    return node.getId();
                }
            }
            fail( "Couldn't find named node '" + name + "' at " + db );
            // The lone above will prevent this return from happening
            return -1;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method private getNamedNode(db HighlyAvailableGraphDatabase, name String) : long from class org.neo4j.kernel.ha.HardKillIT


    private long createNamedNode( HighlyAvailableGraphDatabase db, String name )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            node.setProperty( "name", name );
            tx.success();
            return node.getId();
        }
    }

    private long createNamedNode( HighlyAvailableGraphDatabase db, String name )
    {
        Transaction tx = db.beginTx();
        try
        {
            Node node = db.createNode();
            node.setProperty( "name", name );
            tx.success();
            return node.getId();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createNamedNode(db HighlyAvailableGraphDatabase, name String) : long from class org.neo4j.kernel.ha.HardKillIT


    @Test
    public void transactionsGetsPushedToSlaves() throws Throwable
    {
        // given
        clusterManager = new ClusterManager( clusterOfSize( 3 ), DIR.cleanDirectory( "dbs" ),
                stringMap( tx_push_factor.name(), "2" ) );
        clusterManager.start();
        ManagedCluster cluster = clusterManager.getDefaultCluster();

        // when
        String name = "a node";
        long node = createNode( cluster.getMaster(), name );

        // then
        for ( HighlyAvailableGraphDatabase db : cluster.getAllMembers() ) {
            try (Transaction transaction = db.beginTx())
            {
                assertEquals( node, getNodeByName( db, name ) );
            }
        }
    }

    @Test
    public void transactionsGetsPushedToSlaves() throws Throwable
    {
        // given
        clusterManager = new ClusterManager( clusterOfSize( 3 ), DIR.cleanDirectory( "dbs" ),
                stringMap( tx_push_factor.name(), "2" ) );
        clusterManager.start();
        ManagedCluster cluster = clusterManager.getDefaultCluster();

        // when
        String name = "a node";
        long node = createNode( cluster.getMaster(), name );

        // then
        for ( HighlyAvailableGraphDatabase db : cluster.getAllMembers() ) {
            Transaction transaction = db.beginTx();
            try
            {
                assertEquals( node, getNodeByName( db, name ) );
            }
            finally
            {
                transaction.finish();
            }
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method public transactionsGetsPushedToSlaves() : void from class org.neo4j.kernel.ha.cluster.member.HighAvailabilitySlavesIT


    private long createNode( HighlyAvailableGraphDatabase db, String name )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            node.setProperty( "name", name );
            tx.success();
            return node.getId();
        }
    }

    private long createNode( HighlyAvailableGraphDatabase db, String name )
    {
        Transaction tx = db.beginTx();
        try
        {
            Node node = db.createNode();
            node.setProperty( "name", name );
            tx.success();
            return node.getId();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createNode(db HighlyAvailableGraphDatabase, name String) : long from class org.neo4j.kernel.ha.cluster.member.HighAvailabilitySlavesIT