    @Description( "Query the given fulltext index. Returns the matching relationships and their lucene query score, ordered by score." )
    @Procedure( name = "db.index.fulltext.queryRelationships", mode = READ )
    public Stream<RelationshipOutput> queryFulltextForRelationships( @Name( "indexName" ) String name, @Name( "queryString" ) String query ) throws Exception
    {
        IndexReference indexReference = getValidIndexReference( name );
        awaitOnline( indexReference );
        EntityType entityType = indexReference.schema().entityType();
        if ( entityType != EntityType.RELATIONSHIP )
        {
            throw new IllegalArgumentException( "The '" + name + "' index (" + indexReference + ") is an index on " + entityType +
                    ", so it cannot be queried for relationships." );
        }
        RelationshipIndexCursor cursor = tx.cursors().allocateRelationshipIndexCursor();
        tx.dataRead().relationshipIndexSeek( indexReference, cursor, IndexQuery.fulltextSearch( query ) );

        Spliterator<RelationshipOutput> spliterator = new SpliteratorAdaptor<>()
        {
            @Override
            public boolean tryAdvance( Consumer<? super RelationshipOutput> action )
            {
                while ( cursor.next() )
                {
                    long relationshipReference = cursor.relationshipReference();
                    float score = cursor.score();
                    RelationshipOutput relationshipOutput = RelationshipOutput.forExistingEntityOrNull( db, relationshipReference, score );
                    if ( relationshipOutput != null )
                    {
                        action.accept( relationshipOutput );
                        return true;
                    }
                }
                cursor.close();
                return false;
            }
        };
        return StreamSupport.stream( spliterator, false ).onClose( cursor::close );
    }

    @Description( "Query the given fulltext index. Returns the matching relationships and their lucene query score, ordered by score." )
    @Procedure( name = "db.index.fulltext.queryRelationships", mode = READ )
    public Stream<RelationshipOutput> queryFulltextForRelationships( @Name( "indexName" ) String name, @Name( "queryString" ) String query ) throws Exception
    {
        IndexReference indexReference = getValidIndexReference( name );
        awaitOnline( indexReference );
        EntityType entityType = indexReference.schema().entityType();
        if ( entityType != EntityType.RELATIONSHIP )
        {
            throw new IllegalArgumentException( "The '" + name + "' index (" + indexReference + ") is an index on " + entityType +
                    ", so it cannot be queried for relationships." );
        }
        RelationshipIndexCursor cursor = tx.cursors().allocateRelationshipIndexCursor();
        tx.dataRead().relationshipIndexSeek( indexReference, cursor, IndexQuery.fulltextSearch( query ) );

        Spliterator<RelationshipOutput> spliterator = new SpliteratorAdaptor<RelationshipOutput>()
        {
            @Override
            public boolean tryAdvance( Consumer<? super RelationshipOutput> action )
            {
                while ( cursor.next() )
                {
                    long relationshipReference = cursor.relationshipReference();
                    float score = cursor.score();
                    RelationshipOutput relationshipOutput = RelationshipOutput.forExistingEntityOrNull( db, relationshipReference, score );
                    if ( relationshipOutput != null )
                    {
                        action.accept( relationshipOutput );
                        return true;
                    }
                }
                cursor.close();
                return false;
            }
        };
        return StreamSupport.stream( spliterator, false ).onClose( cursor::close );
    }

Replace Generic With Diamond SpliteratorAdaptor<RelationshipOutput> with SpliteratorAdaptor<> in method public queryFulltextForRelationships(name String, query String) : Stream<RelationshipOutput> from class org.neo4j.kernel.api.impl.fulltext.FulltextProcedures


    @SuppressWarnings( {"unchecked", "SameParameterValue"} )
    private Matcher<AnyValue[]> proc( String procName, String procSignature, Matcher<String> description, String mode )
    {
        Matcher<AnyValue> desc = new TypeSafeMatcher<>()
        {
            @Override
            public void describeTo( Description description )
            {
                description.appendText( "invalid description" );
            }

            @Override
            protected boolean matchesSafely( AnyValue item )
            {
                return item instanceof TextValue && description.matches( ((TextValue) item).stringValue() );
            }
        };

        Matcher<AnyValue>[] matchers =
                new Matcher[]{equalTo( stringValue( procName )), equalTo( stringValue( procName + procSignature  ) ), desc, equalTo( stringValue( mode ) )};
        return arrayContaining( matchers );
    }

    @SuppressWarnings( {"unchecked", "SameParameterValue"} )
    private Matcher<AnyValue[]> proc( String procName, String procSignature, Matcher<String> description, String mode )
    {
        Matcher<AnyValue> desc = new TypeSafeMatcher<AnyValue>()
        {
            @Override
            public void describeTo( Description description )
            {
                description.appendText( "invalid description" );
            }

            @Override
            protected boolean matchesSafely( AnyValue item )
            {
                return item instanceof TextValue && description.matches( ((TextValue) item).stringValue() );
            }
        };

        Matcher<AnyValue>[] matchers =
                new Matcher[]{equalTo( stringValue( procName )), equalTo( stringValue( procName + procSignature  ) ), desc, equalTo( stringValue( mode ) )};
        return arrayContaining( matchers );
    }

Replace Generic With Diamond TypeSafeMatcher<AnyValue> with TypeSafeMatcher<> in method private proc(procName String, procSignature String, description Matcher<String>, mode String) : Matcher<AnyValue[]> from class org.neo4j.kernel.impl.api.integrationtest.BuiltInProceduresIT


    private static Matcher<File> isExistingDatabase()
    {
        return new BaseMatcher<>()
        {
            @Override
            public boolean matches( final Object item )
            {
                final File store = (File) item;
                try
                {
                    Validators.CONTAINS_EXISTING_DATABASE.validate( store );
                    return true;
                }
                catch ( Exception e )
                {
                    return false;
                }
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "an existing database." );
            }

            @Override
            public void describeMismatch( final Object item, final Description description )
            {
                description.appendValue( item ).appendText( " is not an existing database." );
            }
        };
    }

    private static Matcher<File> isExistingDatabase()
    {
        return new BaseMatcher<File>()
        {
            @Override
            public boolean matches( final Object item )
            {
                final File store = (File) item;
                try
                {
                    Validators.CONTAINS_EXISTING_DATABASE.validate( store );
                    return true;
                }
                catch ( Exception e )
                {
                    return false;
                }
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "an existing database." );
            }

            @Override
            public void describeMismatch( final Object item, final Description description )
            {
                description.appendValue( item ).appendText( " is not an existing database." );
            }
        };
    }

Replace Generic With Diamond BaseMatcher<File> with BaseMatcher<> in method private isExistingDatabase() : Matcher<File> from class org.neo4j.commandline.dbms.DatabaseImporterTest


    @Override
    public ResourceIterable<Node> getAllNodes()
    {
        KernelTransaction ktx = statementContext.getKernelTransactionBoundToThisThread( true );
        assertTransactionOpen( ktx );
        return () ->
        {
            Statement statement = ktx.acquireStatement();
            NodeCursor cursor = ktx.cursors().allocateNodeCursor();
            ktx.dataRead().allNodesScan( cursor );
            return new PrefetchingResourceIterator<>()
            {
                @Override
                protected Node fetchNextOrNull()
                {
                    if ( cursor.next() )
                    {
                        return newNodeProxy( cursor.nodeReference() );
                    }
                    else
                    {
                        close();
                        return null;
                    }
                }

                @Override
                public void close()
                {
                    cursor.close();
                    statement.close();
                }
            };
        };
    }

    @Override
    public ResourceIterable<Node> getAllNodes()
    {
        KernelTransaction ktx = statementContext.getKernelTransactionBoundToThisThread( true );
        assertTransactionOpen( ktx );
        return () ->
        {
            Statement statement = ktx.acquireStatement();
            NodeCursor cursor = ktx.cursors().allocateNodeCursor();
            ktx.dataRead().allNodesScan( cursor );
            return new PrefetchingResourceIterator<Node>()
            {
                @Override
                protected Node fetchNextOrNull()
                {
                    if ( cursor.next() )
                    {
                        return newNodeProxy( cursor.nodeReference() );
                    }
                    else
                    {
                        close();
                        return null;
                    }
                }

                @Override
                public void close()
                {
                    cursor.close();
                    statement.close();
                }
            };
        };
    }

Replace Generic With Diamond PrefetchingResourceIterator<Node> with PrefetchingResourceIterator<> in method public getAllNodes() : ResourceIterable<Node> from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    @Override
    public ResourceIterable<Relationship> getAllRelationships()
    {
        KernelTransaction ktx = statementContext.getKernelTransactionBoundToThisThread( true );
        assertTransactionOpen( ktx );
        return () ->
        {
            Statement statement = ktx.acquireStatement();
            RelationshipScanCursor cursor = ktx.cursors().allocateRelationshipScanCursor();
            ktx.dataRead().allRelationshipsScan( cursor );
            return new PrefetchingResourceIterator<>()
            {
                @Override
                protected Relationship fetchNextOrNull()
                {
                    if ( cursor.next() )
                    {
                        return newRelationshipProxy( cursor.relationshipReference(), cursor.sourceNodeReference(), cursor.type(),
                                cursor.targetNodeReference() );
                    }
                    else
                    {
                        close();
                        return null;
                    }
                }

                @Override
                public void close()
                {
                    cursor.close();
                    statement.close();
                }
            };
        };
    }

    @Override
    public ResourceIterable<Relationship> getAllRelationships()
    {
        KernelTransaction ktx = statementContext.getKernelTransactionBoundToThisThread( true );
        assertTransactionOpen( ktx );
        return () ->
        {
            Statement statement = ktx.acquireStatement();
            RelationshipScanCursor cursor = ktx.cursors().allocateRelationshipScanCursor();
            ktx.dataRead().allRelationshipsScan( cursor );
            return new PrefetchingResourceIterator<Relationship>()
            {
                @Override
                protected Relationship fetchNextOrNull()
                {
                    if ( cursor.next() )
                    {
                        return newRelationshipProxy(
                                cursor.relationshipReference(),
                                cursor.sourceNodeReference(),
                                cursor.type(),
                                cursor.targetNodeReference() );
                    }
                    else
                    {
                        close();
                        return null;
                    }
                }

                @Override
                public void close()
                {
                    cursor.close();
                    statement.close();
                }
            };
        };
    }

Replace Generic With Diamond PrefetchingResourceIterator<Relationship> with PrefetchingResourceIterator<> in method public getAllRelationships() : ResourceIterable<Relationship> from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    private static Iterator<ExtensionFactory<?>> getExtensions( Iterator<ExtensionFactory> parent )
    {
        return new Iterator<>()
        {
            @Override
            public boolean hasNext()
            {
                return parent.hasNext();
            }

            @Override
            public ExtensionFactory<?> next()
            {
                return parent.next();
            }
        };
    }

    private static Iterator<ExtensionFactory<?>> getExtensions( Iterator<ExtensionFactory> parent )
    {
        return new Iterator<ExtensionFactory<?>>()
        {
            @Override
            public boolean hasNext()
            {
                return parent.hasNext();
            }

            @Override
            public ExtensionFactory<?> next()
            {
                return parent.next();
            }
        };
    }

Replace Generic With Diamond Iterator<ExtensionFactory<?>> with Iterator<> in method private getExtensions(parent Iterator<ExtensionFactory>) : Iterator<ExtensionFactory<?>> from class org.neo4j.graphdb.facade.GraphDatabaseDependencies


    @Test
    public void modifiedPropertyCanByFurtherModifiedInBeforeCommit()
    {
        // Given
        // -- create node and set property on it in one transaction
        DatabaseManagementService managementService = dbRule.getManagementService();
        GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
        final String key = "key";
        final Object value1 = "the old value";
        final Object value2 = "the new value";
        final Node node;
        try ( Transaction tx = db.beginTx() )
        {
            node = db.createNode();
            node.setProperty( key, "initial value" );
            tx.success();
        }
        // -- register a tx listener which will override a property
        TransactionEventListener<Void> listener = new TransactionEventListenerAdapter<>()
        {
            @Override
            public Void beforeCommit( TransactionData data, GraphDatabaseService databaseService )
            {
                Node modifiedNode = data.assignedNodeProperties().iterator().next().entity();
                assertEquals( node, modifiedNode );
                modifiedNode.setProperty( key, value2 );
                return null;
            }
        };
        managementService.registerTransactionEventListener( DEFAULT_DATABASE_NAME, listener );

        try ( Transaction tx = db.beginTx() )
        {
            // When
            node.setProperty( key, value1 );
            tx.success();
        }
        // Then
        assertThat(node, inTx(db, hasProperty(key).withValue(value2)));
        managementService.unregisterTransactionEventListener( DEFAULT_DATABASE_NAME, listener );
    }

    @Test
    public void modifiedPropertyCanByFurtherModifiedInBeforeCommit()
    {
        // Given
        // -- create node and set property on it in one transaction
        DatabaseManagementService managementService = dbRule.getManagementService();
        GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
        final String key = "key";
        final Object value1 = "the old value";
        final Object value2 = "the new value";
        final Node node;
        try ( Transaction tx = db.beginTx() )
        {
            node = db.createNode();
            node.setProperty( key, "initial value" );
            tx.success();
        }
        // -- register a tx listener which will override a property
        TransactionEventListener<Void> listener = new TransactionEventListenerAdapter<Void>()
        {
            @Override
            public Void beforeCommit( TransactionData data, GraphDatabaseService databaseService )
            {
                Node modifiedNode = data.assignedNodeProperties().iterator().next().entity();
                assertEquals( node, modifiedNode );
                modifiedNode.setProperty( key, value2 );
                return null;
            }
        };
        managementService.registerTransactionEventListener( DEFAULT_DATABASE_NAME, listener );

        try ( Transaction tx = db.beginTx() )
        {
            // When
            node.setProperty( key, value1 );
            tx.success();
        }
        // Then
        assertThat(node, inTx(db, hasProperty(key).withValue(value2)));
        managementService.unregisterTransactionEventListener( DEFAULT_DATABASE_NAME, listener );
    }

Replace Generic With Diamond TransactionEventListenerAdapter<Void> with TransactionEventListenerAdapter<> in method public modifiedPropertyCanByFurtherModifiedInBeforeCommit() : void from class org.neo4j.kernel.impl.event.TestTransactionEvents


    @Test
    public void nodeCanBecomeSchemaIndexableInBeforeCommitByAddingProperty()
    {
        // Given we have a schema index...
        DatabaseManagementService managementService = dbRule.getManagementService();
        GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
        Label label = label( "Label" );
        try ( Transaction tx = db.beginTx() )
        {
            db.schema().indexFor( label ).on( "indexed" ).create();
            tx.success();
        }

        // ... and a transaction event listener that likes to add the indexed property on nodes
        managementService.registerTransactionEventListener( DEFAULT_DATABASE_NAME, new TransactionEventListenerAdapter<>()
        {
            @Override
            public Object beforeCommit( TransactionData data, GraphDatabaseService databaseService )
            {
                Iterator<Node> nodes = data.createdNodes().iterator();
                if ( nodes.hasNext() )
                {
                    Node node = nodes.next();
                    node.setProperty( "indexed", "value" );
                }
                return null;
            }
        } );

        // When we create a node with the right label, but not the right property...
        try ( Transaction tx = db.beginTx() )
        {
            db.schema().awaitIndexesOnline( AWAIT_INDEX_DURATION, AWAIT_INDEX_UNIT );
            Node node = db.createNode( label );
            node.setProperty( "random", 42 );
            tx.success();
        }

        // Then we should be able to look it up through the index.
        try ( Transaction ignore = db.beginTx() )
        {
            Node node = db.findNode( label, "indexed", "value" );
            assertThat( node.getProperty( "random" ), is( 42 ) );
        }
    }

    @Test
    public void nodeCanBecomeSchemaIndexableInBeforeCommitByAddingProperty()
    {
        // Given we have a schema index...
        DatabaseManagementService managementService = dbRule.getManagementService();
        GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
        Label label = label( "Label" );
        try ( Transaction tx = db.beginTx() )
        {
            db.schema().indexFor( label ).on( "indexed" ).create();
            tx.success();
        }

        // ... and a transaction event listener that likes to add the indexed property on nodes
        managementService.registerTransactionEventListener( DEFAULT_DATABASE_NAME, new TransactionEventListenerAdapter<Object>()
        {
            @Override
            public Object beforeCommit( TransactionData data, GraphDatabaseService databaseService )
            {
                Iterator<Node> nodes = data.createdNodes().iterator();
                if ( nodes.hasNext() )
                {
                    Node node = nodes.next();
                    node.setProperty( "indexed", "value" );
                }
                return null;
            }
        } );

        // When we create a node with the right label, but not the right property...
        try ( Transaction tx = db.beginTx() )
        {
            db.schema().awaitIndexesOnline( AWAIT_INDEX_DURATION, AWAIT_INDEX_UNIT );
            Node node = db.createNode( label );
            node.setProperty( "random", 42 );
            tx.success();
        }

        // Then we should be able to look it up through the index.
        try ( Transaction ignore = db.beginTx() )
        {
            Node node = db.findNode( label, "indexed", "value" );
            assertThat( node.getProperty( "random" ), is( 42 ) );
        }
    }

Replace Generic With Diamond TransactionEventListenerAdapter<Object> with TransactionEventListenerAdapter<> in method public nodeCanBecomeSchemaIndexableInBeforeCommitByAddingProperty() : void from class org.neo4j.kernel.impl.event.TestTransactionEvents


    @Test
    public void nodeCanBecomeSchemaIndexableInBeforeCommitByAddingLabel()
    {
        // Given we have a schema index...
        DatabaseManagementService managementService = dbRule.getManagementService();
        GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
        final Label label = label( "Label" );
        try ( Transaction tx = db.beginTx() )
        {
            db.schema().indexFor( label ).on( "indexed" ).create();
            tx.success();
        }

        // ... and a transaction event listener that likes to add the indexed property on nodes
        managementService.registerTransactionEventListener( DEFAULT_DATABASE_NAME, new TransactionEventListenerAdapter<>()
        {
            @Override
            public Object beforeCommit( TransactionData data, GraphDatabaseService databaseService )
            {
                Iterator<Node> nodes = data.createdNodes().iterator();
                if ( nodes.hasNext() )
                {
                    Node node = nodes.next();
                    node.addLabel( label );
                }
                return null;
            }
        } );

        // When we create a node with the right property, but not the right label...
        try ( Transaction tx = db.beginTx() )
        {
            db.schema().awaitIndexesOnline( AWAIT_INDEX_DURATION, AWAIT_INDEX_UNIT );
            Node node = db.createNode();
            node.setProperty( "indexed", "value" );
            node.setProperty( "random", 42 );
            tx.success();
        }

        // Then we should be able to look it up through the index.
        try ( Transaction ignore = db.beginTx() )
        {
            Node node = db.findNode( label, "indexed", "value" );
            assertThat( node.getProperty( "random" ), is( 42 ) );
        }
    }

    @Test
    public void nodeCanBecomeSchemaIndexableInBeforeCommitByAddingLabel()
    {
        // Given we have a schema index...
        DatabaseManagementService managementService = dbRule.getManagementService();
        GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
        final Label label = label( "Label" );
        try ( Transaction tx = db.beginTx() )
        {
            db.schema().indexFor( label ).on( "indexed" ).create();
            tx.success();
        }

        // ... and a transaction event listener that likes to add the indexed property on nodes
        managementService.registerTransactionEventListener( DEFAULT_DATABASE_NAME, new TransactionEventListenerAdapter<Object>()
        {
            @Override
            public Object beforeCommit( TransactionData data, GraphDatabaseService databaseService )
            {
                Iterator<Node> nodes = data.createdNodes().iterator();
                if ( nodes.hasNext() )
                {
                    Node node = nodes.next();
                    node.addLabel( label );
                }
                return null;
            }
        } );

        // When we create a node with the right property, but not the right label...
        try ( Transaction tx = db.beginTx() )
        {
            db.schema().awaitIndexesOnline( AWAIT_INDEX_DURATION, AWAIT_INDEX_UNIT );
            Node node = db.createNode();
            node.setProperty( "indexed", "value" );
            node.setProperty( "random", 42 );
            tx.success();
        }

        // Then we should be able to look it up through the index.
        try ( Transaction ignore = db.beginTx() )
        {
            Node node = db.findNode( label, "indexed", "value" );
            assertThat( node.getProperty( "random" ), is( 42 ) );
        }
    }

Replace Generic With Diamond TransactionEventListenerAdapter<Object> with TransactionEventListenerAdapter<> in method public nodeCanBecomeSchemaIndexableInBeforeCommitByAddingLabel() : void from class org.neo4j.kernel.impl.event.TestTransactionEvents


    @Test
    public void shouldAccessRelationshipDataInAfterCommit()
    {
        // GIVEN
        DatabaseManagementService managementService = dbRule.getManagementService();
        final GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
        final AtomicInteger accessCount = new AtomicInteger();
        final Map<Long,RelationshipData> expectedRelationshipData = new HashMap<>();
        TransactionEventListener<Void> listener = new TransactionEventListenerAdapter<>()
        {
            @Override
            public void afterCommit( TransactionData data, Void state, GraphDatabaseService databaseService )
            {
                accessCount.set( 0 );
                try ( Transaction tx = db.beginTx() )
                {
                    for ( Relationship relationship : data.createdRelationships() )
                    {
                        accessData( relationship );
                    }
                    for ( PropertyEntry<Relationship> change : data.assignedRelationshipProperties() )
                    {
                        accessData( change.entity() );
                    }
                    for ( PropertyEntry<Relationship> change : data.removedRelationshipProperties() )
                    {
                        accessData( change.entity() );
                    }
                    tx.success();
                }
            }

            private void accessData( Relationship relationship )
            {
                accessCount.incrementAndGet();
                RelationshipData expectancy = expectedRelationshipData.get( relationship.getId() );
                assertNotNull( expectancy );
                assertEquals( expectancy.startNode, relationship.getStartNode() );
                assertEquals( expectancy.type, relationship.getType().name() );
                assertEquals( expectancy.endNode, relationship.getEndNode() );
            }
        };
        managementService.registerTransactionEventListener( DEFAULT_DATABASE_NAME, listener );

        // WHEN
        try
        {
            Relationship relationship;
            try ( Transaction tx = db.beginTx() )
            {
                relationship = db.createNode().createRelationshipTo( db.createNode(), MyRelTypes.TEST );
                expectedRelationshipData.put( relationship.getId(), new RelationshipData( relationship ) );
                tx.success();
            }
            // THEN
            assertEquals( 1, accessCount.get() );

            // and WHEN
            try ( Transaction tx = db.beginTx() )
            {
                relationship.setProperty( "name", "Smith" );
                Relationship otherRelationship =
                        db.createNode().createRelationshipTo( db.createNode(), MyRelTypes.TEST2 );
                expectedRelationshipData.put( otherRelationship.getId(), new RelationshipData( otherRelationship ) );
                tx.success();
            }
            // THEN
            assertEquals( 2, accessCount.get() );

            // and WHEN
            try ( Transaction tx = db.beginTx() )
            {
                relationship.delete();
                tx.success();
            }
            // THEN
            assertEquals( 1, accessCount.get() );
        }
        finally
        {
            managementService.unregisterTransactionEventListener( DEFAULT_DATABASE_NAME, listener );
        }
    }

    @Test
    public void shouldAccessRelationshipDataInAfterCommit()
    {
        // GIVEN
        final GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
        final AtomicInteger accessCount = new AtomicInteger();
        final Map<Long,RelationshipData> expectedRelationshipData = new HashMap<>();
        TransactionEventHandler<Void> handler = new TransactionEventHandler.Adapter<Void>()
        {
            @Override
            public void afterCommit( TransactionData data, Void state )
            {
                accessCount.set( 0 );
                try ( Transaction tx = db.beginTx() )
                {
                    for ( Relationship relationship : data.createdRelationships() )
                    {
                        accessData( relationship );
                    }
                    for ( PropertyEntry<Relationship> change : data.assignedRelationshipProperties() )
                    {
                        accessData( change.entity() );
                    }
                    for ( PropertyEntry<Relationship> change : data.removedRelationshipProperties() )
                    {
                        accessData( change.entity() );
                    }
                    tx.success();
                }
            }

            private void accessData( Relationship relationship )
            {
                accessCount.incrementAndGet();
                RelationshipData expectancy = expectedRelationshipData.get( relationship.getId() );
                assertNotNull( expectancy );
                assertEquals( expectancy.startNode, relationship.getStartNode() );
                assertEquals( expectancy.type, relationship.getType().name() );
                assertEquals( expectancy.endNode, relationship.getEndNode() );
            }
        };
        db.registerTransactionEventHandler( handler );

        // WHEN
        try
        {
            Relationship relationship;
            try ( Transaction tx = db.beginTx() )
            {
                relationship = db.createNode().createRelationshipTo( db.createNode(), MyRelTypes.TEST );
                expectedRelationshipData.put( relationship.getId(), new RelationshipData( relationship ) );
                tx.success();
            }
            // THEN
            assertEquals( 1, accessCount.get() );

            // and WHEN
            try ( Transaction tx = db.beginTx() )
            {
                relationship.setProperty( "name", "Smith" );
                Relationship otherRelationship =
                        db.createNode().createRelationshipTo( db.createNode(), MyRelTypes.TEST2 );
                expectedRelationshipData.put( otherRelationship.getId(), new RelationshipData( otherRelationship ) );
                tx.success();
            }
            // THEN
            assertEquals( 2, accessCount.get() );

            // and WHEN
            try ( Transaction tx = db.beginTx() )
            {
                relationship.delete();
                tx.success();
            }
            // THEN
            assertEquals( 1, accessCount.get() );
        }
        finally
        {
            db.unregisterTransactionEventHandler( handler );
        }
    }

Replace Generic With Diamond TransactionEventHandler.Adapter<Void> with TransactionEventListenerAdapter<> in method public shouldAccessRelationshipDataInAfterCommit() : void from class org.neo4j.kernel.impl.event.TestTransactionEvents


    private static TransactionEventListenerAdapter<Object> getBeforeCommitListener( Consumer<TransactionData> dataConsumer )
    {
        return new TransactionEventListenerAdapter<>()
        {
            @Override
            public Object beforeCommit( TransactionData data, GraphDatabaseService databaseService ) throws Exception
            {
                dataConsumer.accept( data );
                return super.beforeCommit( data, databaseService );
            }
        };
    }

    private TransactionEventHandler.Adapter<Object> getBeforeCommitHandler( Consumer<TransactionData> dataConsumer )
    {
        return new TransactionEventHandler.Adapter<Object>()
        {
            @Override
            public Object beforeCommit( TransactionData data ) throws Exception
            {
                dataConsumer.accept( data );
                return super.beforeCommit( data );
            }
        };
    }

Replace Generic With Diamond TransactionEventHandler.Adapter<Object> with TransactionEventListenerAdapter<> in method private getBeforeCommitListener(dataConsumer Consumer<TransactionData>) : TransactionEventListenerAdapter<Object> from class org.neo4j.kernel.impl.event.TransactionEventsIT


        Seeker<LabelScanKey,LabelScanValue> cursor()
        {
            return new Seeker<>()
            {
                int cursor = -1;

                @Override
                public Hit<LabelScanKey,LabelScanValue> get()
                {
                    assert cursor >= 0;
                    Pair<LabelScanKey,LabelScanValue> entry = entries.get( cursor );
                    return new MutableHit<>( entry.first(), entry.other() );
                }

                @Override
                public LabelScanKey key()
                {
                    return get().key();
                }

                @Override
                public LabelScanValue value()
                {
                    return get().value();
                }

                @Override
                public boolean next()
                {
                    if ( cursor + 1 >= entries.size() )
                    {
                        return false;
                    }
                    cursor++;
                    return true;
                }

                @Override
                public void close()
                {   // Nothing to close
                }
            };
        }

        RawCursor<Hit<LabelScanKey,LabelScanValue>,IOException> cursor()
        {
            return new RawCursor<Hit<LabelScanKey,LabelScanValue>,IOException>()
            {
                int cursor = -1;

                @Override
                public Hit<LabelScanKey,LabelScanValue> get()
                {
                    assert cursor >= 0;
                    Pair<LabelScanKey,LabelScanValue> entry = entries.get( cursor );
                    return new MutableHit<>( entry.first(), entry.other() );
                }

                @Override
                public boolean next()
                {
                    if ( cursor + 1 >= entries.size() )
                    {
                        return false;
                    }
                    cursor++;
                    return true;
                }

                @Override
                public void close()
                {   // Nothing to close
                }
            };
        }

Replace Generic With Diamond RawCursor<Hit<LabelScanKey,LabelScanValue>,IOException> with Seeker<> in method package cursor() : Seeker<LabelScanKey,LabelScanValue> from class org.neo4j.internal.index.label.NativeAllEntriesLabelScanReaderTest.Labels


    private static Matcher<Long> isIntPair( int left, int right )
    {
        return new BaseMatcher<>()
        {
            @Override
            public void describeTo( Description description )
            {
                description.appendValue( left );
                description.appendValue( right );
            }

            @Override
            public boolean matches( Object o )
            {
                return o instanceof Long && ((Long) o) == (((long) left << 32) | right);
            }
        };
    }

    private Matcher<Long> isIntPair( int left, int right )
    {
        return new BaseMatcher<Long>()
        {
            @Override
            public void describeTo( Description description )
            {
                description.appendValue( left );
                description.appendValue( right );
            }

            @Override
            public boolean matches( Object o )
            {
                return o instanceof Long && ((Long) o) == (((long) left << 32) | right);
            }
        };
    }

Replace Generic With Diamond BaseMatcher<Long> with BaseMatcher<> in method private isIntPair(left int, right int) : Matcher<Long> from class org.neo4j.collection.PrimitiveArraysTest


    private static InputIterator legacyRelationshipsAsInput( NeoStores legacyStore, boolean requiresPropertyMigration )
    {
        return new StoreScanAsInputIterator<>( legacyStore.getRelationshipStore() )
        {
            @Override
            public InputChunk newChunk()
            {
                return new RelationshipRecordChunk( new RecordStorageReader( legacyStore ), requiresPropertyMigration );
            }
        };
    }

    private static InputIterator legacyRelationshipsAsInput( NeoStores legacyStore, boolean requiresPropertyMigration )
    {
        return new StoreScanAsInputIterator<RelationshipRecord>( legacyStore.getRelationshipStore() )
        {
            @Override
            public InputChunk newChunk()
            {
                return new RelationshipRecordChunk( new RecordStorageReader( legacyStore ), requiresPropertyMigration );
            }
        };
    }

Replace Generic With Diamond StoreScanAsInputIterator<RelationshipRecord> with StoreScanAsInputIterator<> in method private legacyRelationshipsAsInput(legacyStore NeoStores, requiresPropertyMigration boolean) : InputIterator from class org.neo4j.kernel.impl.storemigration.RecordStorageMigrator


    private static InputIterator legacyNodesAsInput( NeoStores legacyStore, boolean requiresPropertyMigration )
    {
        return new StoreScanAsInputIterator<>( legacyStore.getNodeStore() )
        {
            @Override
            public InputChunk newChunk()
            {
                return new NodeRecordChunk( new RecordStorageReader( legacyStore ), requiresPropertyMigration );
            }
        };
    }

    private static InputIterator legacyNodesAsInput( NeoStores legacyStore, boolean requiresPropertyMigration )
    {
        return new StoreScanAsInputIterator<NodeRecord>( legacyStore.getNodeStore() )
        {
            @Override
            public InputChunk newChunk()
            {
                return new NodeRecordChunk( new RecordStorageReader( legacyStore ), requiresPropertyMigration );
            }
        };
    }

Replace Generic With Diamond StoreScanAsInputIterator<NodeRecord> with StoreScanAsInputIterator<> in method private legacyNodesAsInput(legacyStore NeoStores, requiresPropertyMigration boolean) : InputIterator from class org.neo4j.kernel.impl.storemigration.RecordStorageMigrator


    @Override
    public BoundedIterable<Long> newAllEntriesReader()
    {
        ArrayList<BoundedIterable<Long>> allEntriesReader = new ArrayList<>();
        for ( NativeIndexAccessor<?,?> part : this )
        {
            allEntriesReader.add( part.newAllEntriesReader() );
        }

        return new BoundedIterable<>()
        {
            @Override
            public long maxCount()
            {
                long sum = 0L;
                for ( BoundedIterable<Long> part : allEntriesReader )
                {
                    long partMaxCount = part.maxCount();
                    if ( partMaxCount == UNKNOWN_MAX_COUNT )
                    {
                        return UNKNOWN_MAX_COUNT;
                    }
                    sum += partMaxCount;
                }
                return sum;
            }

            @Override
            public void close() throws Exception
            {
                forAll( BoundedIterable::close, allEntriesReader );
            }

            @Override
            public Iterator<Long> iterator()
            {
                return new CombiningIterable<>( allEntriesReader ).iterator();
            }
        };
    }

    @Override
    public BoundedIterable<Long> newAllEntriesReader()
    {
        ArrayList<BoundedIterable<Long>> allEntriesReader = new ArrayList<>();
        for ( NativeIndexAccessor<?,?> part : this )
        {
            allEntriesReader.add( part.newAllEntriesReader() );
        }

        return new BoundedIterable<Long>()
        {
            @Override
            public long maxCount()
            {
                long sum = 0L;
                for ( BoundedIterable<Long> part : allEntriesReader )
                {
                    long partMaxCount = part.maxCount();
                    if ( partMaxCount == UNKNOWN_MAX_COUNT )
                    {
                        return UNKNOWN_MAX_COUNT;
                    }
                    sum += partMaxCount;
                }
                return sum;
            }

            @Override
            public void close() throws Exception
            {
                forAll( BoundedIterable::close, allEntriesReader );
            }

            @Override
            public Iterator<Long> iterator()
            {
                return new CombiningIterable<>( allEntriesReader ).iterator();
            }
        };
    }

Replace Generic With Diamond BoundedIterable<Long> with BoundedIterable<> in method public newAllEntriesReader() : BoundedIterable<Long> from class org.neo4j.kernel.impl.index.schema.TemporalIndexAccessor


    @Override
    public BoundedIterable<Long> newAllEntriesReader()
    {
        Iterable<BoundedIterable<Long>> entries = instanceSelector.transform( IndexAccessor::newAllEntriesReader );
        return new BoundedIterable<>()
        {
            @Override
            public long maxCount()
            {
                long sum = 0;
                for ( BoundedIterable entry : entries )
                {
                    long maxCount = entry.maxCount();
                    if ( maxCount == UNKNOWN_MAX_COUNT )
                    {
                        return UNKNOWN_MAX_COUNT;
                    }
                    sum += maxCount;
                }
                return sum;
            }

            @Override
            public void close() throws Exception
            {
                forAll( BoundedIterable::close, entries );
            }

            @Override
            public Iterator<Long> iterator()
            {
                return Iterables.concat( entries ).iterator();
            }
        };
    }

    @Override
    public BoundedIterable<Long> newAllEntriesReader()
    {
        Iterable<BoundedIterable<Long>> entries = instanceSelector.transform( IndexAccessor::newAllEntriesReader );
        return new BoundedIterable<Long>()
        {
            @Override
            public long maxCount()
            {
                long sum = 0;
                for ( BoundedIterable entry : entries )
                {
                    long maxCount = entry.maxCount();
                    if ( maxCount == UNKNOWN_MAX_COUNT )
                    {
                        return UNKNOWN_MAX_COUNT;
                    }
                    sum += maxCount;
                }
                return sum;
            }

            @SuppressWarnings( "unchecked" )
            @Override
            public void close() throws Exception
            {
                forAll( BoundedIterable::close, entries );
            }

            @Override
            public Iterator<Long> iterator()
            {
                return Iterables.concat( entries ).iterator();
            }
        };
    }

Replace Generic With Diamond BoundedIterable<Long> with BoundedIterable<> in method public newAllEntriesReader() : BoundedIterable<Long> from class org.neo4j.kernel.impl.index.schema.fusion.FusionIndexAccessor


        @SuppressWarnings( "unchecked" )
        RawCursor<Hit<LabelScanKey,LabelScanValue>,IOException> nodesFor( int labelId )
        {
            Map<LabelScanKey,LabelScanValue> forLabel = data.get( labelId );
            if ( forLabel == null )
            {
                forLabel = Collections.emptyMap();
            }

            Map.Entry<LabelScanKey,LabelScanValue>[] entries = forLabel.entrySet().toArray( new Entry[0] );
            return new RawCursor<>()
            {
                private int arrayIndex = -1;

                @Override
                public Hit<LabelScanKey,LabelScanValue> get()
                {
                    Entry<LabelScanKey,LabelScanValue> entry = entries[arrayIndex];
                    return new MutableHit<>( entry.getKey(), entry.getValue() );
                }

                @Override
                public boolean next()
                {
                    arrayIndex++;
                    return arrayIndex < entries.length;
                }

                @Override
                public void close()
                {   // Nothing to close
                }
            };
        }

        @SuppressWarnings( "unchecked" )
        RawCursor<Hit<LabelScanKey,LabelScanValue>,IOException> nodesFor( int labelId )
        {
            Map<LabelScanKey,LabelScanValue> forLabel = data.get( labelId );
            if ( forLabel == null )
            {
                forLabel = Collections.emptyMap();
            }

            Map.Entry<LabelScanKey,LabelScanValue>[] entries =
                    forLabel.entrySet().toArray( new Map.Entry[forLabel.size()] );
            return new RawCursor<Hit<LabelScanKey,LabelScanValue>,IOException>()
            {
                private int arrayIndex = -1;

                @Override
                public Hit<LabelScanKey,LabelScanValue> get()
                {
                    Entry<LabelScanKey,LabelScanValue> entry = entries[arrayIndex];
                    return new MutableHit<>( entry.getKey(), entry.getValue() );
                }

                @Override
                public boolean next()
                {
                    arrayIndex++;
                    return arrayIndex < entries.length;
                }

                @Override
                public void close()
                {   // Nothing to close
                }
            };
        }

Replace Generic With Diamond RawCursor<Hit<LabelScanKey,LabelScanValue>,IOException> with RawCursor<> in method package nodesFor(labelId int) : RawCursor<Hit<LabelScanKey,LabelScanValue>,IOException> from class org.neo4j.internal.index.label.NativeLabelScanWriterTest.ControlledInserter


        @Override
        public StoreScan<IndexPopulationFailedKernelException> answer( InvocationOnMock invocation )
        {
            final Visitor<EntityUpdates,IndexPopulationFailedKernelException> visitor =
                    visitor( invocation.getArgument( 2 ) );
            return new StoreScan<>()
            {
                private volatile boolean stop;

                @Override
                public void run() throws IndexPopulationFailedKernelException
                {
                    for ( EntityUpdates update : updates )
                    {
                        if ( stop )
                        {
                            return;
                        }
                        visitor.visit( update );
                    }
                }

                @Override
                public void stop()
                {
                    stop = true;
                }

                @Override
                public void acceptUpdate( MultipleIndexPopulator.MultipleIndexUpdater updater, IndexEntryUpdate<?> update, long currentlyIndexedNodeId )
                {
                    // no-op
                }

                @Override
                public PopulationProgress getProgress()
                {
                    return PopulationProgress.single( 42, 100 );
                }
            };
        }

        @Override
        public StoreScan<IndexPopulationFailedKernelException> answer( InvocationOnMock invocation )
        {
            final Visitor<EntityUpdates,IndexPopulationFailedKernelException> visitor =
                    visitor( invocation.getArgument( 2 ) );
            return new StoreScan<IndexPopulationFailedKernelException>()
            {
                private volatile boolean stop;

                @Override
                public void run() throws IndexPopulationFailedKernelException
                {
                    for ( EntityUpdates update : updates )
                    {
                        if ( stop )
                        {
                            return;
                        }
                        visitor.visit( update );
                    }
                }

                @Override
                public void stop()
                {
                    stop = true;
                }

                @Override
                public void acceptUpdate( MultipleIndexPopulator.MultipleIndexUpdater updater,
                        IndexEntryUpdate<?> update,
                        long currentlyIndexedNodeId )
                {
                    // no-op
                }

                @Override
                public PopulationProgress getProgress()
                {
                    return PopulationProgress.single( 42, 100 );
                }
            };
        }

Replace Generic With Diamond StoreScan<IndexPopulationFailedKernelException> with StoreScan<> in method public answer(invocation InvocationOnMock) : StoreScan<IndexPopulationFailedKernelException> from class org.neo4j.kernel.impl.api.index.IndexingServiceTest.DataUpdates


    private static Matcher<? extends Throwable> causedBy( final Throwable exception )
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Throwable item )
            {
                while ( item != null )
                {
                    if ( item == exception )
                    {
                        return true;
                    }
                    item = item.getCause();
                }
                return false;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "exception caused by " ).appendValue( exception );
            }
        };
    }

    private static Matcher<? extends Throwable> causedBy( final Throwable exception )
    {
        return new TypeSafeMatcher<Throwable>()
        {
            @Override
            protected boolean matchesSafely( Throwable item )
            {
                while ( item != null )
                {
                    if ( item == exception )
                    {
                        return true;
                    }
                    item = item.getCause();
                }
                return false;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "exception caused by " ).appendValue( exception );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<Throwable> with TypeSafeMatcher<> in method private causedBy(exception Throwable) : Matcher<? extends Throwable> from class org.neo4j.kernel.impl.api.index.IndexingServiceTest


    @Test
    public void shouldLockUpdatedNodes() throws Exception
    {
        // given
        LockService locks = mock( LockService.class, new Answer<>()
        {
            @Override
            public synchronized Object answer( final InvocationOnMock invocation )
            {
                // This is necessary because finalize() will also be called
                String name = invocation.getMethod().getName();
                if ( name.equals( "acquireNodeLock" ) || name.equals( "acquireRelationshipLock" ) )
                {
                    return mock( Lock.class, invocationOnMock -> null );
                }
                return null;
            }
        } );
        NeoStores neoStores = neoStoresRule.builder().build();
        NodeStore nodeStore = neoStores.getNodeStore();
        long[] nodes = { // allocate ids
                nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(),};

        {
            // create the node records that we will modify in our main tx.
            TransactionRecordState tx = newTransactionRecordState( neoStores );
            for ( int i = 1; i < nodes.length - 1; i++ )
            {
                tx.nodeCreate( nodes[i] );
            }
            tx.nodeAddProperty( nodes[3], 0, Values.of( "old" ) );
            tx.nodeAddProperty( nodes[4], 0, Values.of( "old" ) );
            BatchTransactionApplier applier = buildApplier( neoStores, locks );
            apply( applier, transaction( tx ) );
        }
        reset( locks );

        // These are the changes we want to assert locking on
        TransactionRecordState tx = newTransactionRecordState( neoStores );
        tx.nodeCreate( nodes[0] );
        tx.addLabelToNode( 0, nodes[1] );
        tx.nodeAddProperty( nodes[2], 0, Values.of( "value" ) );
        tx.nodeChangeProperty( nodes[3], 0, Values.of( "value" ) );
        tx.nodeRemoveProperty( nodes[4], 0 );
        tx.nodeDelete( nodes[5] );

        tx.nodeCreate( nodes[6] );
        tx.addLabelToNode( 0, nodes[6] );
        tx.nodeAddProperty( nodes[6], 0, Values.of( "value" ) );

        //commit( tx );
        BatchTransactionApplier applier = buildApplier( neoStores, locks );
        apply( applier, transaction( tx ) );

        // then
        // create node, NodeCommand == 1 update
        verify( locks ).acquireNodeLock( nodes[0], LockService.LockType.WRITE_LOCK );
        // add label, NodeCommand == 1 update
        verify( locks ).acquireNodeLock( nodes[1], LockService.LockType.WRITE_LOCK );
        // add property, NodeCommand and PropertyCommand == 2 updates
        verify( locks, times( 2 ) ).acquireNodeLock( nodes[2], LockService.LockType.WRITE_LOCK );
        // update property, in place, PropertyCommand == 1 update
        verify( locks ).acquireNodeLock( nodes[3], LockService.LockType.WRITE_LOCK );
        // remove property, updates the Node and the Property == 2 updates
        verify( locks, times( 2 ) ).acquireNodeLock( nodes[4], LockService.LockType.WRITE_LOCK );
        // delete node, single NodeCommand == 1 update
        verify( locks ).acquireNodeLock( nodes[5], LockService.LockType.WRITE_LOCK );
        // create and add-label goes into the NodeCommand, add property is a PropertyCommand == 2 updates
        verify( locks, times( 2 ) ).acquireNodeLock( nodes[6], LockService.LockType.WRITE_LOCK );
    }

    @Test
    public void shouldLockUpdatedNodes() throws Exception
    {
        // given
        LockService locks = mock( LockService.class, new Answer<Object>()
        {
            @Override
            public synchronized Object answer( final InvocationOnMock invocation )
            {
                // This is necessary because finalize() will also be called
                String name = invocation.getMethod().getName();
                if ( name.equals( "acquireNodeLock" ) || name.equals( "acquireRelationshipLock" ) )
                {
                    return mock( Lock.class, invocationOnMock -> null );
                }
                return null;
            }
        } );
        NeoStores neoStores = neoStoresRule.builder().build();
        NodeStore nodeStore = neoStores.getNodeStore();
        long[] nodes = { // allocate ids
                nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(), nodeStore.nextId(),};

        {
            // create the node records that we will modify in our main tx.
            TransactionRecordState tx = newTransactionRecordState( neoStores );
            for ( int i = 1; i < nodes.length - 1; i++ )
            {
                tx.nodeCreate( nodes[i] );
            }
            tx.nodeAddProperty( nodes[3], 0, Values.of( "old" ) );
            tx.nodeAddProperty( nodes[4], 0, Values.of( "old" ) );
            BatchTransactionApplier applier = buildApplier( neoStores, locks );
            apply( applier, transaction( tx ) );
        }
        reset( locks );

        // These are the changes we want to assert locking on
        TransactionRecordState tx = newTransactionRecordState( neoStores );
        tx.nodeCreate( nodes[0] );
        tx.addLabelToNode( 0, nodes[1] );
        tx.nodeAddProperty( nodes[2], 0, Values.of( "value" ) );
        tx.nodeChangeProperty( nodes[3], 0, Values.of( "value" ) );
        tx.nodeRemoveProperty( nodes[4], 0 );
        tx.nodeDelete( nodes[5] );

        tx.nodeCreate( nodes[6] );
        tx.addLabelToNode( 0, nodes[6] );
        tx.nodeAddProperty( nodes[6], 0, Values.of( "value" ) );

        //commit( tx );
        BatchTransactionApplier applier = buildApplier( neoStores, locks );
        apply( applier, transaction( tx ) );

        // then
        // create node, NodeCommand == 1 update
        verify( locks ).acquireNodeLock( nodes[0], LockService.LockType.WRITE_LOCK );
        // add label, NodeCommand == 1 update
        verify( locks ).acquireNodeLock( nodes[1], LockService.LockType.WRITE_LOCK );
        // add property, NodeCommand and PropertyCommand == 2 updates
        verify( locks, times( 2 ) ).acquireNodeLock( nodes[2], LockService.LockType.WRITE_LOCK );
        // update property, in place, PropertyCommand == 1 update
        verify( locks ).acquireNodeLock( nodes[3], LockService.LockType.WRITE_LOCK );
        // remove property, updates the Node and the Property == 2 updates
        verify( locks, times( 2 ) ).acquireNodeLock( nodes[4], LockService.LockType.WRITE_LOCK );
        // delete node, single NodeCommand == 1 update
        verify( locks ).acquireNodeLock( nodes[5], LockService.LockType.WRITE_LOCK );
        // create and add-label goes into the NodeCommand, add property is a PropertyCommand == 2 updates
        verify( locks, times( 2 ) ).acquireNodeLock( nodes[6], LockService.LockType.WRITE_LOCK );
    }

Replace Generic With Diamond Answer<Object> with Answer<> in method public shouldLockUpdatedNodes() : void from class org.neo4j.internal.recordstorage.TransactionRecordStateTest


    public static Predicate<Thread> waitingWhileIn( final Class<?> owner, final String method )
    {
        verifyMethodExists( owner, method );
        return new Predicate<>()
        {
            @Override
            public boolean test( Thread thread )
            {
                if ( thread.getState() == Thread.State.WAITING || thread.getState() == Thread.State.TIMED_WAITING )
                {
                    return StackWalker.getInstance().walk( s -> s.filter(
                            frame -> frame.getClassName().equals( owner.getName() ) && frame.getMethodName().equals( method ) ).findAny() ).isPresent();
                }
                return false;
            }

            @Override
            public String toString()
            {
                return String.format( "Predicate[Thread.state=WAITING && call stack contains %s.%s()]", owner.getName(), method );
            }
        };
    }

    public static Predicate<Thread> waitingWhileIn( final Class<?> owner, final String method )
    {
        return new Predicate<Thread>()
        {
            @Override
            public boolean test( Thread thread )
            {
                ReflectionUtil.verifyMethodExists( owner, method );

                if ( thread.getState() == Thread.State.WAITING || thread.getState() == Thread.State.TIMED_WAITING )
                {
                    for ( StackTraceElement element : thread.getStackTrace() )
                    {
                        if ( element.getClassName().equals( owner.getName() ) && element.getMethodName().equals( method ) )
                        {
                            return true;
                        }
                    }
                }
                return false;
            }

            @Override
            public String toString()
            {
                return String.format( "Predicate[Thread.state=WAITING && thread.getStackTrace() contains %s.%s()]",
                        owner.getName(), method );
            }
        };
    }

Replace Generic With Diamond Predicate<Thread> with Predicate<> in method public waitingWhileIn(owner Class<?>, method String) : Predicate<Thread> from class org.neo4j.test.rule.concurrent.ThreadingRule


    @ParameterizedTest
    @EnumSource( BufferFactories.class )
    void shouldHandleRunningOutOfBytesWhenRequestSpansMultipleFiles( IntFunction<ByteBuffer> bufferFactory ) throws Exception
    {
        // Given
        StoreChannel storeChannel1 = fileSystem.create( new File( "foo.1" ) );
        ByteBuffer buffer = ByteBuffer.allocate( 2 );
        buffer.put( (byte) 0 );
        buffer.put( (byte) 0 );
        buffer.flip();
        storeChannel1.writeAll( buffer );
        storeChannel1.force( false );
        storeChannel1.close();

        buffer.flip();

        StoreChannel storeChannel2 = fileSystem.open( new File( "foo.2" ), Set.of( READ ) );
        buffer.put( (byte) 0 );
        buffer.put( (byte) 1 );
        buffer.flip();
        storeChannel2.writeAll( buffer );
        storeChannel2.force( false );
        storeChannel2.close();

        storeChannel1 = fileSystem.open( new File( "foo.1" ), Set.of( READ ) );
        final StoreChannel storeChannel2Copy = fileSystem.open( new File( "foo.2" ), Set.of( READ ) );

        ReadAheadChannel<StoreChannel> channel = new ReadAheadChannel<>( storeChannel1, bufferFactory.apply( DEFAULT_READ_AHEAD_SIZE ) )
        {
            @Override
            protected StoreChannel next( StoreChannel channel )
            {
                return storeChannel2Copy;
            }
        };

        assertThrows( ReadPastEndException.class, channel::getLong );
        assertEquals( 1, channel.getInt() );
        assertThrows( ReadPastEndException.class, channel::get );
    }

    @ParameterizedTest
    @EnumSource( BufferFactories.class )
    void shouldHandleRunningOutOfBytesWhenRequestSpansMultipleFiles( IntFunction<ByteBuffer> bufferFactory ) throws Exception
    {
        // Given
        StoreChannel storeChannel1 = fileSystem.open( new File( "foo.1" ), OpenMode.READ_WRITE );
        ByteBuffer buffer = ByteBuffer.allocate( 2 );
        buffer.put( (byte) 0 );
        buffer.put( (byte) 0 );
        buffer.flip();
        storeChannel1.writeAll( buffer );
        storeChannel1.force( false );
        storeChannel1.close();

        buffer.flip();

        StoreChannel storeChannel2 = fileSystem.open( new File( "foo.2" ), OpenMode.READ );
        buffer.put( (byte) 0 );
        buffer.put( (byte) 1 );
        buffer.flip();
        storeChannel2.writeAll( buffer );
        storeChannel2.force( false );
        storeChannel2.close();

        storeChannel1 = fileSystem.open( new File( "foo.1" ), OpenMode.READ );
        final StoreChannel storeChannel2Copy = fileSystem.open( new File( "foo.2" ), OpenMode.READ );

        ReadAheadChannel<StoreChannel> channel = new ReadAheadChannel<StoreChannel>( storeChannel1, bufferFactory.apply( DEFAULT_READ_AHEAD_SIZE ) )
        {
            @Override
            protected StoreChannel next( StoreChannel channel )
            {
                return storeChannel2Copy;
            }
        };

        assertThrows( ReadPastEndException.class, channel::getLong );
        assertEquals( 1, channel.getInt() );
        assertThrows( ReadPastEndException.class, channel::get );
    }

Replace Generic With Diamond ReadAheadChannel<StoreChannel> with ReadAheadChannel<> in method package shouldHandleRunningOutOfBytesWhenRequestSpansMultipleFiles(bufferFactory IntFunction<ByteBuffer>) : void from class org.neo4j.kernel.impl.transaction.log.ReadAheadChannelTest


        public String get( String key ) throws IOException
        {
            return lookup( key, new Reader<>()
            {
                @Override
                protected String parseValue( ReadableBuffer value )
                {
                    return readKey( value );
                }
            } );
        }

        public String get( String key ) throws IOException
        {
            return lookup( key, new Reader<String>()
            {
                @Override
                protected String parseValue( ReadableBuffer value )
                {
                    return readKey( value );
                }
            } );
        }

Replace Generic With Diamond Reader<String> with Reader<> in method public get(key String) : String from class org.neo4j.kernel.impl.store.kvstore.AbstractKeyValueStoreTest.Store


    private AbstractKeyValueStore.Reader<String> stringReader( String value )
    {
        return new AbstractKeyValueStore.Reader<>()
        {
            @Override
            protected String parseValue( ReadableBuffer buffer )
            {
                return value;
            }
        };
    }

    private AbstractKeyValueStore.Reader<String> stringReader( String value )
    {
        return new AbstractKeyValueStore.Reader<String>()
        {
            @Override
            protected String parseValue( ReadableBuffer buffer )
            {
                return value;
            }
        };
    }

Replace Generic With Diamond AbstractKeyValueStore.Reader<String> with AbstractKeyValueStore.Reader<> in method private stringReader(value String) : AbstractKeyValueStore.Reader<String> from class org.neo4j.kernel.impl.store.kvstore.AbstractKeyValueStoreTest


        Iterator<EphemeralFileChannel> getOpenChannels()
        {
            final Iterator<WeakReference<EphemeralFileChannel>> refs = channels.iterator();

            return new PrefetchingIterator<>()
            {
                @Override
                protected EphemeralFileChannel fetchNextOrNull()
                {
                    while ( refs.hasNext() )
                    {
                        EphemeralFileChannel channel = refs.next().get();
                        if ( channel != null )
                        {
                            return channel;
                        }
                        refs.remove();
                    }
                    return null;
                }

                @Override
                public void remove()
                {
                    refs.remove();
                }
            };
        }

        Iterator<EphemeralFileChannel> getOpenChannels()
        {
            final Iterator<WeakReference<EphemeralFileChannel>> refs = channels.iterator();

            return new PrefetchingIterator<EphemeralFileChannel>()
            {
                @Override
                protected EphemeralFileChannel fetchNextOrNull()
                {
                    while ( refs.hasNext() )
                    {
                        EphemeralFileChannel channel = refs.next().get();
                        if ( channel != null )
                        {
                            return channel;
                        }
                        refs.remove();
                    }
                    return null;
                }

                @Override
                public void remove()
                {
                    refs.remove();
                }
            };
        }

Replace Generic With Diamond PrefetchingIterator<EphemeralFileChannel> with PrefetchingIterator<> in method package getOpenChannels() : Iterator<EphemeralFileChannel> from class org.neo4j.graphdb.mockfs.EphemeralFileSystemAbstraction.EphemeralFileData


    /**
     * A short-hand method for creating a {@link Map} of key/value pairs.
     *
     * @param objects alternating key and value.
     * @param <K> type of keys
     * @param <V> type of values
     * @return a Map with the entries supplied by {@code objects}.
     */
    public static <K, V> Map<K, V> genericMap( Object... objects )
    {
        return genericMap( new HashMap<>(), objects );
    }

    /**
     * A short-hand method for creating a {@link Map} of key/value pairs.
     *
     * @param objects alternating key and value.
     * @param <K> type of keys
     * @param <V> type of values
     * @return a Map with the entries supplied by {@code objects}.
     */
    public static <K, V> Map<K, V> genericMap( Object... objects )
    {
        return genericMap( new HashMap<K, V>(), objects );
    }

Replace Generic With Diamond HashMap<K,V> with HashMap<> in method public genericMap(objects Object...) : Map<K,V> from class org.neo4j.helpers.collection.MapUtil


    @Override
    public void scanCompleted( PhaseTracker phaseTracker ) throws IndexEntryConflictException
    {
        if ( !markMergeStarted() )
        {
            // This populator has already been closed, either from an external cancel or drop call.
            // Either way we're not supposed to do this merge.
            return;
        }

        try
        {
            phaseTracker.enterPhase( PhaseTracker.Phase.MERGE );
            if ( !allScanUpdates.isEmpty() )
            {
                mergeScanUpdates();
            }

            externalUpdates.doneAdding();
            // don't merge and sort the external updates

            // Build the tree from the scan updates
            phaseTracker.enterPhase( PhaseTracker.Phase.BUILD );
            File duplicatesFile = new File( storeFile.getParentFile(), storeFile.getName() + ".dup" );
            try ( IndexKeyStorage<KEY> indexKeyStorage = new IndexKeyStorage<>( fileSystem, duplicatesFile, bufferFactory, blockSize, layout ) )
            {
                RecordingConflictDetector<KEY,VALUE> recordingConflictDetector = new RecordingConflictDetector<>( !descriptor.isUnique(), indexKeyStorage );
                writeScanUpdatesToTree( recordingConflictDetector );

                // Apply the external updates
                phaseTracker.enterPhase( PhaseTracker.Phase.APPLY_EXTERNAL );
                writeExternalUpdatesToTree( recordingConflictDetector );

                // Verify uniqueness
                if ( descriptor.isUnique() )
                {
                    verifyUniqueKeys( recordingConflictDetector.allConflicts() );
                }
            }
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
        catch ( InterruptedException e )
        {
            Thread.currentThread().interrupt();
            throw new RuntimeException( "Got interrupted, so merge not completed", e );
        }
        catch ( ExecutionException e )
        {
            // Propagating merge exception from other thread
            Throwable executionException = e.getCause();
            if ( executionException instanceof RuntimeException )
            {
                throw (RuntimeException) executionException;
            }
            throw new RuntimeException( executionException );
        }
        finally
        {
            mergeOngoingLatch.countDown();
        }
    }

    @Override
    public void scanCompleted( PhaseTracker phaseTracker ) throws IndexEntryConflictException
    {
        if ( !markMergeStarted() )
        {
            // This populator has already been closed, either from an external cancel or drop call.
            // Either way we're not supposed to do this merge.
            return;
        }

        try
        {
            phaseTracker.enterPhase( PhaseTracker.Phase.MERGE );
            if ( !allScanUpdates.isEmpty() )
            {
                mergeScanUpdates();
            }

            externalUpdates.doneAdding();
            // don't merge and sort the external updates

            // Build the tree from the scan updates
            phaseTracker.enterPhase( PhaseTracker.Phase.BUILD );
            RecordingConflictDetector<KEY,VALUE> recordingConflictDetector = new RecordingConflictDetector<>( !descriptor.isUnique() );
            writeScanUpdatesToTree( recordingConflictDetector );

            // Apply the external updates
            phaseTracker.enterPhase( PhaseTracker.Phase.APPLY_EXTERNAL );
            writeExternalUpdatesToTree( recordingConflictDetector );

            // Verify uniqueness
            if ( descriptor.isUnique() )
            {
                verifyUniqueKeys( recordingConflictDetector.allConflicts() );
            }
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
        catch ( InterruptedException e )
        {
            Thread.currentThread().interrupt();
            throw new RuntimeException( "Got interrupted, so merge not completed", e );
        }
        catch ( ExecutionException e )
        {
            // Propagating merge exception from other thread
            Throwable executionException = e.getCause();
            if ( executionException instanceof RuntimeException )
            {
                throw (RuntimeException) executionException;
            }
            throw new RuntimeException( executionException );
        }
        finally
        {
            mergeOngoingLatch.countDown();
        }
    }

Try With Resources try(IndexKeyStorage<KEY> indexKeyStorage=new IndexKeyStorage<>(fileSystem,duplicatesFile,bufferFactory,blockSize,layout)) in method public scanCompleted(phaseTracker PhaseTracker) : void from class org.neo4j.kernel.impl.index.schema.BlockBasedIndexPopulator


    private Iterator<PropertyBlock> propertiesIterator( Map<String, Object> properties )
    {
        if ( properties == null || properties.isEmpty() )
        {
            return emptyIterator();
        }
        return new IteratorWrapper<>( properties.entrySet().iterator() )
        {
            @Override
            protected PropertyBlock underlyingObjectToObject( Entry<String,Object> property )
            {
                return propertyCreator.encodePropertyValue( getOrCreatePropertyKeyId( property.getKey() ), ValueUtils.asValue( property.getValue() ) );
            }
        };
    }

    private Iterator<PropertyBlock> propertiesIterator( Map<String, Object> properties )
    {
        if ( properties == null || properties.isEmpty() )
        {
            return emptyIterator();
        }
        return new IteratorWrapper<PropertyBlock, Map.Entry<String,Object>>( properties.entrySet().iterator() )
        {
            @Override
            protected PropertyBlock underlyingObjectToObject( Entry<String, Object> property )
            {
                return propertyCreator.encodePropertyValue(
                        getOrCreatePropertyKeyId( property.getKey() ), ValueUtils.asValue( property.getValue() ) );
            }
        };
    }

Replace Generic With Diamond IteratorWrapper<PropertyBlock,Map.Entry<String,Object>> with IteratorWrapper<> in method private propertiesIterator(properties Map<String,Object>) : Iterator<PropertyBlock> from class org.neo4j.unsafe.batchinsert.internal.BatchInserterImpl


    @Override
    public Iterable<Long> getRelationshipIds( long nodeId )
    {
        flushStrategy.forceFlush();
        return new BatchRelationshipIterable<>( storageReader, nodeId )
        {
            @Override
            protected Long nextFrom( long relId, int type, long startNode, long endNode )
            {
                return relId;
            }
        };
    }

    @Override
    public Iterable<Long> getRelationshipIds( long nodeId )
    {
        flushStrategy.forceFlush();
        return new BatchRelationshipIterable<Long>( storageReader, nodeId )
        {
            @Override
            protected Long nextFrom( long relId, int type, long startNode, long endNode )
            {
                return relId;
            }
        };
    }

Replace Generic With Diamond BatchRelationshipIterable<Long> with BatchRelationshipIterable<> in method public getRelationshipIds(nodeId long) : Iterable<Long> from class org.neo4j.unsafe.batchinsert.internal.BatchInserterImpl


    @Override
    public Iterable<BatchRelationship> getRelationships( long nodeId )
    {
        flushStrategy.forceFlush();
        return new BatchRelationshipIterable<>( storageReader, nodeId )
        {
            @Override
            protected BatchRelationship nextFrom( long relId, int type, long startNode, long endNode )
            {
                return batchRelationshipOf( relId, type, startNode, endNode );
            }
        };
    }

    @Override
    public Iterable<BatchRelationship> getRelationships( long nodeId )
    {
        flushStrategy.forceFlush();
        return new BatchRelationshipIterable<BatchRelationship>( storageReader, nodeId )
        {
            @Override
            protected BatchRelationship nextFrom( long relId, int type, long startNode, long endNode )
            {
                return batchRelationshipOf( relId, type, startNode, endNode );
            }
        };
    }

Replace Generic With Diamond BatchRelationshipIterable<BatchRelationship> with BatchRelationshipIterable<> in method public getRelationships(nodeId long) : Iterable<BatchRelationship> from class org.neo4j.unsafe.batchinsert.internal.BatchInserterImpl


    private Iterable<CommonAbstractStore> instantiatedRecordStores()
    {
        Iterator<StoreType> storeTypes = new FilteringIterator<>( iterator( STORE_TYPES ), INSTANTIATED_STORES );
        return loop( new IteratorWrapper<>( storeTypes )
        {
            @Override
            protected CommonAbstractStore underlyingObjectToObject( StoreType type )
            {
                return stores[type.ordinal()];
            }
        } );
    }

    private Iterable<CommonAbstractStore> instantiatedRecordStores()
    {
        Iterator<StoreType> storeTypes = new FilteringIterator<>( iterator( STORE_TYPES ), INSTANTIATED_STORES );
        return loop( new IteratorWrapper<CommonAbstractStore,StoreType>( storeTypes )
        {
            @Override
            protected CommonAbstractStore underlyingObjectToObject( StoreType type )
            {
                return stores[type.ordinal()];
            }
        } );
    }

Replace Generic With Diamond IteratorWrapper<CommonAbstractStore,StoreType> with IteratorWrapper<> in method private instantiatedRecordStores() : Iterable<CommonAbstractStore> from class org.neo4j.kernel.impl.store.NeoStores


    public File dumpState( Locks lm, LockWorker... workers ) throws IOException
    {
        try ( FileOutputStream out = new FileOutputStream( file, false ) )
        {
            FormattedLogProvider logProvider = FormattedLogProvider.withoutAutoFlush().toOutputStream( out );
            //  * locks held by the lock manager
            lm.accept( new DumpLocksVisitor( logProvider.getLog( LockWorkFailureDump.class ) ) );
            //  * rag manager state;
            //  * workers state
            Log log = logProvider.getLog( getClass() );
            for ( LockWorker worker : workers )
            {
                // - what each is doing and have up to now
                log.info( "Worker %s", worker );
            }
            return file;
        }
    }

    public File dumpState( Locks lm, LockWorker... workers ) throws IOException
    {
        FileOutputStream out = new FileOutputStream( file, false );
        FormattedLogProvider logProvider = FormattedLogProvider.withoutAutoFlush().toOutputStream( out );

        try
        {
            //  * locks held by the lock manager
            lm.accept( new DumpLocksVisitor( logProvider.getLog( LockWorkFailureDump.class ) ) );
            //  * rag manager state;
            //  * workers state
            Log log = logProvider.getLog( getClass() );
            for ( LockWorker worker : workers )
            {
                // - what each is doing and have up to now
                log.info( "Worker %s", worker );
            }
            return file;
        }
        finally
        {
            out.flush();
            out.close();
        }
    }

Try With Resources try(FileOutputStream out=new FileOutputStream(file,false)) in method public dumpState(lm Locks, workers LockWorker...) : File from class org.neo4j.kernel.impl.locking.LockWorkFailureDump


    private long doCheckPoint( TriggerInfo triggerInfo ) throws IOException
    {
        try ( LogCheckPointEvent event = tracer.beginCheckPoint() )
        {
            long[] lastClosedTransaction = transactionIdStore.getLastClosedTransaction();
            long lastClosedTransactionId = lastClosedTransaction[0];
            LogPosition logPosition = new LogPosition( lastClosedTransaction[1], lastClosedTransaction[2] );
            String prefix = triggerInfo.describe( lastClosedTransactionId );
            /*
             * Check kernel health before going into waiting for transactions to be closed, to avoid
             * getting into a scenario where we would await a condition that would potentially never
             * happen.
             */
            databaseHealth.assertHealthy( IOException.class );
            /*
             * First we flush the store. If we fail now or during the flush, on recovery we'll find the
             * earlier check point and replay from there all the log entries. Everything will be ok.
             */
            msgLog.info( prefix + " checkpoint started..." );
            long startTime = currentTimeMillis();
            storageEngine.flushAndForce( ioLimiter );
            /*
             * Check kernel health before going to write the next check point.  In case of a panic this check point
             * will be aborted, which is the safest alternative so that the next recovery will have a chance to
             * repair the damages.
             */
            databaseHealth.assertHealthy( IOException.class );
            appender.checkPoint( logPosition, event );
            threshold.checkPointHappened( lastClosedTransactionId );
            msgLog.info( prefix + " checkpoint completed in " + duration( currentTimeMillis() - startTime ) );
            /*
             * Prune up to the version pointed from the latest check point,
             * since it might be an earlier version than the current log version.
             */
            logPruning.pruneLogs( logPosition.getLogVersion() );
            lastCheckPointedTx = lastClosedTransactionId;
            return lastClosedTransactionId;
        }
        catch ( Throwable t )
        {
            // Why only log failure here? It's because check point can potentially be made from various
            // points of execution e.g. background thread triggering check point if needed and during
            // shutdown where it's better to have more control over failure handling.
            msgLog.error( "Checkpoint failed", t );
            throw t;
        }
    }

    private long doCheckPoint( TriggerInfo triggerInfo, LogCheckPointEvent logCheckPointEvent ) throws IOException
    {
        try
        {
            long[] lastClosedTransaction = transactionIdStore.getLastClosedTransaction();
            long lastClosedTransactionId = lastClosedTransaction[0];
            LogPosition logPosition = new LogPosition( lastClosedTransaction[1], lastClosedTransaction[2] );
            String prefix = triggerInfo.describe( lastClosedTransactionId );
            /*
             * Check kernel health before going into waiting for transactions to be closed, to avoid
             * getting into a scenario where we would await a condition that would potentially never
             * happen.
             */
            databaseHealth.assertHealthy( IOException.class );
            /*
             * First we flush the store. If we fail now or during the flush, on recovery we'll find the
             * earlier check point and replay from there all the log entries. Everything will be ok.
             */
            msgLog.info( prefix + " checkpoint started..." );
            long startTime = currentTimeMillis();
            storageEngine.flushAndForce( ioLimiter );
            /*
             * Check kernel health before going to write the next check point.  In case of a panic this check point
             * will be aborted, which is the safest alternative so that the next recovery will have a chance to
             * repair the damages.
             */
            databaseHealth.assertHealthy( IOException.class );
            appender.checkPoint( logPosition, logCheckPointEvent );
            threshold.checkPointHappened( lastClosedTransactionId );
            msgLog.info( prefix + " checkpoint completed in " + duration( currentTimeMillis() - startTime ) );
            /*
             * Prune up to the version pointed from the latest check point,
             * since it might be an earlier version than the current log version.
             */
            logPruning.pruneLogs( logPosition.getLogVersion() );
            lastCheckPointedTx = lastClosedTransactionId;
            return lastClosedTransactionId;
        }
        catch ( Throwable t )
        {
            // Why only log failure here? It's because check point can potentially be made from various
            // points of execution e.g. background thread triggering check point if needed and during
            // shutdown where it's better to have more control over failure handling.
            msgLog.error( "Checkpoint failed", t );
            throw t;
        }
    }

Try With Resources try(LogCheckPointEvent event=tracer.beginCheckPoint()) in method private doCheckPoint(triggerInfo TriggerInfo) : long from class org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointerImpl


    private long doCheckPoint( TriggerInfo triggerInfo ) throws IOException
    {
        try ( LogCheckPointEvent event = tracer.beginCheckPoint() )
        {
            long[] lastClosedTransaction = transactionIdStore.getLastClosedTransaction();
            long lastClosedTransactionId = lastClosedTransaction[0];
            LogPosition logPosition = new LogPosition( lastClosedTransaction[1], lastClosedTransaction[2] );
            String prefix = triggerInfo.describe( lastClosedTransactionId );
            /*
             * Check kernel health before going into waiting for transactions to be closed, to avoid
             * getting into a scenario where we would await a condition that would potentially never
             * happen.
             */
            databaseHealth.assertHealthy( IOException.class );
            /*
             * First we flush the store. If we fail now or during the flush, on recovery we'll find the
             * earlier check point and replay from there all the log entries. Everything will be ok.
             */
            msgLog.info( prefix + " checkpoint started..." );
            long startTime = currentTimeMillis();
            forceOperation.flushAndForce( ioLimiter );
            /*
             * Check kernel health before going to write the next check point.  In case of a panic this check point
             * will be aborted, which is the safest alternative so that the next recovery will have a chance to
             * repair the damages.
             */
            databaseHealth.assertHealthy( IOException.class );
            appender.checkPoint( logPosition, event );
            threshold.checkPointHappened( lastClosedTransactionId );
            long durationMillis = currentTimeMillis() - startTime;
            msgLog.info( prefix + " checkpoint completed in " + duration( durationMillis ) );
            checkPointerMonitor.checkPointCompleted( durationMillis );
            /*
             * Prune up to the version pointed from the latest check point,
             * since it might be an earlier version than the current log version.
             */
            logPruning.pruneLogs( logPosition.getLogVersion() );
            lastCheckPointedTx = lastClosedTransactionId;
            return lastClosedTransactionId;
        }
        catch ( Throwable t )
        {
            // Why only log failure here? It's because check point can potentially be made from various
            // points of execution e.g. background thread triggering check point if needed and during
            // shutdown where it's better to have more control over failure handling.
            msgLog.error( "Checkpoint failed", t );
            throw t;
        }
    }

    private long doCheckPoint( TriggerInfo triggerInfo, LogCheckPointEvent logCheckPointEvent ) throws IOException
    {
        try
        {
            long[] lastClosedTransaction = transactionIdStore.getLastClosedTransaction();
            long lastClosedTransactionId = lastClosedTransaction[0];
            LogPosition logPosition = new LogPosition( lastClosedTransaction[1], lastClosedTransaction[2] );
            String prefix = triggerInfo.describe( lastClosedTransactionId );
            /*
             * Check kernel health before going into waiting for transactions to be closed, to avoid
             * getting into a scenario where we would await a condition that would potentially never
             * happen.
             */
            databaseHealth.assertHealthy( IOException.class );
            /*
             * First we flush the store. If we fail now or during the flush, on recovery we'll find the
             * earlier check point and replay from there all the log entries. Everything will be ok.
             */
            msgLog.info( prefix + " checkpoint started..." );
            long startTime = currentTimeMillis();
            forceOperation.flushAndForce( ioLimiter );
            /*
             * Check kernel health before going to write the next check point.  In case of a panic this check point
             * will be aborted, which is the safest alternative so that the next recovery will have a chance to
             * repair the damages.
             */
            databaseHealth.assertHealthy( IOException.class );
            appender.checkPoint( logPosition, logCheckPointEvent );
            threshold.checkPointHappened( lastClosedTransactionId );
            msgLog.info( prefix + " checkpoint completed in " + duration( currentTimeMillis() - startTime ) );
            /*
             * Prune up to the version pointed from the latest check point,
             * since it might be an earlier version than the current log version.
             */
            logPruning.pruneLogs( logPosition.getLogVersion() );
            lastCheckPointedTx = lastClosedTransactionId;
            return lastClosedTransactionId;
        }
        catch ( Throwable t )
        {
            // Why only log failure here? It's because check point can potentially be made from various
            // points of execution e.g. background thread triggering check point if needed and during
            // shutdown where it's better to have more control over failure handling.
            msgLog.error( "Checkpoint failed", t );
            throw t;
        }
    }


        @Override
        public void run()
        {
            try ( StorageReader reader = storageEngine.newReader();
                  CommandCreationContext creationContext = storageEngine.newCommandCreationContext() )
            {
                TransactionQueue queue = new TransactionQueue( batchSize, ( tx, last ) ->
                {
                    // Apply
                    storageEngine.apply( tx, TransactionApplicationMode.EXTERNAL );

                    // And verify that all nodes are in the index
                    verifyIndex( tx );
                    base += batchSize;
                } );
                for ( ; !end.get(); i++ )
                {
                    queue.queue( createNodeAndProperty( i, reader, creationContext ) );
                }
                queue.empty();
            }
            catch ( Exception e )
            {
                throw new RuntimeException( e );
            }
            finally
            {
                commandCreationContext.close();
            }
        }

        @Override
        public void run()
        {
            try
            {
                TransactionQueue queue = new TransactionQueue( batchSize, ( tx, last ) ->
                {
                    // Apply
                    storageEngine.apply( tx, TransactionApplicationMode.EXTERNAL );

                    // And verify that all nodes are in the index
                    verifyIndex( tx );
                    base += batchSize;
                } );
                for ( ; !end.get(); i++ )
                {
                    queue.queue( createNodeAndProperty( i ) );
                }
                queue.empty();
            }
            catch ( Exception e )
            {
                throw new RuntimeException( e );
            }
            finally
            {
                commandCreationContext.close();
            }
        }

Try With Resources try(StorageReader reader=storageEngine.newReader(); CommandCreationContext creationContext=storageEngine.newCommandCreationContext()) in method public run() : void from class org.neo4j.kernel.impl.transaction.command.IndexWorkSyncTransactionApplicationStressIT.Worker


    @Test
    public void testGraphAddPropertyWithNullKey()
    {
        try ( Transaction transaction = db.beginTx() )
        {
            graphProperties().setProperty( null, "bar" );
            fail( "Null key should result in exception." );
        }
        catch ( IllegalArgumentException ignored )
        {
        }
    }

    @Test
    public void testGraphAddPropertyWithNullKey()
    {
        try
        {
            graphProperties().setProperty( null, "bar" );
            fail( "Null key should result in exception." );
        }
        catch ( IllegalArgumentException ignored )
        {
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method public testGraphAddPropertyWithNullKey() : void from class org.neo4j.kernel.impl.core.GraphPropertiesProxyTest


    @Test
    public void testGraphAddPropertyWithNullValue()
    {
        try ( Transaction transaction = db.beginTx() )
        {
            graphProperties().setProperty( "foo", null );
            fail( "Null value should result in exception." );
        }
        catch ( IllegalArgumentException ignored )
        {
        }
    }

    @Test
    public void testGraphAddPropertyWithNullValue()
    {
        try
        {
            graphProperties().setProperty( "foo", null );
            fail( "Null value should result in exception." );
        }
        catch ( IllegalArgumentException ignored )
        {
        }
        tx.failure();
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method public testGraphAddPropertyWithNullValue() : void from class org.neo4j.kernel.impl.core.GraphPropertiesProxyTest


    @Test
    public void testNodeCreateAndDelete()
    {
        long nodeId;
        try ( Transaction transaction = db.beginTx() )
        {
            Node node = getGraphDb().createNode();
            nodeId = node.getId();
            getGraphDb().getNodeById( nodeId );
            node.delete();
            transaction.success();
        }
        try ( Transaction transaction = db.beginTx() )
        {
            getGraphDb().getNodeById( nodeId );
            fail( "Node[" + nodeId + "] should be deleted." );
        }
        catch ( NotFoundException ignored )
        {
        }
    }

    @Test
    public void testNodeCreateAndDelete()
    {
        Node node = getGraphDb().createNode();
        long nodeId = node.getId();
        getGraphDb().getNodeById( nodeId );
        node.delete();

        tx.success();
        tx.begin();
        try
        {
            getGraphDb().getNodeById( nodeId );
            fail( "Node[" + nodeId + "] should be deleted." );
        }
        catch ( NotFoundException ignored )
        {
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method public testNodeCreateAndDelete() : void from class org.neo4j.kernel.impl.core.NodeTest


    @Test
    public void canOnlyReleaseOnce()
    {
        Node node = createNode();

        try ( Transaction transaction = db.beginTx() )
        {
            Lock nodeLock = transaction.acquireWriteLock( node );
            nodeLock.release();
            try
            {
                nodeLock.release();
                fail( "Shouldn't be able to release more than once" );
            }
            catch ( IllegalStateException e )
            { // Good
            }
        }
    }

    @Test
    public void canOnlyReleaseOnce()
    {
        Node node = getGraphDb().createNode();

        tx.success();
        Transaction current = tx.begin();
        Lock nodeLock = current.acquireWriteLock( node );
        nodeLock.release();
        try
        {
            nodeLock.release();
            fail( "Shouldn't be able to release more than once" );
        }
        catch ( IllegalStateException e )
        { // Good
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method public canOnlyReleaseOnce() : void from class org.neo4j.kernel.impl.transaction.ManualAcquireLockTest