    public static Deferred<Node> findNodesByLabelAndProperty( final Label label, final String propertyName,
                                                              final Object propertyValue,
                                                              final GraphDatabaseService db )
    {
        return new Deferred<>( db )
        {
            @Override
            protected Iterable<Node> manifest()
            {
                return loop( db.findNodes( label, propertyName, propertyValue ) );
            }
        };
    }

    public static Deferred<Node> findNodesByLabelAndProperty( final Label label, final String propertyName,
                                                              final Object propertyValue,
                                                              final GraphDatabaseService db )
    {
        return new Deferred<Node>( db )
        {
            @Override
            protected Iterable<Node> manifest()
            {
                return loop( db.findNodes( label, propertyName, propertyValue ) );
            }
        };
    }

Replace Generic With Diamond Deferred<Node> with Deferred<> in method public findNodesByLabelAndProperty(label Label, propertyName String, propertyValue Object, db GraphDatabaseService) : Deferred<Node> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    public static Deferred<IndexDefinition> getIndexes( final GraphDatabaseService db, final Label label )
    {
        return new Deferred<>( db )
        {
            @Override
            protected Iterable<IndexDefinition> manifest()
            {
                try ( Transaction transaction = db.beginTx() )
                {
                    return db.schema().getIndexes( label );
                }
            }
        };
    }

    public static Deferred<IndexDefinition> getIndexes( final GraphDatabaseService db, final Label label )
    {
        return new Deferred<IndexDefinition>( db )
        {
            @Override
            protected Iterable<IndexDefinition> manifest()
            {
                return db.schema().getIndexes( label );
            }
        };
    }

Replace Generic With Diamond Deferred<IndexDefinition> with Deferred<> in method public getIndexes(db GraphDatabaseService, label Label) : Deferred<IndexDefinition> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    public static Deferred<String> getPropertyKeys( final GraphDatabaseService db,
                                                    final PropertyContainer propertyContainer )
    {
        return new Deferred<>( db )
        {
            @Override
            protected Iterable<String> manifest()
            {
                return propertyContainer.getPropertyKeys();
            }
        };
    }

    public static Deferred<String> getPropertyKeys( final GraphDatabaseService db,
                                                    final PropertyContainer propertyContainer )
    {
        return new Deferred<String>( db )
        {
            @Override
            protected Iterable<String> manifest()
            {
                return propertyContainer.getPropertyKeys();
            }
        };
    }

Replace Generic With Diamond Deferred<String> with Deferred<> in method public getPropertyKeys(db GraphDatabaseService, propertyContainer PropertyContainer) : Deferred<String> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    public static Deferred<ConstraintDefinition> getConstraints( final GraphDatabaseService db, final Label label )
    {
        return new Deferred<>( db )
        {
            @Override
            protected Iterable<ConstraintDefinition> manifest()
            {
                return db.schema().getConstraints( label );
            }
        };
    }

    public static Deferred<ConstraintDefinition> getConstraints( final GraphDatabaseService db, final Label label )
    {
        return new Deferred<ConstraintDefinition>( db )
        {
            @Override
            protected Iterable<ConstraintDefinition> manifest()
            {
                return db.schema().getConstraints( label );
            }
        };
    }

Replace Generic With Diamond Deferred<ConstraintDefinition> with Deferred<> in method public getConstraints(db GraphDatabaseService, label Label) : Deferred<ConstraintDefinition> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    public static Deferred<ConstraintDefinition> getConstraints( final GraphDatabaseService db,
            final RelationshipType type )
    {
        return new Deferred<>( db )
        {
            @Override
            protected Iterable<ConstraintDefinition> manifest()
            {
                return db.schema().getConstraints( type );
            }
        };
    }

    public static Deferred<ConstraintDefinition> getConstraints( final GraphDatabaseService db,
            final RelationshipType type )
    {
        return new Deferred<ConstraintDefinition>( db )
        {
            @Override
            protected Iterable<ConstraintDefinition> manifest()
            {
                return db.schema().getConstraints( type );
            }
        };
    }

Replace Generic With Diamond Deferred<ConstraintDefinition> with Deferred<> in method public getConstraints(db GraphDatabaseService, type RelationshipType) : Deferred<ConstraintDefinition> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    public static Deferred<ConstraintDefinition> getConstraints( final GraphDatabaseService db )
    {
        return new Deferred<>( db )
        {
            @Override
            protected Iterable<ConstraintDefinition> manifest()
            {
                return db.schema().getConstraints();
            }
        };
    }

    public static Deferred<ConstraintDefinition> getConstraints( final GraphDatabaseService db )
    {
        return new Deferred<ConstraintDefinition>( db )
        {
            @Override
            protected Iterable<ConstraintDefinition> manifest()
            {
                return db.schema().getConstraints( );
            }
        };
    }

Replace Generic With Diamond Deferred<ConstraintDefinition> with Deferred<> in method public getConstraints(db GraphDatabaseService) : Deferred<ConstraintDefinition> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    @SafeVarargs
    public static <T> TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> containsOnly( final T... expectedObjects )
    {
        return new TypeSafeDiagnosingMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Neo4jMatchers.Deferred<T> nodes, Description description )
            {
                Set<T> expected = asSet( expectedObjects );
                Set<T> found = Iterables.asSet( nodes.collection() );
                if ( !expected.equals( found ) )
                {
                    description.appendText( "found " + found.toString() );
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "exactly " + asSet( expectedObjects ) );
            }
        };
    }

    @SafeVarargs
    public static <T> TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> containsOnly( final T... expectedObjects )
    {
        return new TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>>()
        {
            @Override
            protected boolean matchesSafely( Neo4jMatchers.Deferred<T> nodes, Description description )
            {
                Set<T> expected = asSet( expectedObjects );
                Set<T> found = Iterables.asSet( nodes.collection() );
                if ( !expected.equals( found ) )
                {
                    description.appendText( "found " + found.toString() );
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "exactly " + asSet( expectedObjects ) );
            }
        };
    }

Replace Generic With Diamond TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> with TypeSafeDiagnosingMatcher<> in method public containsOnly(expectedObjects T...) : TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> hasSize( final int expectedSize )
    {
        return new TypeSafeDiagnosingMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Neo4jMatchers.Deferred<?> nodes, Description description )
            {
                int foundSize = nodes.collection().size();

                if ( foundSize != expectedSize )
                {
                    description.appendText( "found " + nodes.collection().toString() );
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "collection of size " + expectedSize );
            }
        };
    }

    public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> hasSize( final int expectedSize )
    {
        return new TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>>()
        {
            @Override
            protected boolean matchesSafely( Neo4jMatchers.Deferred<?> nodes, Description description )
            {
                int foundSize = nodes.collection().size();

                if ( foundSize != expectedSize )
                {
                    description.appendText( "found " + nodes.collection().toString() );
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "collection of size " + expectedSize );
            }
        };
    }

Replace Generic With Diamond TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> with TypeSafeDiagnosingMatcher<> in method public hasSize(expectedSize int) : TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<IndexDefinition>> haveState(
            final GraphDatabaseService db, final Schema.IndexState expectedState )
    {
        return new TypeSafeDiagnosingMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Neo4jMatchers.Deferred<IndexDefinition> indexes, Description description )
            {
                for ( IndexDefinition current : indexes.collection() )
                {
                    Schema.IndexState currentState = db.schema().getIndexState( current );
                    if ( !currentState.equals( expectedState ) )
                    {
                        description.appendValue( current ).appendText( " has state " ).appendValue( currentState );
                        if ( currentState == Schema.IndexState.FAILED )
                        {
                            String indexFailure = db.schema().getIndexFailure( current );
                            description.appendText( " has failure message: " ).appendText( indexFailure );
                        }
                        return false;
                    }
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "all indexes have state " + expectedState );
            }
        };
    }

    public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<IndexDefinition>> haveState(
            final GraphDatabaseService db, final Schema.IndexState expectedState )
    {
        return new TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<IndexDefinition>>()
        {
            @Override
            protected boolean matchesSafely( Neo4jMatchers.Deferred<IndexDefinition> indexes, Description description )
            {
                for ( IndexDefinition current : indexes.collection() )
                {
                    Schema.IndexState currentState = db.schema().getIndexState( current );
                    if ( !currentState.equals( expectedState ) )
                    {
                        description.appendValue( current ).appendText( " has state " ).appendValue( currentState );
                        if ( currentState == Schema.IndexState.FAILED )
                        {
                            String indexFailure = db.schema().getIndexFailure( current );
                            description.appendText( " has failure message: " ).appendText( indexFailure );
                        }
                        return false;
                    }
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "all indexes have state " + expectedState );
            }
        };
    }

Replace Generic With Diamond TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<IndexDefinition>> with TypeSafeDiagnosingMatcher<> in method public haveState(db GraphDatabaseService, expectedState Schema.IndexState) : TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<IndexDefinition>> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    @SafeVarargs
    public static <T> TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> contains( final T... expectedObjects )
    {
        return new TypeSafeDiagnosingMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Neo4jMatchers.Deferred<T> nodes, Description description )
            {
                Set<T> expected = asSet( expectedObjects );
                Set<T> found = Iterables.asSet( nodes.collection() );
                if ( !found.containsAll( expected ) )
                {
                    description.appendText( "found " + found.toString() );
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "contains " + asSet( expectedObjects ) );
            }
        };
    }

    @SafeVarargs
    public static <T> TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> contains( final T... expectedObjects )
    {
        return new TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>>()
        {
            @Override
            protected boolean matchesSafely( Neo4jMatchers.Deferred<T> nodes, Description description )
            {
                Set<T> expected = asSet( expectedObjects );
                Set<T> found = Iterables.asSet( nodes.collection() );
                if ( !found.containsAll( expected ) )
                {
                    description.appendText( "found " + found.toString() );
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "contains " + asSet( expectedObjects ) );
            }
        };
    }

Replace Generic With Diamond TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> with TypeSafeDiagnosingMatcher<> in method public contains(expectedObjects T...) : TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> isEmpty( )
    {
        return new TypeSafeDiagnosingMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Deferred<?> deferred, Description description )
            {
                Collection<?> collection = deferred.collection();
                if ( !collection.isEmpty() )
                {
                    description.appendText( "was " + collection.toString() );
                    return false;
                }

                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "empty collection" );
            }
        };
    }

    public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> isEmpty( )
    {
        return new TypeSafeDiagnosingMatcher<Deferred<?>>()
        {
            @Override
            protected boolean matchesSafely( Deferred<?> deferred, Description description )
            {
                Collection<?> collection = deferred.collection();
                if ( !collection.isEmpty() )
                {
                    description.appendText( "was " + collection.toString() );
                    return false;
                }

                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "empty collection" );
            }
        };
    }

Replace Generic With Diamond TypeSafeDiagnosingMatcher<Deferred<?>> with TypeSafeDiagnosingMatcher<> in method public isEmpty() : TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> from class org.neo4j.test.mockito.matcher.Neo4jMatchers


    static <T> Matcher<Iterable<T>> containsItem( Matcher<T> itemMatcher )
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Iterable<T> items )
            {
                for ( T item : items )
                {
                    if ( itemMatcher.matches( item ) )
                    {
                        return true;
                    }
                }
                return false;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "an iterable containing " ).appendDescriptionOf( itemMatcher );
            }
        };
    }

    <T> Matcher<Iterable<T>> containsItem( Matcher<T> itemMatcher )
    {
        return new TypeSafeMatcher<Iterable<T>>()
        {
            @Override
            protected boolean matchesSafely( Iterable<T> items )
            {
                for ( T item : items )
                {
                    if ( itemMatcher.matches( item ) )
                    {
                        return true;
                    }
                }
                return false;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "an iterable containing " ).appendDescriptionOf( itemMatcher );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<Iterable<T>> with TypeSafeMatcher<> in method package containsItem(itemMatcher Matcher<T>) : Matcher<Iterable<T>> from class org.neo4j.cypher.internal.javacompat.NotificationTestSupport


    static <T> Matcher<Iterable<T>> containsNoItem( Matcher<T> itemMatcher )
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Iterable<T> items )
            {
                for ( T item : items )
                {
                    if ( itemMatcher.matches( item ) )
                    {
                        return false;
                    }
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "an iterable not containing " ).appendDescriptionOf( itemMatcher );
            }
        };
    }

    <T> Matcher<Iterable<T>> containsNoItem( Matcher<T> itemMatcher )
    {
        return new TypeSafeMatcher<Iterable<T>>()
        {
            @Override
            protected boolean matchesSafely( Iterable<T> items )
            {
                for ( T item : items )
                {
                    if ( itemMatcher.matches( item ) )
                    {
                        return false;
                    }
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "an iterable not containing " ).appendDescriptionOf( itemMatcher );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<Iterable<T>> with TypeSafeMatcher<> in method package containsNoItem(itemMatcher Matcher<T>) : Matcher<Iterable<T>> from class org.neo4j.cypher.internal.javacompat.NotificationTestSupport


    static Matcher<Notification> notification( String code, Matcher<String> description, Matcher<InputPosition> position, SeverityLevel severity )
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( Notification item )
            {
                return code.equals( item.getCode() ) && description.matches( item.getDescription() ) && position.matches( item.getPosition() ) &&
                        severity.equals( item.getSeverity() );
            }

            @Override
            public void describeTo( Description target )
            {
                target.appendText( "Notification{code=" ).appendValue( code ).appendText( ", description=[" ).appendDescriptionOf( description ).appendText(
                        "], position=[" ).appendDescriptionOf( position ).appendText( "], severity=" ).appendValue( severity ).appendText( "}" );
            }
        };
    }

    protected Matcher<Notification> notification(
            String code,
            Matcher<String> description,
            Matcher<InputPosition> position,
            SeverityLevel severity )
    {
        return new TypeSafeMatcher<Notification>()
        {
            @Override
            protected boolean matchesSafely( Notification item )
            {
                return code.equals( item.getCode() ) &&
                       description.matches( item.getDescription() ) &&
                       position.matches( item.getPosition() ) &&
                       severity.equals( item.getSeverity() );
            }

            @Override
            public void describeTo( Description target )
            {
                target.appendText( "Notification{code=" ).appendValue( code )
                        .appendText( ", description=[" ).appendDescriptionOf( description )
                        .appendText( "], position=[" ).appendDescriptionOf( position )
                        .appendText( "], severity=" ).appendValue( severity )
                        .appendText( "}" );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<Notification> with TypeSafeMatcher<> in method package notification(code String, description Matcher<String>, position Matcher<InputPosition>, severity SeverityLevel) : Matcher<Notification> from class org.neo4j.cypher.internal.javacompat.NotificationTestSupport


    private static <T> Stream<T> toStream( PrimitiveLongResourceIterator iterator, LongFunction<T> mapper )
    {
        Iterator<T> it = new Iterator<>()
        {
            @Override
            public boolean hasNext()
            {
                return iterator.hasNext();
            }

            @Override
            public T next()
            {
                return mapper.apply( iterator.next() );
            }
        };

        return Iterators.stream( it, Spliterator.ORDERED );
    }

    private static <T> Stream<T> toStream( PrimitiveLongResourceIterator iterator, LongFunction<T> mapper )
    {
        Iterator<T> it = new Iterator<T>()
        {
            @Override
            public boolean hasNext()
            {
                return iterator.hasNext();
            }

            @Override
            public T next()
            {
                return mapper.apply( iterator.next() );
            }
        };

        return Iterators.stream( it, Spliterator.ORDERED );
    }

Replace Generic With Diamond Iterator<T> with Iterator<> in method private toStream(iterator PrimitiveLongResourceIterator, mapper LongFunction<T>) : Stream<T> from class org.neo4j.procedure.builtin.BuiltInProcedures


            @Override
            public <FAILURE extends Exception> StoreScan<FAILURE> visitNodes( int[] labelIds, IntPredicate propertyKeyIdFilter,
                    Visitor<EntityUpdates,FAILURE> propertyUpdateVisitor, Visitor<NodeLabelUpdate,FAILURE> labelUpdateVisitor, boolean forceStoreScan )
            {
                return new StoreScan<>()
                {
                    @Override
                    public void run()
                    {
                        throw new RuntimeException( "Just failing" );
                    }

                    @Override
                    public void stop()
                    {
                    }

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

                    @Override
                    public PopulationProgress getProgress()
                    {
                        return null;
                    }
                };
            }

            @Override
            public <FAILURE extends Exception> StoreScan<FAILURE> visitNodes( int[] labelIds, IntPredicate propertyKeyIdFilter,
                    Visitor<EntityUpdates,FAILURE> propertyUpdateVisitor, Visitor<NodeLabelUpdate,FAILURE> labelUpdateVisitor, boolean forceStoreScan )
            {
                return new StoreScan<FAILURE>()
                {
                    @Override
                    public void run()
                    {
                        throw new RuntimeException( "Just failing" );
                    }

                    @Override
                    public void stop()
                    {
                    }

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

                    @Override
                    public PopulationProgress getProgress()
                    {
                        return null;
                    }
                };
            }

Replace Generic With Diamond StoreScan<FAILURE> with StoreScan<> in method public visitNodes(labelIds int[], propertyKeyIdFilter IntPredicate, propertyUpdateVisitor Visitor<EntityUpdates,FAILURE>, labelUpdateVisitor Visitor<NodeLabelUpdate,FAILURE>, forceStoreScan boolean) : StoreScan<FAILURE> from class org.neo4j.kernel.impl.api.index.IndexPopulationJobTest.shouldCloseMultiPopulatorOnFailedPopulation.failingStoreView.new IndexStoreView.Adaptor


    @Test
    void shouldCloseMultiPopulatorOnFailedPopulation()
    {
        // given
        NullLogProvider logProvider = NullLogProvider.getInstance();
        IndexStoreView failingStoreView = new IndexStoreView.Adaptor()
        {
            @Override
            public <FAILURE extends Exception> StoreScan<FAILURE> visitNodes( int[] labelIds, IntPredicate propertyKeyIdFilter,
                    Visitor<EntityUpdates,FAILURE> propertyUpdateVisitor, Visitor<NodeLabelUpdate,FAILURE> labelUpdateVisitor, boolean forceStoreScan )
            {
                return new StoreScan<>()
                {
                    @Override
                    public void run()
                    {
                        throw new RuntimeException( "Just failing" );
                    }

                    @Override
                    public void stop()
                    {
                    }

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

                    @Override
                    public PopulationProgress getProgress()
                    {
                        return null;
                    }
                };
            }
        };
        TrackingMultipleIndexPopulator populator = new TrackingMultipleIndexPopulator( failingStoreView, logProvider, EntityType.NODE,
                new DatabaseSchemaState( logProvider ), mock( IndexStatisticsStore.class ) );
        IndexPopulationJob populationJob = new IndexPopulationJob( populator, NO_MONITOR, false );

        // when
        populationJob.run();

        // then
        assertTrue( populator.closed );
    }

    @Test
    void shouldCloseMultiPopulatorOnFailedPopulation()
    {
        // given
        NullLogProvider logProvider = NullLogProvider.getInstance();
        IndexStoreView failingStoreView = new IndexStoreView.Adaptor()
        {
            @Override
            public <FAILURE extends Exception> StoreScan<FAILURE> visitNodes( int[] labelIds, IntPredicate propertyKeyIdFilter,
                    Visitor<EntityUpdates,FAILURE> propertyUpdateVisitor, Visitor<NodeLabelUpdate,FAILURE> labelUpdateVisitor, boolean forceStoreScan )
            {
                return new StoreScan<FAILURE>()
                {
                    @Override
                    public void run()
                    {
                        throw new RuntimeException( "Just failing" );
                    }

                    @Override
                    public void stop()
                    {
                    }

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

                    @Override
                    public PopulationProgress getProgress()
                    {
                        return null;
                    }
                };
            }
        };
        TrackingMultipleIndexPopulator populator = new TrackingMultipleIndexPopulator( failingStoreView, logProvider, EntityType.NODE,
                new DatabaseSchemaState( logProvider ), mock( IndexStatisticsStore.class ) );
        IndexPopulationJob populationJob = new IndexPopulationJob( populator, NO_MONITOR, false );

        // when
        populationJob.run();

        // then
        assertTrue( populator.closed );
    }

Replace Generic With Diamond StoreScan<FAILURE> with StoreScan<> in method package shouldCloseMultiPopulatorOnFailedPopulation() : void from class org.neo4j.kernel.impl.api.index.IndexPopulationJobTest


    private static Matcher<String> hasExpectedFormat()
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            public boolean matchesSafely( String item )
            {
                return item.trim().split( " " ).length > 1;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "message of valid format" );
            }
        };
    }

    private static Matcher<String> hasExpectedFormat()
    {
        return new TypeSafeMatcher<String>()
        {
            @Override
            public boolean matchesSafely( String item )
            {
                return item.trim().split( " " ).length > 1;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "message of valid format" );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<String> with TypeSafeMatcher<> in method private hasExpectedFormat() : Matcher<String> from class org.neo4j.consistency.report.ConsistencyReporterTest


    StoreScan<IndexPopulationFailedKernelException> indexAllEntities()
    {
        int[] entityTokenIds = entityTokenIds();
        int[] propertyKeyIds = propertyKeyIds();
        IntPredicate propertyKeyIdFilter = propertyKeyId -> contains( propertyKeyIds, propertyKeyId );

        if ( type == EntityType.RELATIONSHIP )
        {
            storeScan = storeView.visitRelationships( entityTokenIds, propertyKeyIdFilter, new EntityPopulationVisitor() );
        }
        else
        {
            storeScan = storeView.visitNodes( entityTokenIds, propertyKeyIdFilter, new EntityPopulationVisitor(), null, false );
        }
        storeScan.setPhaseTracker( phaseTracker );
        return new DelegatingStoreScan<>( storeScan )
        {
            @Override
            public void run() throws IndexPopulationFailedKernelException
            {
                super.run();
                flushAll();
            }
        };
    }

    StoreScan<IndexPopulationFailedKernelException> indexAllEntities()
    {
        int[] entityTokenIds = entityTokenIds();
        int[] propertyKeyIds = propertyKeyIds();
        IntPredicate propertyKeyIdFilter = propertyKeyId -> contains( propertyKeyIds, propertyKeyId );

        if ( type == EntityType.RELATIONSHIP )
        {
            storeScan = storeView.visitRelationships( entityTokenIds, propertyKeyIdFilter, new EntityPopulationVisitor() );
        }
        else
        {
            storeScan = storeView.visitNodes( entityTokenIds, propertyKeyIdFilter, new EntityPopulationVisitor(), null, false );
        }
        storeScan.setPhaseTracker( phaseTracker );
        return new DelegatingStoreScan<IndexPopulationFailedKernelException>( storeScan )
        {
            @Override
            public void run() throws IndexPopulationFailedKernelException
            {
                super.run();
                flushAll();
            }
        };
    }

Replace Generic With Diamond DelegatingStoreScan<IndexPopulationFailedKernelException> with DelegatingStoreScan<> in method package indexAllEntities() : StoreScan<IndexPopulationFailedKernelException> from class org.neo4j.kernel.impl.api.index.MultipleIndexPopulator


    private RawIterator<AnyValue[],ProcedureException> createIterator( SecurityContext procedureSecurityContext,
            RawIterator<AnyValue[],ProcedureException> procedureCall )
    {
        return new RawIterator<>()
        {
            @Override
            public boolean hasNext() throws ProcedureException
            {
                try ( KernelTransaction.Revertable ignore = ktx.overrideWith( procedureSecurityContext ) )
                {
                    return procedureCall.hasNext();
                }
            }

            @Override
            public AnyValue[] next() throws ProcedureException
            {
                try ( KernelTransaction.Revertable ignore = ktx.overrideWith( procedureSecurityContext ) )
                {
                    return procedureCall.next();
                }
            }
        };
    }

    private RawIterator<AnyValue[],ProcedureException> createIterator( SecurityContext procedureSecurityContext,
            RawIterator<AnyValue[],ProcedureException> procedureCall )
    {
        return new RawIterator<AnyValue[],ProcedureException>()
        {
            @Override
            public boolean hasNext() throws ProcedureException
            {
                try ( KernelTransaction.Revertable ignore = ktx.overrideWith( procedureSecurityContext ) )
                {
                    return procedureCall.hasNext();
                }
            }

            @Override
            public AnyValue[] next() throws ProcedureException
            {
                try ( KernelTransaction.Revertable ignore = ktx.overrideWith( procedureSecurityContext ) )
                {
                    return procedureCall.next();
                }
            }
        };
    }

Replace Generic With Diamond RawIterator<AnyValue[],ProcedureException> with RawIterator<> in method private createIterator(procedureSecurityContext SecurityContext, procedureCall RawIterator<AnyValue[],ProcedureException>) : RawIterator<AnyValue[],ProcedureException> from class org.neo4j.kernel.impl.newapi.AllStoreHolder


    private RecordProxy<NeoStoreRecord, Void> getOrLoadNeoStoreRecord()
    {
        // TODO Move this neo store record thingie into RecordAccessSet
        if ( neoStoreRecord == null )
        {
            neoStoreRecord = new RecordChanges<>( new RecordChanges.Loader<>()
            {
                @Override
                public NeoStoreRecord newUnused( long key, Void additionalData )
                {
                    throw new UnsupportedOperationException();
                }

                @Override
                public NeoStoreRecord load( long key, Void additionalData )
                {
                    return metaDataStore.graphPropertyRecord();
                }

                @Override
                public void ensureHeavy( NeoStoreRecord record )
                {
                }

                @Override
                public NeoStoreRecord clone( NeoStoreRecord neoStoreRecord ) throws CloneNotSupportedException
                {
                    return neoStoreRecord.clone();
                }
            }, new IntCounter() );
        }
        return neoStoreRecord.getOrLoad( 0L, null );
    }

    private RecordProxy<NeoStoreRecord, Void> getOrLoadNeoStoreRecord()
    {
        // TODO Move this neo store record thingie into RecordAccessSet
        if ( neoStoreRecord == null )
        {
            neoStoreRecord = new RecordChanges<>( new RecordChanges.Loader<NeoStoreRecord, Void>()
            {
                @Override
                public NeoStoreRecord newUnused( long key, Void additionalData )
                {
                    throw new UnsupportedOperationException();
                }

                @Override
                public NeoStoreRecord load( long key, Void additionalData )
                {
                    return metaDataStore.graphPropertyRecord();
                }

                @Override
                public void ensureHeavy( NeoStoreRecord record )
                {
                }

                @Override
                public NeoStoreRecord clone( NeoStoreRecord neoStoreRecord ) throws CloneNotSupportedException
                {
                    return neoStoreRecord.clone();
                }
            }, new IntCounter() );
        }
        return neoStoreRecord.getOrLoad( 0L, null );
    }

Replace Generic With Diamond RecordChanges<> with RecordChanges<> in method private getOrLoadNeoStoreRecord() : RecordProxy<NeoStoreRecord,Void> from class org.neo4j.internal.recordstorage.TransactionRecordState


    private CountsTracker openCountsStore( FileSystemAbstraction fs, PageCache pageCache, DatabaseLayout layout, Config config, LogProvider logProvider,
            VersionContextSupplier versionContextSupplier )
    {
        boolean readOnly = config.get( GraphDatabaseSettings.read_only );
        CountsTracker counts = readOnly
                               ? new ReadOnlyCountsTracker( logProvider, fs, pageCache, config, layout )
                               : new CountsTracker( logProvider, fs, pageCache, config, layout, versionContextSupplier );
        counts.setInitializer( new DataInitializer<>()
        {
            private final Log log = logProvider.getLog( MetaDataStore.class );

            @Override
            public void initialize( CountsAccessor.Updater updater )
            {
                log.warn( "Missing counts store, rebuilding it." );
                new CountsComputer( neoStores, pageCache, layout ).initialize( updater );
                log.warn( "Counts store rebuild completed." );
            }

            @Override
            public long initialVersion()
            {
                return neoStores.getMetaDataStore().getLastCommittedTransactionId();
            }
        } );
        return counts;
    }

    private CountsTracker openCountsStore( FileSystemAbstraction fs, PageCache pageCache, DatabaseLayout layout, Config config, LogProvider logProvider,
            VersionContextSupplier versionContextSupplier )
    {
        boolean readOnly = config.get( GraphDatabaseSettings.read_only );
        CountsTracker counts = readOnly
                               ? new ReadOnlyCountsTracker( logProvider, fs, pageCache, config, layout )
                               : new CountsTracker( logProvider, fs, pageCache, config, layout, versionContextSupplier );
        counts.setInitializer( new DataInitializer<CountsAccessor.Updater>()
        {
            private final Log log = logProvider.getLog( MetaDataStore.class );

            @Override
            public void initialize( CountsAccessor.Updater updater )
            {
                log.warn( "Missing counts store, rebuilding it." );
                new CountsComputer( neoStores, pageCache, layout ).initialize( updater );
                log.warn( "Counts store rebuild completed." );
            }

            @Override
            public long initialVersion()
            {
                return neoStores.getMetaDataStore().getLastCommittedTransactionId();
            }
        } );
        return counts;
    }

Replace Generic With Diamond DataInitializer<CountsAccessor.Updater> with DataInitializer<> in method private openCountsStore(fs FileSystemAbstraction, pageCache PageCache, layout DatabaseLayout, config Config, logProvider LogProvider, versionContextSupplier VersionContextSupplier) : CountsTracker from class org.neo4j.internal.recordstorage.RecordStorageEngine


    @Test
    void shouldNotCountRelationshipsCreatedInOtherTransaction() throws Exception
    {
        // given
        final Barrier.Control barrier = new Barrier.Control();
        long before = numberOfRelationships();
        Future<Long> tx = executor.submit( () ->
        {
            try ( Transaction txn = db.beginTx() )
            {
                Node node = db.createNode();
                node.createRelationshipTo( db.createNode(), withName( "KNOWS" ) );
                node.createRelationshipTo( db.createNode(), withName( "KNOWS" ) );
                long whatThisThreadSees = countsForRelationship( null, null, null );
                barrier.reached();
                txn.success();
                return whatThisThreadSees;
            }
        } );
        barrier.await();

        // when
        long during = numberOfRelationships();
        barrier.release();
        long whatOtherThreadSees = tx.get();
        long after = numberOfRelationships();

        // then
        assertEquals( 0, before );
        assertEquals( 0, during );
        assertEquals( 2, after );
        assertEquals( after, whatOtherThreadSees );
    }

    @Test
    public void shouldNotCountRelationshipsCreatedInOtherTransaction() throws Exception
    {
        // given
        GraphDatabaseService graphDb = db.getGraphDatabaseAPI();
        final Barrier.Control barrier = new Barrier.Control();
        long before = numberOfRelationships();
        Future<Long> tx = threading.execute( new NamedFunction<GraphDatabaseService, Long>( "create-relationships" )
        {
            @Override
            public Long apply( GraphDatabaseService graphDb )
            {
                try ( Transaction tx = graphDb.beginTx() )
                {
                    Node node = graphDb.createNode();
                    node.createRelationshipTo( graphDb.createNode(), withName( "KNOWS" ) );
                    node.createRelationshipTo( graphDb.createNode(), withName( "KNOWS" ) );
                    long whatThisThreadSees = countsForRelationship( null, null, null );
                    barrier.reached();
                    tx.success();
                    return whatThisThreadSees;
                }
            }
        }, graphDb );
        barrier.await();

        // when
        long during = numberOfRelationships();
        barrier.release();
        long whatOtherThreadSees = tx.get();
        long after = numberOfRelationships();

        // then
        assertEquals( 0, before );
        assertEquals( 0, during );
        assertEquals( 2, after );
        assertEquals( after, whatOtherThreadSees );
    }

Replace Anonymous With Lambda org.neo4j.kernel.counts.RelationshipCountsTest.shouldNotCountRelationshipsCreatedInOtherTransaction.tx.execute.new NamedFunction<GraphDatabaseService,Long> with () -> {try(Transaction txn=db.beginTx())Node node=db.createNode(); in method package shouldNotCountRelationshipsCreatedInOtherTransaction() : void from class org.neo4j.kernel.counts.RelationshipCountsTest


    private static Iterable<boolean[]> permutations( final int size )
    {
        final int max = 1 << size;
        return () -> new PrefetchingIterator<>()
        {
            int pos;

            @Override
            protected boolean[] fetchNextOrNull()
            {
                if ( pos < max )
                {
                    int cur = pos++;
                    boolean[] result = new boolean[size];
                    for ( int i = 0; i < size; i++ )
                    {
                        result[i] = (cur & 1) == 1;
                        cur >>= 1;
                    }
                    return result;
                }
                return null;
            }
        };
    }

    private static Iterable<boolean[]> permutations( final int size )
    {
        final int max = 1 << size;
        return () -> new PrefetchingIterator<boolean[]>()
        {
            int pos;

            @Override
            protected boolean[] fetchNextOrNull()
            {
                if ( pos < max )
                {
                    int cur = pos++;
                    boolean[] result = new boolean[size];
                    for ( int i = 0; i < size; i++ )
                    {
                        result[i] = (cur & 1) == 1;
                        cur >>= 1;
                    }
                    return result;
                }
                return null;
            }
        };
    }

Replace Generic With Diamond PrefetchingIterator<boolean[]> with PrefetchingIterator<> in method private permutations(size int) : Iterable<boolean[]> from class org.neo4j.kernel.impl.core.TestLoopRelationships


    public static Matcher<Exception> exception( Class<? extends Exception> type, Matcher<String> message )
    {
        return new TypeSafeMatcher<>( type )
        {
            @Override
            protected boolean matchesSafely( Exception item )
            {
                return message.matches( item.getMessage() );
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "Exception of type " ).appendValue( type.getName() ).appendText( " with message " ).appendDescriptionOf( message );
            }
        };
    }

    public static Matcher<Exception> exception( Class<? extends Exception> type, Matcher<String> message )
    {
        return new TypeSafeMatcher<Exception>( type )
        {
            @Override
            protected boolean matchesSafely( Exception item )
            {
                return message.matches( item.getMessage() );
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "Exception of type " ).appendValue( type.getName() )
                        .appendText( " with message " ).appendDescriptionOf( message );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<Exception> with TypeSafeMatcher<> in method public exception(type Class<? extends Exception>, message Matcher<String>) : Matcher<Exception> from class org.neo4j.values.storable.AssertingStructureBuilder


    @Test
    void withState()
    {
        /* Graph
         *
         * (a)-[1]->(b)-[2]->(c)-[5]->(d)
         */

        graph.makeEdgeChain( "a,b,c,d" );
        setWeight( "a", "b", 1 );
        setWeight( "b", "c", 2 );
        setWeight( "c", "d", 5 );

        InitialBranchState<Integer> state = new InitialBranchState.State<>( 0, 0 );
        final Map<Node, Integer> encounteredState = new HashMap<>();
        PathExpander<Integer> expander = new PathExpander<>()
        {
            @Override
            public Iterable<Relationship> expand( Path path, BranchState<Integer> state )
            {
                if ( path.length() > 0 )
                {
                    int newState = state.getState() + ((Number)path.lastRelationship().getProperty( "weight" )).intValue();
                    state.setState( newState );
                    encounteredState.put( path.endNode(), newState );
                }
                return path.endNode().getRelationships();
            }

            @Override
            public PathExpander<Integer> reverse()
            {
                return this;
            }
        };

        PathFinder<WeightedPath> finder = new Dijkstra( expander, state,
                CommonEvaluators.doubleCostEvaluator( "weight" ) );
        assertPaths(finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) ),
                "a,b,c,d" );
        assertEquals( 1, encounteredState.get( graph.getNode( "b" ) ).intValue() );
        assertEquals( 3, encounteredState.get( graph.getNode( "c" ) ).intValue() );
        assertEquals( 8, encounteredState.get( graph.getNode( "d" ) ).intValue() );
    }

    @Test
    public void withState()
    {
        /* Graph
         *
         * (a)-[1]->(b)-[2]->(c)-[5]->(d)
         */

        graph.makeEdgeChain( "a,b,c,d" );
        setWeight( "a", "b", 1 );
        setWeight( "b", "c", 2 );
        setWeight( "c", "d", 5 );

        InitialBranchState<Integer> state = new InitialBranchState.State<>( 0, 0 );
        final Map<Node, Integer> encounteredState = new HashMap<>();
        PathExpander<Integer> expander = new PathExpander<Integer>()
        {
            @Override
            public Iterable<Relationship> expand( Path path, BranchState<Integer> state )
            {
                if ( path.length() > 0 )
                {
                    int newState = state.getState() + ((Number)path.lastRelationship().getProperty( "weight" )).intValue();
                    state.setState( newState );
                    encounteredState.put( path.endNode(), newState );
                }
                return path.endNode().getRelationships();
            }

            @Override
            public PathExpander<Integer> reverse()
            {
                return this;
            }
        };

        PathFinder<WeightedPath> finder = new Dijkstra( expander, state,
                CommonEvaluators.doubleCostEvaluator( "weight" ) );
        assertPaths(finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) ),
                "a,b,c,d" );
        assertEquals( 1, encounteredState.get( graph.getNode( "b" ) ).intValue() );
        assertEquals( 3, encounteredState.get( graph.getNode( "c" ) ).intValue() );
        assertEquals( 8, encounteredState.get( graph.getNode( "d" ) ).intValue() );
    }

Replace Generic With Diamond PathExpander<Integer> with PathExpander<> in method package withState() : void from class org.neo4j.graphalgo.path.DijkstraIncreasingWeightTest


    private static List<Long> extractPrimitiveLongIteratorAsList( PrimitiveLongResourceIterator longIterator )
    {
        try ( longIterator )
        {
            List<Long> actualNodeIds = new ArrayList<>();
            while ( longIterator.hasNext() )
            {
                actualNodeIds.add( longIterator.next() );
            }
            return actualNodeIds;
        }
    }

    private List<Long> extractPrimitiveLongIteratorAsList( PrimitiveLongResourceIterator longIterator )
    {
        try
        {
            List<Long> actualNodeIds = new ArrayList<>();
            while ( longIterator.hasNext() )
            {
                actualNodeIds.add( longIterator.next() );
            }
            return actualNodeIds;
        }
        finally
        {
            longIterator.close();
        }
    }

Try With Resources try(longIterator) in method private extractPrimitiveLongIteratorAsList(longIterator PrimitiveLongResourceIterator) : List<Long> from class org.neo4j.batchinsert.internal.BatchInsertTest


    @Test
    void shouldPanicOnFailure() throws Exception
    {
        // GIVEN
        SimpleStageControl control = new SimpleStageControl();
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        Exception testPanic = new RuntimeException();
        ForkedProcessorStep<Void> step = new ForkedProcessorStep<>( control, "Processor",
            config( availableProcessors ) )
        {
            @Override
            protected void forkedProcess( int id, int processors, Void batch ) throws Throwable
            {
                throw testPanic;
            }
        };

        // WHEN
        step.start( 0 );
        step.receive( 1, null );
        control.steps( step );

        // THEN
        step.awaitCompleted();
        try
        {
            control.assertHealthy();
        }
        catch ( Exception e )
        {
            assertSame( testPanic, e );
        }
    }

    @Test
    public void shouldPanicOnFailure() throws Exception
    {
        // GIVEN
        SimpleStageControl control = new SimpleStageControl();
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        Exception testPanic = new RuntimeException();
        ForkedProcessorStep<Void> step = new ForkedProcessorStep<Void>( control, "Processor",
                config( availableProcessors ) )
        {
            @Override
            protected void forkedProcess( int id, int processors, Void batch ) throws Throwable
            {
                throw testPanic;
            }
        };

        // WHEN
        step.start( 0 );
        step.receive( 1, null );
        control.steps( step );

        // THEN
        step.awaitCompleted();
        try
        {
            control.assertHealthy();
        }
        catch ( Exception e )
        {
            assertSame( testPanic, e );
        }
    }

Replace Generic With Diamond ForkedProcessorStep<Void> with ForkedProcessorStep<> in method package shouldPanicOnFailure() : void from class org.neo4j.internal.batchimport.staging.ForkedProcessorStepTest


    private static Iterator<PropertyBlock> blocksOf( PropertyCreator creator, Value[] values )
    {
        return new IteratorWrapper<>( iterator( values ) )
        {
            int key;

            @Override
            protected PropertyBlock underlyingObjectToObject( Value value )
            {
                return creator.encodePropertyValue( key++, value );
            }
        };
    }

    private Iterator<PropertyBlock> blocksOf( PropertyCreator creator, Value[] values )
    {
        return new IteratorWrapper<PropertyBlock,Value>( iterator( values ) )
        {
            int key;

            @Override
            protected PropertyBlock underlyingObjectToObject( Value value )
            {
                return creator.encodePropertyValue( key++, value );
            }
        };
    }

Replace Generic With Diamond IteratorWrapper<PropertyBlock,Value> with IteratorWrapper<> in method private blocksOf(creator PropertyCreator, values Value[]) : Iterator<PropertyBlock> from class org.neo4j.internal.recordstorage.RecordPropertyCursorTest


    private static long[] calculatePageCacheFileSize( DatabaseLayout databaseLayout ) throws IOException
    {
        MutableLong pageCacheTotal = new MutableLong();
        MutableLong luceneTotal = new MutableLong();
        for ( StoreType storeType : StoreType.values() )
        {
            long length = databaseLayout.file( storeType.getDatabaseFile() ).mapToLong( File::length ).sum();
            pageCacheTotal.add( length );
        }

        File indexFolder = IndexDirectoryStructure.baseSchemaIndexFolder( databaseLayout.databaseDirectory() );
        if ( indexFolder.exists() )
        {
            Files.walkFileTree( indexFolder.toPath(), new SimpleFileVisitor<>()
            {
                @Override
                public FileVisitResult visitFile( Path path, BasicFileAttributes attrs )
                {
                    File file = path.toFile();
                    Path name = path.getName( path.getNameCount() - 3 );
                    boolean isLuceneFile = (path.getNameCount() >= 3 && name.toString().startsWith( "lucene-" )) ||
                            (path.getNameCount() >= 4 && path.getName( path.getNameCount() - 4 ).toString().equals( "lucene" ));
                    if ( !FailureStorage.DEFAULT_FAILURE_FILE_NAME.equals( file.getName() ) )
                    {
                        (isLuceneFile ? luceneTotal : pageCacheTotal).add( file.length() );
                    }
                    return FileVisitResult.CONTINUE;
                }
            } );
        }
        pageCacheTotal.add( databaseLayout.labelScanStore().length() );
        return new long[]{pageCacheTotal.longValue(), luceneTotal.longValue()};
    }

    private static long[] calculatePageCacheFileSize( DatabaseLayout databaseLayout ) throws IOException
    {
        MutableLong pageCacheTotal = new MutableLong();
        MutableLong luceneTotal = new MutableLong();
        for ( StoreType storeType : StoreType.values() )
        {
            long length = databaseLayout.file( storeType.getDatabaseFile() ).mapToLong( File::length ).sum();
            pageCacheTotal.add( length );
        }

        File indexFolder = IndexDirectoryStructure.baseSchemaIndexFolder( databaseLayout.databaseDirectory() );
        if ( indexFolder.exists() )
        {
            Files.walkFileTree( indexFolder.toPath(), new SimpleFileVisitor<Path>()
            {
                @Override
                public FileVisitResult visitFile( Path path, BasicFileAttributes attrs )
                {
                    File file = path.toFile();
                    Path name = path.getName( path.getNameCount() - 3 );
                    boolean isLuceneFile = (path.getNameCount() >= 3 && name.toString().startsWith( "lucene-" )) ||
                            (path.getNameCount() >= 4 && path.getName( path.getNameCount() - 4 ).toString().equals( "lucene" ));
                    if ( !FailureStorage.DEFAULT_FAILURE_FILE_NAME.equals( file.getName() ) )
                    {
                        (isLuceneFile ? luceneTotal : pageCacheTotal).add( file.length() );
                    }
                    return FileVisitResult.CONTINUE;
                }
            } );
        }
        pageCacheTotal.add( databaseLayout.labelScanStore().length() );
        return new long[]{pageCacheTotal.longValue(), luceneTotal.longValue()};
    }

Replace Generic With Diamond SimpleFileVisitor<Path> with SimpleFileVisitor<> in method private calculatePageCacheFileSize(databaseLayout DatabaseLayout) : long[] from class org.neo4j.commandline.dbms.MemoryRecommendationsCommandTest


    private static Iterable<DataFactory>
    relationshipData( final Charset encoding, Collection<Args.Option<File[]>> relationshipsFiles )
    {
        return new IterableWrapper<>( relationshipsFiles )
        {
            @Override
            protected DataFactory underlyingObjectToObject( Args.Option<File[]> group )
            {
                return data( defaultRelationshipType( group.metadata() ), encoding, group.value() );
            }
        };
    }

    public static Iterable<DataFactory>
            relationshipData( final Charset encoding, Collection<Option<File[]>> relationshipsFiles )
    {
        return new IterableWrapper<DataFactory,Option<File[]>>( relationshipsFiles )
        {
            @Override
            protected DataFactory underlyingObjectToObject( Option<File[]> group )
            {
                return data( defaultRelationshipType( group.metadata() ), encoding, group.value() );
            }
        };
    }

Replace Generic With Diamond IterableWrapper<DataFactory,Option<File[]>> with IterableWrapper<> in method private relationshipData(encoding Charset, relationshipsFiles Collection<Args.Option<File[]>>) : Iterable<DataFactory> from class org.neo4j.importer.CsvImporter


    private static Iterable<DataFactory> nodeData( final Charset encoding,
            Collection<Args.Option<File[]>> nodesFiles )
    {
        return new IterableWrapper<>( nodesFiles )
        {
            @Override
            protected DataFactory underlyingObjectToObject( Args.Option<File[]> input )
            {
                Decorator decorator = input.metadata() != null
                                      ? additiveLabels( input.metadata().split( ":" ) )
                                      : NO_DECORATOR;
                return data( decorator, encoding, input.value() );
            }
        };
    }

    public static Iterable<DataFactory> nodeData( final Charset encoding,
            Collection<Option<File[]>> nodesFiles )
    {
        return new IterableWrapper<DataFactory,Option<File[]>>( nodesFiles )
        {
            @Override
            protected DataFactory underlyingObjectToObject( Option<File[]> input )
            {
                Decorator decorator = input.metadata() != null
                        ? additiveLabels( input.metadata().split( ":" ) )
                        : NO_DECORATOR;
                return data( decorator, encoding, input.value() );
            }
        };
    }

Replace Generic With Diamond IterableWrapper<DataFactory,Option<File[]>> with IterableWrapper<> in method private nodeData(encoding Charset, nodesFiles Collection<Args.Option<File[]>>) : Iterable<DataFactory> from class org.neo4j.importer.CsvImporter


        @Override
        public Iterator<AnyValue> iterator()
        {
            switch ( inner.iterationPreference() )
            {
            case RANDOM_ACCESS:
                return super.iterator();
            case ITERATION:
                return new PrefetchingIterator<>()
                {
                    private int count;
                    private Iterator<AnyValue> innerIterator = inner.iterator();

                    @Override
                    protected AnyValue fetchNextOrNull()
                    {
                        //make sure we are at least at first element
                        while ( count < from && innerIterator.hasNext() )
                        {
                            innerIterator.next();
                            count++;
                        }
                        //check if we are done
                        if ( count < from || count >= to || !innerIterator.hasNext() )
                        {
                            return null;
                        }
                        //take the next step
                        count++;
                        return innerIterator.next();
                    }
                };

            default:
                throw new IllegalStateException( "unknown iteration preference" );
            }
        }

        @Override
        public Iterator<AnyValue> iterator()
        {
            switch ( inner.iterationPreference() )
            {
            case RANDOM_ACCESS:
                return super.iterator();
            case ITERATION:
                return new PrefetchingIterator<AnyValue>()
                {
                    private int count;
                    private Iterator<AnyValue> innerIterator = inner.iterator();

                    @Override
                    protected AnyValue fetchNextOrNull()
                    {
                        //make sure we are at least at first element
                        while ( count < from && innerIterator.hasNext() )
                        {
                            innerIterator.next();
                            count++;
                        }
                        //check if we are done
                        if ( count < from || count >= to || !innerIterator.hasNext() )
                        {
                            return null;
                        }
                        //take the next step
                        count++;
                        return innerIterator.next();
                    }
                };

            default:
                throw new IllegalStateException( "unknown iteration preference" );
            }
        }

Replace Generic With Diamond PrefetchingIterator<AnyValue> with PrefetchingIterator<> in method public iterator() : Iterator<AnyValue> from class org.neo4j.values.virtual.ListValue.ListSlice


    @Override
    public Iterator<AnyValue> iterator()
    {
        return new Iterator<>()
        {
            private int count;

            @Override
            public boolean hasNext()
            {
                return count < size();
            }

            @Override
            public AnyValue next()
            {
                if ( !hasNext() )
                {
                    throw new NoSuchElementException();
                }
                return value( count++ );
            }
        };
    }

    @Override
    public Iterator<AnyValue> iterator()
    {
        return new Iterator<AnyValue>()
        {
            private int count;

            @Override
            public boolean hasNext()
            {
                return count < size();
            }

            @Override
            public AnyValue next()
            {
                if ( !hasNext() )
                {
                    throw new NoSuchElementException();
                }
                return value( count++ );
            }
        };
    }

Replace Generic With Diamond Iterator<AnyValue> with Iterator<> in method public iterator() : Iterator<AnyValue> from class org.neo4j.values.virtual.ListValue


    /**
     * There are two files: sourceFile and targetFile. Blocks are merged, mergeFactor at the time, from source to target. When all blocks from source have
     * been merged into a larger block one merge iteration is done and source and target are flipped. As long as source contain more than a single block more
     * merge iterations are needed and we start over again.
     * When source only contain a single block we are finished and the extra file is deleted and {@link #blockFile} contains the result with a single sorted
     * block.
     *
     * See {@link #performSingleMerge(int, BlockReader, StoreChannel, Cancellation, ByteBuffer[], ByteBuffer)} for further details.
     *
     * @param mergeFactor See {@link #performSingleMerge(int, BlockReader, StoreChannel, Cancellation, ByteBuffer[], ByteBuffer)}.
     * @param cancellation Injected so that this merge can be cancelled, if an external request to do that comes in.
     * A cancelled merge will leave the same end state file/channel-wise, just not quite completed, which is fine because the merge
     * was cancelled meaning that the result will not be used for anything other than deletion.
     * @throws IOException If something goes wrong when reading from file.
     */
    public void merge( int mergeFactor, Cancellation cancellation ) throws IOException
    {
        monitor.mergeStarted( entryCount, calculateNumberOfEntriesWrittenDuringMerges( entryCount, numberOfBlocksInCurrentFile, mergeFactor ) );
        File sourceFile = blockFile;
        File tempFile = new File( blockFile.getParent(), blockFile.getName() + ".b" );
        try ( Allocator mergeBufferAllocator = bufferFactory.newLocalAllocator() )
        {
            File targetFile = tempFile;

            // Allocate all buffers that will be used and reused for all merge iterations
            ByteBuffer writeBuffer = mergeBufferAllocator.allocate( bufferFactory.bufferSize() );
            ByteBuffer[] readBuffers = new ByteBuffer[mergeFactor];
            for ( int i = 0; i < readBuffers.length; i++ )
            {
                readBuffers[i] = mergeBufferAllocator.allocate( bufferFactory.bufferSize() );
            }

            while ( numberOfBlocksInCurrentFile > 1 )
            {
                // Perform one complete merge iteration, merging all blocks from source into target.
                // After this step, target will contain fewer blocks than source, but may need another merge iteration.
                try ( BlockReader<KEY,VALUE> reader = reader( sourceFile );
                      StoreChannel targetChannel = fs.open( targetFile, OpenMode.READ_WRITE ) )
                {
                    long blocksMergedSoFar = 0;
                    long blocksInMergedFile = 0;
                    while ( !cancellation.cancelled() && blocksMergedSoFar < numberOfBlocksInCurrentFile )
                    {
                        blocksMergedSoFar += performSingleMerge( mergeFactor, reader, targetChannel, cancellation, readBuffers, writeBuffer );
                        blocksInMergedFile++;
                    }
                    numberOfBlocksInCurrentFile = blocksInMergedFile;
                    monitor.mergeIterationFinished( blocksMergedSoFar, blocksInMergedFile );
                }

                // Flip and restore the channels
                File tmpSourceFile = sourceFile;
                sourceFile = targetFile;
                targetFile = tmpSourceFile;
            }
        }
        finally
        {
            if ( sourceFile == blockFile )
            {
                fs.deleteFile( tempFile );
            }
            else
            {
                fs.deleteFile( blockFile );
                fs.renameFile( tempFile, blockFile );
            }
        }
    }

    /**
     * There are two files: sourceFile and targetFile. Blocks are merged, mergeFactor at the time, from source to target. When all blocks from source have
     * been merged into a larger block one merge iteration is done and source and target are flipped. As long as source contain more than a single block more
     * merge iterations are needed and we start over again.
     * When source only contain a single block we are finished and the extra file is deleted and {@link #blockFile} contains the result with a single sorted
     * block.
     *
     * See {@link #performSingleMerge(int, BlockReader, StoreChannel, Cancellation)} for further details.
     *
     * @param mergeFactor See {@link #performSingleMerge(int, BlockReader, StoreChannel, Cancellation)}.
     * @param cancellation Injected so that this merge can be cancelled, if an external request to do that comes in.
     * A cancelled merge will leave the same end state file/channel-wise, just not quite completed, which is fine because the merge
     * was cancelled meaning that the result will not be used for anything other than deletion.
     * @throws IOException If something goes wrong when reading from file.
     */
    public void merge( int mergeFactor, Cancellation cancellation ) throws IOException
    {
        monitor.mergeStarted( entryCount, calculateNumberOfEntriesWrittenDuringMerges( entryCount, numberOfBlocksInCurrentFile, mergeFactor ) );
        File sourceFile = blockFile;
        File tempFile = new File( blockFile.getParent(), blockFile.getName() + ".b" );
        try
        {
            File targetFile = tempFile;
            while ( numberOfBlocksInCurrentFile > 1 )
            {
                // Perform one complete merge iteration, merging all blocks from source into target.
                // After this step, target will contain fewer blocks than source, but may need another merge iteration.
                try ( BlockReader<KEY,VALUE> reader = reader( sourceFile );
                      StoreChannel targetChannel = fs.open( targetFile, OpenMode.READ_WRITE ) )
                {
                    long blocksMergedSoFar = 0;
                    long blocksInMergedFile = 0;
                    while ( !cancellation.cancelled() && blocksMergedSoFar < numberOfBlocksInCurrentFile )
                    {
                        blocksMergedSoFar += performSingleMerge( mergeFactor, reader, targetChannel, cancellation );
                        blocksInMergedFile++;
                    }
                    numberOfBlocksInCurrentFile = blocksInMergedFile;
                    monitor.mergeIterationFinished( blocksMergedSoFar, blocksInMergedFile );
                }

                // Flip and restore the channels
                File tmpSourceFile = sourceFile;
                sourceFile = targetFile;
                targetFile = tmpSourceFile;
            }
        }
        finally
        {
            if ( sourceFile == blockFile )
            {
                fs.deleteFile( tempFile );
            }
            else
            {
                fs.deleteFile( blockFile );
                fs.renameFile( tempFile, blockFile );
            }
        }
    }

Try With Resources try(Allocator mergeBufferAllocator=bufferFactory.newLocalAllocator()) in method public merge(mergeFactor int, cancellation Cancellation) : void from class org.neo4j.kernel.impl.index.schema.BlockStorage


    private static Matcher<OtherThreadRule> isThreadState( final Thread.State... eitherOfStates )
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( OtherThreadRule rule )
            {
                try
                {
                    rule.executor.waitUntilThreadState( eitherOfStates );
                    return true;
                }
                catch ( TimeoutException e )
                {
                    rule.executor.printStackTrace( System.err );
                    return false;
                }
            }

            @Override
            public void describeTo( org.hamcrest.Description description )
            {
                description.appendText( "Thread blocked in state WAITING" );
            }
        };
    }

    public static Matcher<OtherThreadRule> isThreadState( final Thread.State... eitherOfStates )
    {
        return new TypeSafeMatcher<OtherThreadRule>()
        {
            @Override
            protected boolean matchesSafely( OtherThreadRule rule )
            {
                try
                {
                    rule.executor.waitUntilThreadState( eitherOfStates );
                    return true;
                }
                catch ( TimeoutException e )
                {
                    rule.executor.printStackTrace( System.err );
                    return false;
                }
            }

            @Override
            public void describeTo( org.hamcrest.Description description )
            {
                description.appendText( "Thread blocked in state WAITING" );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<OtherThreadRule> with TypeSafeMatcher<> in method private isThreadState(eitherOfStates Thread.State...) : Matcher<OtherThreadRule> from class org.neo4j.test.rule.OtherThreadRule


    private BlockBasedIndexPopulator<GenericKey,NativeIndexValue> instantiatePopulator( BlockStorage.Monitor monitor, MemoryAllocationTracker memoryTracker )
    {
        IndexSpecificSpaceFillingCurveSettings spatialSettings = IndexSpecificSpaceFillingCurveSettings.fromConfig( Config.defaults() );
        GenericLayout layout = new GenericLayout( 1, spatialSettings );
        BlockBasedIndexPopulator<GenericKey,NativeIndexValue> populator =
                new BlockBasedIndexPopulator<>( pageCache, fs, indexFiles, layout, EMPTY, INDEX_DESCRIPTOR, spatialSettings, false, 100, 2, monitor,
                        memoryTracker )
                {
                    @Override
                    NativeIndexReader<GenericKey,NativeIndexValue> newReader()
                    {
                        throw new UnsupportedOperationException( "Not needed in this test" );
                    }
                };
        populator.create();
        return populator;
    }

    private BlockBasedIndexPopulator<GenericKey,NativeIndexValue> instantiatePopulator( BlockStorage.Monitor monitor, MemoryAllocationTracker memoryTracker )
    {
        IndexSpecificSpaceFillingCurveSettings spatialSettings = IndexSpecificSpaceFillingCurveSettings.fromConfig( Config.defaults() );
        GenericLayout layout = new GenericLayout( 1, spatialSettings );
        BlockBasedIndexPopulator<GenericKey,NativeIndexValue> populator =
                new BlockBasedIndexPopulator<GenericKey,NativeIndexValue>( storage.pageCache(), storage.fileSystem(), indexFiles, layout, EMPTY,
                        INDEX_DESCRIPTOR, spatialSettings, false, 100, 2, monitor, memoryTracker )
                {
                    @Override
                    NativeIndexReader<GenericKey,NativeIndexValue> newReader()
                    {
                        throw new UnsupportedOperationException( "Not needed in this test" );
                    }
                };
        populator.create();
        return populator;
    }

Replace Generic With Diamond BlockBasedIndexPopulator<GenericKey,NativeIndexValue> with BlockBasedIndexPopulator<> in method private instantiatePopulator(monitor BlockStorage.Monitor, memoryTracker MemoryAllocationTracker) : BlockBasedIndexPopulator<GenericKey,NativeIndexValue> from class org.neo4j.kernel.impl.index.schema.BlockBasedIndexPopulatorTest


            @Override
            public ChannelInitializer<Channel> channelInitializer()
            {
                return new ChannelInitializer<>()
                {
                    @Override
                    public void initChannel( Channel ch )
                    {
                    }
                };
            }

            @Override
            public ChannelInitializer<Channel> channelInitializer()
            {
                return new ChannelInitializer<Channel>()
                {
                    @Override
                    public void initChannel( Channel ch )
                    {
                    }
                };
            }

Replace Generic With Diamond ChannelInitializer<Channel> with ChannelInitializer<> in method public channelInitializer() : ChannelInitializer<Channel> from class org.neo4j.bolt.v1.transport.NettyServerTest.protocolOnAddress.new NettyServer.ProtocolInitializer


    private static NettyServer.ProtocolInitializer protocolOnAddress( ListenSocketAddress address )
    {
        return new NettyServer.ProtocolInitializer()
        {
            @Override
            public ChannelInitializer<Channel> channelInitializer()
            {
                return new ChannelInitializer<>()
                {
                    @Override
                    public void initChannel( Channel ch )
                    {
                    }
                };
            }

            @Override
            public ListenSocketAddress address()
            {
                return address;
            }
        };
    }

    private NettyServer.ProtocolInitializer protocolOnAddress( final ListenSocketAddress address )
    {
        return new NettyServer.ProtocolInitializer()
        {
            @Override
            public ChannelInitializer<Channel> channelInitializer()
            {
                return new ChannelInitializer<Channel>()
                {
                    @Override
                    public void initChannel( Channel ch )
                    {
                    }
                };
            }

            @Override
            public ListenSocketAddress address()
            {
                return address;
            }
        };
    }

Replace Generic With Diamond ChannelInitializer<Channel> with ChannelInitializer<> in method private protocolOnAddress(address ListenSocketAddress) : NettyServer.ProtocolInitializer from class org.neo4j.bolt.v1.transport.NettyServerTest


    @Test
    void shouldFindDecentAmountOfNodesForALabel() throws Exception
    {
        // GIVEN
        // 16 is the magic number of the page iterator
        // 32 is the number of nodes in each lucene document
        final int labelId = 1;
        int nodeCount = 32 * 16 + 10;
        start();
        write( new PrefetchingIterator<>()
        {
            private int i = -1;

            @Override
            protected NodeLabelUpdate fetchNextOrNull()
            {
                return ++i < nodeCount ? labelChanges( i, NO_LABELS, new long[]{labelId} ) : null;
            }
        } );

        // WHEN
        Set<Long> nodeSet = new TreeSet<>();
        LabelScanReader reader = store.newReader();
        PrimitiveLongResourceIterator nodes = reader.nodesWithLabel( labelId );
        while ( nodes.hasNext() )
        {
            nodeSet.add( nodes.next() );
        }
        nodes.close();

        // THEN
        assertEquals( nodeCount, nodeSet.size(), "Found gaps in node id range: " + gaps( nodeSet, nodeCount ) );
    }

    @Test
    void shouldFindDecentAmountOfNodesForALabel() throws Exception
    {
        // GIVEN
        // 16 is the magic number of the page iterator
        // 32 is the number of nodes in each lucene document
        final int labelId = 1;
        int nodeCount = 32 * 16 + 10;
        start();
        write( new PrefetchingIterator<NodeLabelUpdate>()
        {
            private int i = -1;

            @Override
            protected NodeLabelUpdate fetchNextOrNull()
            {
                return ++i < nodeCount ? labelChanges( i, NO_LABELS, new long[]{labelId} ) : null;
            }
        } );

        // WHEN
        Set<Long> nodeSet = new TreeSet<>();
        LabelScanReader reader = store.newReader();
        PrimitiveLongResourceIterator nodes = reader.nodesWithLabel( labelId );
        while ( nodes.hasNext() )
        {
            nodeSet.add( nodes.next() );
        }
        nodes.close();

        // THEN
        assertEquals( nodeCount, nodeSet.size(), "Found gaps in node id range: " + gaps( nodeSet, nodeCount ) );
    }

Replace Generic With Diamond PrefetchingIterator<NodeLabelUpdate> with PrefetchingIterator<> in method package shouldFindDecentAmountOfNodesForALabel() : void from class org.neo4j.internal.index.label.NativeLabelScanStoreTest


    public static int countAndClose( PrimitiveLongResourceIterator iterator )
    {
        try ( iterator )
        {
            return count( iterator );
        }
    }

    public static int countAndClose( PrimitiveLongResourceIterator iterator )
    {
        try
        {
            return count( iterator );
        }
        finally
        {
            iterator.close();
        }
    }

Try With Resources try(iterator) in method public countAndClose(iterator PrimitiveLongResourceIterator) : int from class org.neo4j.collection.PrimitiveLongCollections


    public static long[] closingAsArray( PrimitiveLongResourceIterator iterator )
    {
        try ( iterator )
        {
            return asArray( iterator );
        }
    }

    public static long[] closingAsArray( PrimitiveLongResourceIterator iterator )
    {
        try
        {
            return asArray( iterator );
        }
        finally
        {
            iterator.close();
        }
    }

Try With Resources try(iterator) in method public closingAsArray(iterator PrimitiveLongResourceIterator) : long[] from class org.neo4j.collection.PrimitiveLongCollections


    public static <T> Iterator<T> map( final LongFunction<T> mapFunction, final LongIterator source )
    {
        return new Iterator<>()
        {
            @Override
            public boolean hasNext()
            {
                return source.hasNext();
            }

            @Override
            public T next()
            {
                return mapFunction.apply( source.next() );
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException();
            }
        };
    }

    public static <T> Iterator<T> map( final LongFunction<T> mapFunction, final LongIterator source )
    {
        return new Iterator<T>()
        {
            @Override
            public boolean hasNext()
            {
                return source.hasNext();
            }

            @Override
            public T next()
            {
                return mapFunction.apply( source.next() );
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException();
            }
        };
    }

Replace Generic With Diamond Iterator<T> with Iterator<> in method public map(mapFunction LongFunction<T>, source LongIterator) : Iterator<T> from class org.neo4j.collection.PrimitiveLongCollections


    public static Iterator<Long> toIterator( final LongIterator primIterator )
    {
        return new Iterator<>()
        {
            @Override
            public boolean hasNext()
            {
                return primIterator.hasNext();
            }

            @Override
            public Long next()
            {
                return primIterator.next();
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException();
            }
        };
    }

    public static Iterator<Long> toIterator( final LongIterator primIterator )
    {
        return new Iterator<Long>()
        {
            @Override
            public boolean hasNext()
            {
                return primIterator.hasNext();
            }

            @Override
            public Long next()
            {
                return primIterator.next();
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException(  );
            }
        };
    }

Replace Generic With Diamond Iterator<Long> with Iterator<> in method public toIterator(primIterator LongIterator) : Iterator<Long> from class org.neo4j.collection.PrimitiveLongCollections


    static <T, EX extends Exception> RawIterator<T, EX> of( T ... values )
    {
        return new RawIterator<>()
        {
            private int position;

            @Override
            public boolean hasNext()
            {
                return position < values.length;
            }

            @Override
            public T next() throws EX
            {
                if ( hasNext() )
                {
                    return values[position++];
                }
                throw new NoSuchElementException();
            }
        };
    }

    static <T, EX extends Exception> RawIterator<T, EX> of( T ... values )
    {
        return new RawIterator<T,EX>()
        {
            private int position;

            @Override
            public boolean hasNext() throws EX
            {
                return position < values.length;
            }

            @Override
            public T next() throws EX
            {
                if ( hasNext() )
                {
                    return values[position++];
                }
                throw new NoSuchElementException();
            }
        };
    }

Replace Generic With Diamond RawIterator<T,EX> with RawIterator<> in method public of(values T...) : RawIterator<T,EX> from class org.neo4j.collection.RawIterator


    @Override
    public Iterator<AnyValue> iterator()
    {
        return new Iterator<>()
        {
            private int offset;

            @Override
            public boolean hasNext()
            {
                return offset < length();
            }

            @Override
            public AnyValue next()
            {
                if ( !hasNext() )
                {
                    throw new NoSuchElementException();
                }
                return value( offset++ );
            }
        };
    }

    @Override
    public Iterator<AnyValue> iterator()
    {
        return new Iterator<AnyValue>()
        {
            private int offset;

            @Override
            public boolean hasNext()
            {
                return offset < length();
            }

            @Override
            public AnyValue next()
            {
                if ( !hasNext() )
                {
                    throw new NoSuchElementException();
                }
                return value( offset++ );
            }
        };
    }

Replace Generic With Diamond Iterator<AnyValue> with Iterator<> in method public iterator() : Iterator<AnyValue> from class org.neo4j.values.storable.ArrayValue


    private Iterator<Comparable> comparables( final String string )
    {
        return new PrefetchingIterator<>()
        {
            private int index;

            @Override
            protected Comparable fetchNextOrNull()
            {
                if ( index >= string.length() )
                {   // End reached
                    return null;
                }

                int startIndex = index;
                char ch = string.charAt( index );
                boolean isNumber = Character.isDigit( ch );
                while ( Character.isDigit( ch ) == isNumber && ++index < string.length() )
                {
                    ch = string.charAt( index );
                }
                String substring = string.substring( startIndex, index );
                return isNumber ? Long.valueOf( substring ) : substring;
            }
        };
    }

    @SuppressWarnings( "rawtypes" )
    private Iterator<Comparable> comparables( final String string )
    {
        return new PrefetchingIterator<Comparable>()
        {
            private int index;

            @Override
            protected Comparable fetchNextOrNull()
            {
                if ( index >= string.length() )
                {   // End reached
                    return null;
                }

                int startIndex = index;
                char ch = string.charAt( index );
                boolean isNumber = Character.isDigit( ch );
                while ( Character.isDigit( ch ) == isNumber && ++index < string.length() )
                {
                    ch = string.charAt( index );
                }
                String substring = string.substring( startIndex, index );
                return isNumber ? Long.valueOf( substring ) : substring;
            }
        };
    }

Replace Generic With Diamond PrefetchingIterator<Comparable> with PrefetchingIterator<> in method private comparables(string String) : Iterator<Comparable> from class org.neo4j.kernel.impl.util.NumberAwareStringComparator


    public static void deletePathRecursively( Path path ) throws IOException
    {
        Files.walkFileTree( path, new SimpleFileVisitor<>()
        {
            @Override
            public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException
            {
                deleteFile( file );
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory( Path dir, IOException e ) throws IOException
            {
                if ( e != null )
                {
                    throw e;
                }
                try
                {
                    Files.delete( dir );
                }
                catch ( DirectoryNotEmptyException notEmpty )
                {
                    String reason = notEmptyReason( dir, notEmpty );
                    throw new IOException( notEmpty.getMessage() + ": " + reason, notEmpty );
                }
                return FileVisitResult.CONTINUE;
            }

            private String notEmptyReason( Path dir, DirectoryNotEmptyException notEmpty )
            {
                try ( Stream<Path> list = Files.list( dir ) )
                {
                    return list.map( p -> String.valueOf( p.getFileName() ) ).collect( Collectors.joining( "', '", "'", "'." ) );
                }
                catch ( Exception e )
                {
                    notEmpty.addSuppressed( e );
                    return "(could not list directory: " + e.getMessage() + ")";
                }
            }
        } );
    }

    public static void deletePathRecursively( Path path ) throws IOException
    {
        Files.walkFileTree( path, new SimpleFileVisitor<Path>()
        {
            @Override
            public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException
            {
                deleteFile( file );
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory( Path dir, IOException e ) throws IOException
            {
                if ( e != null )
                {
                    throw e;
                }
                try
                {
                    Files.delete( dir );
                }
                catch ( DirectoryNotEmptyException notEmpty )
                {
                    String reason = notEmptyReason( dir, notEmpty );
                    throw new IOException( notEmpty.getMessage() + ": " + reason, notEmpty );
                }
                return FileVisitResult.CONTINUE;
            }

            private String notEmptyReason( Path dir, DirectoryNotEmptyException notEmpty )
            {
                try ( Stream<Path> list = Files.list( dir ) )
                {
                    return list.map( p -> String.valueOf( p.getFileName() ) ).collect( Collectors.joining("', '", "'", "'." ) );
                }
                catch ( Exception e )
                {
                    notEmpty.addSuppressed( e );
                    return "(could not list directory: " + e.getMessage() + ")";
                }
            }
        } );
    }

Replace Generic With Diamond SimpleFileVisitor<Path> with SimpleFileVisitor<> in method public deletePathRecursively(path Path) : void from class org.neo4j.io.fs.FileUtils


    @Description( "Query the given fulltext index. Returns the matching nodes and their lucene query score, ordered by score." )
    @Procedure( name = "db.index.fulltext.queryNodes", mode = READ )
    public Stream<NodeOutput> queryFulltextForNodes( @Name( "indexName" ) String name, @Name( "queryString" ) String query ) throws Exception
    {
        IndexReference indexReference = getValidIndexReference( name );
        awaitOnline( indexReference );
        EntityType entityType = indexReference.schema().entityType();
        if ( entityType != EntityType.NODE )
        {
            throw new IllegalArgumentException( "The '" + name + "' index (" + indexReference + ") is an index on " + entityType +
                    ", so it cannot be queried for nodes." );
        }
        NodeValueIndexCursor cursor = tx.cursors().allocateNodeValueIndexCursor();
        IndexReadSession indexSession = tx.dataRead().indexReadSession( indexReference );
        tx.dataRead().nodeIndexSeek( indexSession, cursor, IndexOrder.NONE, false, IndexQuery.fulltextSearch( query ) );

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

    @Description( "Query the given fulltext index. Returns the matching nodes and their lucene query score, ordered by score." )
    @Procedure( name = "db.index.fulltext.queryNodes", mode = READ )
    public Stream<NodeOutput> queryFulltextForNodes( @Name( "indexName" ) String name, @Name( "queryString" ) String query ) throws Exception
    {
        IndexReference indexReference = getValidIndexReference( name );
        awaitOnline( indexReference );
        EntityType entityType = indexReference.schema().entityType();
        if ( entityType != EntityType.NODE )
        {
            throw new IllegalArgumentException( "The '" + name + "' index (" + indexReference + ") is an index on " + entityType +
                    ", so it cannot be queried for nodes." );
        }
        NodeValueIndexCursor cursor = tx.cursors().allocateNodeValueIndexCursor();
        IndexReadSession indexSession = tx.dataRead().indexReadSession( indexReference );
        tx.dataRead().nodeIndexSeek( indexSession, cursor, IndexOrder.NONE, false, IndexQuery.fulltextSearch( query ) );

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

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