        @Override
        public void run()
        {
            for ( EntityUpdates update : updates )
                {
                    try ( Transaction transaction = embeddedDatabase.beginTx() )
                    {
                        Node node = embeddedDatabase.getNodeById( update.getEntityId() );
                        for ( int labelId : labelsNameIdMap.values() )
                        {
                            LabelSchemaDescriptor schema = SchemaDescriptorFactory.forLabel( labelId, propertyId );
                            for ( IndexEntryUpdate<?> indexUpdate :
                                    update.forIndexKeys( Collections.singleton( schema ) ) )
                            {
                                switch ( indexUpdate.updateMode() )
                                {
                                case CHANGED:
                                case ADDED:
                                    node.addLabel(
                                            Label.label( labelsIdNameMap.get( schema.getLabelId() ) ) );
                                    node.setProperty( NAME_PROPERTY, indexUpdate.values()[0].asObject() );
                                    break;
                                case REMOVED:
                                    node.addLabel(
                                            Label.label( labelsIdNameMap.get( schema.getLabelId() ) ) );
                                    node.delete();
                                    break;
                                default:
                                    throw new IllegalArgumentException( indexUpdate.updateMode().name() );
                                }
                            }
                        }
                        transaction.success();
                    }
                }
                try ( StorageReader reader = storageEngine.newReader() )
                {
                    for ( EntityUpdates update : updates )
                    {
                        Iterable<IndexEntryUpdate<SchemaDescriptor>> entryUpdates =
                                indexService.convertToIndexUpdates( update, reader, EntityType.NODE );
                        DirectIndexUpdates directIndexUpdates = new DirectIndexUpdates( entryUpdates );
                        indexService.apply( directIndexUpdates );
                    }
                }
                catch ( UncheckedIOException | IndexEntryConflictException e )
                {
                    throw new RuntimeException( e );
                }
        }

        @Override
        public void run()
        {
            for ( EntityUpdates update : updates )
                {
                    try ( Transaction transaction = embeddedDatabase.beginTx() )
                    {
                        Node node = embeddedDatabase.getNodeById( update.getEntityId() );
                        for ( int labelId : labelsNameIdMap.values() )
                        {
                            LabelSchemaDescriptor schema = SchemaDescriptorFactory.forLabel( labelId, propertyId );
                            for ( IndexEntryUpdate<?> indexUpdate :
                                    update.forIndexKeys( Collections.singleton( schema ) ) )
                            {
                                switch ( indexUpdate.updateMode() )
                                {
                                case CHANGED:
                                case ADDED:
                                    node.addLabel(
                                            Label.label( labelsIdNameMap.get( schema.getLabelId() ) ) );
                                    node.setProperty( NAME_PROPERTY, indexUpdate.values()[0].asObject() );
                                    break;
                                case REMOVED:
                                    node.addLabel(
                                            Label.label( labelsIdNameMap.get( schema.getLabelId() ) ) );
                                    node.delete();
                                    break;
                                default:
                                    throw new IllegalArgumentException( indexUpdate.updateMode().name() );
                                }
                            }
                        }
                        transaction.success();
                    }
                }
                try
                {
                    for ( EntityUpdates update : updates )
                    {
                        Iterable<IndexEntryUpdate<SchemaDescriptor>> entryUpdates =
                                indexService.convertToIndexUpdates( update, EntityType.NODE );
                        DirectIndexUpdates directIndexUpdates = new DirectIndexUpdates( entryUpdates );
                        indexService.apply( directIndexUpdates );
                    }
                }
                catch ( UncheckedIOException | IndexEntryConflictException e )
                {
                    throw new RuntimeException( e );
                }
        }

Try With Resources try(StorageReader reader=storageEngine.newReader()) in method public run() : void from class schema.MultiIndexPopulationConcurrentUpdatesIT.UpdateGenerator


    @Test
    public void shouldBeAbleToSnapshotDuringHeavyLoad() throws Throwable
    {
        // GIVEN
        final KernelTransactions transactions = newKernelTransactions();
        Race race = new Race();
        final int threads = 50;
        final AtomicBoolean end = new AtomicBoolean();
        final AtomicReferenceArray<KernelTransactionsSnapshot> snapshots = new AtomicReferenceArray<>( threads );

        // Representing "transaction" threads
        for ( int i = 0; i < threads; i++ )
        {
            final int threadIndex = i;
            race.addContestant( () ->
            {
                ThreadLocalRandom random = ThreadLocalRandom.current();
                while ( !end.get() )
                {
                    try ( KernelTransaction ignored = getKernelTransaction( transactions ) )
                    {
                        parkNanos( MILLISECONDS.toNanos( random.nextInt( 3 ) ) );
                        if ( snapshots.get( threadIndex ) == null )
                        {
                            snapshots.set( threadIndex, transactions.get() );
                            parkNanos( MILLISECONDS.toNanos( random.nextInt( 3 ) ) );
                        }
                    }
                    catch ( TransactionFailureException e )
                    {
                        throw new RuntimeException( e );
                    }
                }
            } );
        }

        // Just checks snapshots
        race.addContestant( () ->
        {
            ThreadLocalRandom random = ThreadLocalRandom.current();
            int snapshotsLeft = 1_000;
            while ( snapshotsLeft > 0 )
            {
                int threadIndex = random.nextInt( threads );
                KernelTransactionsSnapshot snapshot = snapshots.get( threadIndex );
                if ( snapshot != null && snapshot.allClosed() )
                {
                    snapshotsLeft--;
                    snapshots.set( threadIndex, null );
                }
            }

            // End condition of this test can be described as:
            //   when 1000 snapshots have been seen as closed.
            // setting this boolean to true will have all other threads end as well so that race.go() will end
            end.set( true );
        } );

        // WHEN
        race.go();
    }

    @Test
    public void shouldBeAbleToSnapshotDuringHeavyLoad() throws Throwable
    {
        // GIVEN
        final KernelTransactions transactions = newKernelTransactions();
        Race race = new Race();
        final int threads = 50;
        final AtomicBoolean end = new AtomicBoolean();
        final AtomicReferenceArray<KernelTransactionsSnapshot> snapshots = new AtomicReferenceArray<>( threads );

        // Representing "transaction" threads
        for ( int i = 0; i < threads; i++ )
        {
            final int threadIndex = i;
            race.addContestant( () ->
            {
                ThreadLocalRandom random = ThreadLocalRandom.current();
                while ( !end.get() )
                {
                    try ( KernelTransaction transaction = getKernelTransaction( transactions ) )
                    {
                        KernelTransactionsSnapshot snapshot = null;
                        try
                        {
                            parkNanos( MILLISECONDS.toNanos( random.nextInt( 3 ) ) );
                            if ( snapshots.get( threadIndex ) == null )
                            {
                                requireNonNull( transactions, "transactions is null" );
                                snapshot = requireNonNull( transactions.get(), "transactions.get() returned null" );
                                snapshots.set( threadIndex, snapshot );
                                parkNanos( MILLISECONDS.toNanos( random.nextInt( 3 ) ) );
                            }
                        }
                        catch ( RuntimeException e )
                        {
                            StringBuilder sb = new StringBuilder( "Gotcha!\n" )
                                    .append( "threadIndex=" ).append( threadIndex ).append( '\n' )
                                    .append( "transaction=" ).append( transaction ).append( '\n' )
                                    .append( "snapshots=" ).append( snapshots ).append( '\n' )
                                    .append( "snapshot=" ).append( snapshot ).append( '\n' )
                                    .append( "end=" ).append( end );
                            throw new RuntimeException( sb.toString(), e );
                        }
                    }
                    catch ( TransactionFailureException e )
                    {
                        throw new RuntimeException( e );
                    }
                }
            } );
        }

        // Just checks snapshots
        race.addContestant( () ->
        {
            ThreadLocalRandom random = ThreadLocalRandom.current();
            int snapshotsLeft = 1_000;
            while ( snapshotsLeft > 0 )
            {
                int threadIndex = random.nextInt( threads );
                KernelTransactionsSnapshot snapshot = snapshots.get( threadIndex );
                if ( snapshot != null && snapshot.allClosed() )
                {
                    snapshotsLeft--;
                    snapshots.set( threadIndex, null );
                }
            }

            // End condition of this test can be described as:
            //   when 1000 snapshots have been seen as closed.
            // setting this boolean to true will have all other threads end as well so that race.go() will end
            end.set( true );
        } );

        // WHEN
        race.go();
    }

Try With Resources try(KernelTransaction ignored=getKernelTransaction(transactions)) in method public shouldBeAbleToSnapshotDuringHeavyLoad() : void from class org.neo4j.kernel.impl.api.KernelTransactionsTest


    @Test
    public void shouldKeepAuthorizationForLifetimeOfTransaction() throws Throwable
    {
        DoubleLatch latch = new DoubleLatch( 2 );
        final Throwable[] threadFail = {null};

        Thread readerThread = new Thread( () ->
        {
            try
            {
                try ( Driver driver = connectDriver( "neo", "abc123" );
                        Session session = driver.session();
                        Transaction tx = session.beginTransaction() )
                {
                    assertThat( tx.run( "MATCH (n) RETURN count(n)" ).single().get( 0 ).asInt(), greaterThanOrEqualTo( 0 ) );
                    latch.startAndWaitForAllToStart();
                    latch.finishAndWaitForAllToFinish();
                    assertThat( tx.run( "MATCH (n) RETURN count(n)" ).single().get( 0 ).asInt(), greaterThanOrEqualTo( 0 ) );
                    tx.success();
                }
            }
            catch ( Throwable t )
            {
                threadFail[0] = t;
                // Always release the latch so we get the failure in the main thread
                latch.start();
                latch.finish();
            }
        } );

        readerThread.start();
        latch.startAndWaitForAllToStart();

        clearAuthCacheFromDifferentConnection();

        latch.finishAndWaitForAllToFinish();

        readerThread.join();
        if ( threadFail[0] != null )
        {
            throw threadFail[0];
        }
    }

    @Test
    public void shouldKeepAuthorizationForLifetimeOfTransaction() throws Throwable
    {
        restartServerWithoutSystemAccount();

        DoubleLatch latch = new DoubleLatch( 2 );
        final Throwable[] threadFail = {null};

        Thread readerThread = new Thread( () ->
        {
            try
            {
                assertAuth( "neo", "abc123" );
                assertBeginTransactionSucceeds();
                assertReadSucceeds();

                latch.startAndWaitForAllToStart();
                latch.finishAndWaitForAllToFinish();

                assertReadSucceeds();
            }
            catch ( Throwable t )
            {
                threadFail[0] = t;
                // Always release the latch so we get the failure in the main thread
                latch.start();
                latch.finish();
            }
        } );

        readerThread.start();
        latch.startAndWaitForAllToStart();

        clearAuthCacheFromDifferentConnection();

        latch.finishAndWaitForAllToFinish();

        readerThread.join();
        if ( threadFail[0] != null )
        {
            throw threadFail[0];
        }
    }

Try With Resources try(Driver driver=connectDriver("neo","abc123"); Session session=driver.session(); Transaction tx=session.beginTransaction()) in method public shouldKeepAuthorizationForLifetimeOfTransaction() : void from class org.neo4j.server.security.enterprise.auth.integration.bolt.LdapAuthIT


    ParallelNativeIndexPopulator( File baseIndexFile, IndexLayout<KEY,VALUE> layout, NativeIndexPopulatorPartSupplier<KEY,VALUE> partSupplier )
    {
        this.layout = layout;
        this.threadLocalPopulators = ThreadLocal.withInitial( () ->
        {
            if ( closed )
            {
                throw new IllegalStateException( "Already closed" );
            }
            if ( merged )
            {
                throw new IllegalStateException( "Already merged" );
            }

            File file = new File( baseIndexFile + "-part-" + nextPartId.getAndIncrement() );
            NativeIndexPopulator<KEY,VALUE> populator = partSupplier.part( file );
            ThreadLocalPopulator tlPopulator = new ThreadLocalPopulator( populator );
            partPopulators.add( tlPopulator );
            populator.create();
            return tlPopulator;
        } );
        this.completePopulator = partSupplier.part( baseIndexFile );
    }

    ParallelNativeIndexPopulator( File baseIndexFile, IndexLayout<KEY,VALUE> layout, NativeIndexPopulatorPartSupplier<KEY,VALUE> partSupplier )
    {
        this.layout = layout;
        this.threadLocalPopulators = new ThreadLocal<ThreadLocalPopulator>()
        {
            /**
             * Creates a new part populator. It can be synchronized because it simplifies the implementation
             * and virtually all time is spent in PageCache#map method inside populator.create, which is synchronized anyway.
             */
            @Override
            protected ThreadLocalPopulator initialValue()
            {
                if ( closed )
                {
                    throw new IllegalStateException( "Already closed" );
                }
                if ( merged )
                {
                    throw new IllegalStateException( "Already merged" );
                }

                File file = new File( baseIndexFile + "-part-" + nextPartId.getAndIncrement() );
                NativeIndexPopulator<KEY,VALUE> populator = partSupplier.part( file );
                ThreadLocalPopulator tlPopulator = new ThreadLocalPopulator( populator );
                partPopulators.add( tlPopulator );
                populator.create();
                return tlPopulator;
            }
        };
        this.completePopulator = partSupplier.part( baseIndexFile );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.index.schema.ParallelNativeIndexPopulator.ParallelNativeIndexPopulator.new ThreadLocal<ThreadLocalPopulator> with () -> {if(closed){throw new IllegalStateException("Already closed"); in method package ParallelNativeIndexPopulator(baseIndexFile File, layout IndexLayout<KEY,VALUE>, partSupplier NativeIndexPopulatorPartSupplier<KEY,VALUE>) from class org.neo4j.kernel.impl.index.schema.ParallelNativeIndexPopulator


        @Override
        public IndexUpdater newUpdater( final IndexUpdateMode mode )
        {
            return new CollectingIndexUpdater( updates ->
            {
                switch ( mode )
                {
                    case ONLINE:
                        regularUpdates.addAll( updates );
                        break;

                    case RECOVERY:
                        batchedUpdates.addAll( updates );
                        break;

                    default:
                        throw new UnsupportedOperationException(  );
                }
            } );
        }

        @Override
        public IndexUpdater newUpdater( final IndexUpdateMode mode )
        {
            return new CollectingIndexUpdater()
            {
                @Override
                public void close()
                {
                    switch ( mode )
                    {
                        case ONLINE:
                            regularUpdates.addAll( updates );
                            break;

                        case RECOVERY:
                            batchedUpdates.addAll( updates );
                            break;

                        default:
                            throw new UnsupportedOperationException(  );
                    }
                }
            };
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.IndexRecoveryIT.GatheringIndexWriter.newUpdater.new CollectingIndexUpdater with updates -> {switch(mode)case ONLINE:regularUpdates.addAll(updates); in method public newUpdater(mode IndexUpdateMode) : IndexUpdater from class org.neo4j.kernel.impl.api.index.IndexRecoveryIT.GatheringIndexWriter


    @Override
    public IndexUpdater newPopulatingUpdater( NodePropertyAccessor accessor )
    {
        // Native index populators don't make use of NodePropertyAccessor, so just ignore it

        // Don't have an explicit updatesPopulator, instead record these updates and then each populator will have to apply next time they notice.
        return new CollectingIndexUpdater( updates ->
        {
            // Ensure there's at least one part populator active. This is for a case where an index population is started
            // and the only data coming in is from the populating updater.
            if ( partPopulators.isEmpty() )
            {
                threadLocalPopulators.get();
            }
            partPopulators.forEach( p -> p.updates.add( updates ) );
        } );
    }

    @Override
    public IndexUpdater newPopulatingUpdater( NodePropertyAccessor accessor )
    {
        // Native index populators don't make use of NodePropertyAccessor, so just ignore it

        // Don't have an explicit updatesPopulator, instead record these updates and then each populator will have to apply next time they notice.
        return new CollectingIndexUpdater<KEY,VALUE>()
        {
            @Override
            protected void apply( Collection<IndexEntryUpdate<?>> updates )
            {
                // Ensure there's at least one part populator active. This is for a case where an index population is started
                // and the only data coming in is from the populating updater.
                if ( partPopulators.isEmpty() )
                {
                    threadLocalPopulators.get();
                }
                partPopulators.forEach( p -> p.updates.add( updates ) );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.index.schema.ParallelNativeIndexPopulator.newPopulatingUpdater.new CollectingIndexUpdater<KEY,VALUE> with updates -> {if(partPopulators.isEmpty()){threadLocalPopulators.get(); in method public newPopulatingUpdater(accessor NodePropertyAccessor) : IndexUpdater from class org.neo4j.kernel.impl.index.schema.ParallelNativeIndexPopulator


    public static void main( String[] args )
    {
        System.err.println("WARNING: neo4j-backup is deprecated and support for it will be removed in a future\n" +
                "version of Neo4j; please use neo4j-admin backup instead.\n");
        try ( BackupProtocolService backupProtocolService = backupProtocolService() )
        {
            BackupTool tool = new BackupTool( backupProtocolService, System.out );
            BackupOutcome backupOutcome = tool.run( args );

            if ( !backupOutcome.isConsistent() )
            {
                exitFailure( "WARNING: The database is inconsistent." );
            }
        }
        catch ( Exception e )
        {
            System.out.println( "Backup failed." );
            exitFailure( e.getMessage() );
        }
    }

    public static void main( String[] args )
    {
        System.err.println("WARNING: neo4j-backup is deprecated and support for it will be removed in a future\n" +
                "version of Neo4j; please use neo4j-admin backup instead.\n");
        BackupTool tool = new BackupTool( new BackupProtocolService(), System.out );
        try
        {
            BackupOutcome backupOutcome = tool.run( args );

            if ( !backupOutcome.isConsistent() )
            {
                exitFailure( "WARNING: The database is inconsistent." );
            }
        }
        catch ( ToolFailureException e )
        {
            System.out.println( "Backup failed." );
            exitFailure( e.getMessage() );
        }
    }

Try With Resources try(BackupProtocolService backupProtocolService=backupProtocolService()) in method public main(args String[]) : void from class org.neo4j.backup.BackupTool


    @Test
    public void shouldNotOpenStoreWithNodesOrRelationshipsInIt() throws Exception
    {
        // GIVEN
        someDataInTheDatabase();

        // WHEN
        try ( JobScheduler jobScheduler = new ThreadPoolJobScheduler() )
        {
            RecordFormats recordFormats = RecordFormatSelector.selectForConfig( Config.defaults(), NullLogProvider.getInstance() );
            try ( BatchingNeoStores store = BatchingNeoStores.batchingNeoStores( storage.fileSystem(), storage.directory().databaseDir(), recordFormats,
                    DEFAULT, NullLogService.getInstance(), EMPTY, Config.defaults(), jobScheduler ) )
            {
                store.createNew();
                fail( "Should fail on existing data" );
            }
        }
        catch ( IllegalStateException e )
        {
            // THEN
            assertThat( e.getMessage(), containsString( "already contains" ) );
        }
    }

    @Test
    public void shouldNotOpenStoreWithNodesOrRelationshipsInIt() throws Exception
    {
        // GIVEN
        someDataInTheDatabase();

        // WHEN
        try
        {
            RecordFormats recordFormats = RecordFormatSelector.selectForConfig( Config.defaults(), NullLogProvider.getInstance() );
            try ( BatchingNeoStores store = BatchingNeoStores.batchingNeoStores( storage.fileSystem(), storage.directory().databaseDir(), recordFormats,
                    DEFAULT, NullLogService.getInstance(), EMPTY, Config.defaults() ) )
            {
                store.createNew();
                fail( "Should fail on existing data" );
            }
        }
        catch ( IllegalStateException e )
        {
            // THEN
            assertThat( e.getMessage(), containsString( "already contains" ) );
        }
    }

Try With Resources try(JobScheduler jobScheduler=new ThreadPoolJobScheduler()) in method public shouldNotOpenStoreWithNodesOrRelationshipsInIt() : void from class org.neo4j.unsafe.impl.batchimport.store.BatchingNeoStoresTest


    /**
     * There was this problem where some steps and in particular parallel CSV input parsing that
     * paniced would hang the import entirely.
     */
    @Test
    public void shouldExitAndThrowExceptionOnPanic() throws Exception
    {
        try ( JobScheduler jobScheduler = new ThreadPoolJobScheduler() )
        {
            BatchImporter importer = new ParallelBatchImporter( directory.databaseLayout(), fs, null, Configuration.DEFAULT,
                    NullLogService.getInstance(), ExecutionMonitors.invisible(), AdditionalInitialIds.EMPTY,
                    Config.defaults(), StandardV3_0.RECORD_FORMATS, NO_MONITOR, jobScheduler );
            Iterable<DataFactory> nodeData =
                    datas( data( NO_DECORATOR, fileAsCharReadable( nodeCsvFileWithBrokenEntries() ) ) );
            Input brokenCsvInput = new CsvInput(
                    nodeData, defaultFormatNodeFileHeader(),
                    datas(), defaultFormatRelationshipFileHeader(),
                    IdType.ACTUAL,
                    csvConfigurationWithLowBufferSize(),
                    new BadCollector( NullOutputStream.NULL_OUTPUT_STREAM, 0, 0 ) );
            importer.doImport( brokenCsvInput );
            fail( "Should have failed properly" );
        }
        catch ( InputException e )
        {
            // THEN
            assertTrue( e.getCause() instanceof DataAfterQuoteException );
            // and we managed to shut down properly
        }
    }

    /**
     * There was this problem where some steps and in particular parallel CSV input parsing that
     * paniced would hang the import entirely.
     */
    @Test
    public void shouldExitAndThrowExceptionOnPanic() throws Exception
    {
        // GIVEN
        BatchImporter importer = new ParallelBatchImporter( directory.databaseLayout(), fs, null, Configuration.DEFAULT,
                NullLogService.getInstance(), ExecutionMonitors.invisible(), AdditionalInitialIds.EMPTY,
                Config.defaults(), StandardV3_0.RECORD_FORMATS, NO_MONITOR );
        Iterable<DataFactory> nodeData =
                datas( data( NO_DECORATOR, fileAsCharReadable( nodeCsvFileWithBrokenEntries() ) ) );
        Input brokenCsvInput = new CsvInput(
                nodeData, defaultFormatNodeFileHeader(),
                datas(), defaultFormatRelationshipFileHeader(),
                IdType.ACTUAL,
                csvConfigurationWithLowBufferSize(),
                new BadCollector( NullOutputStream.NULL_OUTPUT_STREAM, 0, 0 ) );

        // WHEN
        try
        {
            importer.doImport( brokenCsvInput );
            fail( "Should have failed properly" );
        }
        catch ( InputException e )
        {
            // THEN
            assertTrue( e.getCause() instanceof DataAfterQuoteException );
            // and we managed to shut down properly
        }
    }

Try With Resources try(JobScheduler jobScheduler=new ThreadPoolJobScheduler()) in method public shouldExitAndThrowExceptionOnPanic() : void from class org.neo4j.unsafe.impl.batchimport.ImportPanicIT


    private Executable withNewSet( Consumer<MutableLinearProbeLongHashSet> test )
    {
        return () ->
        {
            try ( MutableLinearProbeLongHashSet set = newSet() )
            {
                    test.accept( set );
            }
        };
    }

    private Executable withNewSet( Consumer<MutableLinearProbeLongHashSet> test )
    {
        return () ->
        {
            final MutableLinearProbeLongHashSet set = newSet();
            try
            {
                test.accept( set );
            }
            finally
            {
                set.close();
            }
        };
    }

Try With Resources try(MutableLinearProbeLongHashSet set=newSet()) in method private withNewSet(test Consumer<MutableLinearProbeLongHashSet>) : Executable from class org.neo4j.collection.offheap.MutableLinearProbeLongHashSetTest


    private Lifecycle lifecycleToTriggerCheckPointOnShutdown()
    {
        // Write new checkpoint in the log only if the kernel is healthy.
        // We cannot throw here since we need to shutdown without exceptions,
        // so let's make the checkpointing part of the life, so LifeSupport can handle exceptions properly
        return LifecycleAdapter.onShutdown( () ->
        {
            if ( databaseHealth.isHealthy() )
            {
                // Flushing of neo stores happens as part of the checkpoint
                transactionLogModule.checkPointing().forceCheckPoint( new SimpleTriggerInfo( "database shutdown" ) );
            }
        } );
    }

    private Lifecycle lifecycleToTriggerCheckPointOnShutdown()
    {
        // Write new checkpoint in the log only if the kernel is healthy.
        // We cannot throw here since we need to shutdown without exceptions,
        // so let's make the checkpointing part of the life, so LifeSupport can handle exceptions properly
        return new LifecycleAdapter()
        {
            @Override
            public void shutdown() throws IOException
            {
                if ( databaseHealth.isHealthy() )
                {
                    // Flushing of neo stores happens as part of the checkpoint
                    transactionLogModule.checkPointing()
                            .forceCheckPoint( new SimpleTriggerInfo( "database shutdown" ) );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.NeoStoreDataSource.lifecycleToTriggerCheckPointOnShutdown.new LifecycleAdapter with () -> {if(databaseHealth.isHealthy()){transactionLogModule.checkPointing().forceCheckPoint(new SimpleTriggerInfo("database shutdown")); in method private lifecycleToTriggerCheckPointOnShutdown() : Lifecycle from class org.neo4j.kernel.NeoStoreDataSource


        static Set<WorkLog> combinations()
        {
            Set<WorkLog> combinations = Collections.newSetFromMap( new LinkedHashMap<>() );
            for ( Transaction transaction : Transaction.values() )
            {
                combinations.add( BASE.extend( transaction ) );
            }
            for ( Transaction transaction : Transaction.values() )
            {
                for ( WorkLog combination : new ArrayList<>( combinations ) )
                {
                    combinations.add( combination.extend( transaction ) );
                }
            }
            return combinations;
        }

        static Set<WorkLog> combinations()
        {
            Set<WorkLog> combinations = Collections.newSetFromMap( new LinkedHashMap<WorkLog, Boolean>() );
            for ( Transaction transaction : Transaction.values() )
            {
                combinations.add( BASE.extend( transaction ) );
            }
            for ( Transaction transaction : Transaction.values() )
            {
                for ( WorkLog combination : new ArrayList<>( combinations ) )
                {
                    combinations.add( combination.extend( transaction ) );
                }
            }
            return combinations;
        }

Replace Generic With Diamond LinkedHashMap<WorkLog,Boolean> with LinkedHashMap<> in method package combinations() : Set<WorkLog> from class org.neo4j.tools.rebuild.RebuildFromLogsTest.WorkLog


    private void populateCountStore( CountsAccessor.Updater countsUpdater )
    {
        try ( NodeLabelsCache cache = new NodeLabelsCache( numberArrayFactory, highLabelId ) )
        {
            // Count nodes
            superviseDynamicExecution( new NodeCountsStage( Configuration.DEFAULT, cache, nodes, highLabelId, countsUpdater, progressMonitor ) );
            // Count relationships
            superviseDynamicExecution(
                    new RelationshipCountsStage( Configuration.DEFAULT, cache, relationships, highLabelId, highRelationshipTypeId, countsUpdater,
                            numberArrayFactory, progressMonitor ) );
        }
    }

    @Override
    public void initialize( CountsAccessor.Updater countsUpdater )
    {
        progressMonitor.start( nodes.getHighestPossibleIdInUse() + relationships.getHighestPossibleIdInUse() );
        NodeLabelsCache cache = new NodeLabelsCache( numberArrayFactory, highLabelId );
        try
        {
            // Count nodes
            superviseDynamicExecution(
                    new NodeCountsStage( Configuration.DEFAULT, cache, nodes, highLabelId, countsUpdater,
                            progressMonitor ) );
            // Count relationships
            superviseDynamicExecution(
                    new RelationshipCountsStage( Configuration.DEFAULT, cache, relationships, highLabelId,
                            highRelationshipTypeId, countsUpdater, numberArrayFactory, progressMonitor ) );
        }
        finally
        {
            cache.close();
            progressMonitor.completed();
        }
    }

Try With Resources try(NodeLabelsCache cache=new NodeLabelsCache(numberArrayFactory,highLabelId)) in method private populateCountStore(countsUpdater CountsAccessor.Updater) : void from class org.neo4j.kernel.impl.store.CountsComputer


    @Test
    void pagedFileIoMustThrowIfFileIsUnmapped()
    {
        assertTimeout( ofMillis( SHORT_TIMEOUT_MILLIS ), () ->
        {
            configureStandardPageCache();

            PagedFile pagedFile = pageCache.map( file( "a" ), filePageSize );
            closeThisPagedFile( pagedFile );

            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_WRITE_LOCK ) )
            {
                FileIsNotMappedException exception = assertThrows( FileIsNotMappedException.class, cursor::next );
                StringWriter out = new StringWriter();
                exception.printStackTrace( new PrintWriter( out ) );
                assertThat( out.toString(), containsString( "closeThisPagedFile" ) );
            }
        } );
    }

    @Test( timeout = SHORT_TIMEOUT_MILLIS )
    public void pagedFileIoMustThrowIfFileIsUnmapped() throws IOException
    {
        configureStandardPageCache();

        PagedFile pagedFile = pageCache.map( file( "a" ), filePageSize );
        closeThisPagedFile( pagedFile );

        try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_WRITE_LOCK ) )
        {
            try
            {
                cursor.next();
                fail( "cursor.next() on unmapped file did not throw" );
            }
            catch ( FileIsNotMappedException e )
            {
                StringWriter out = new StringWriter();
                e.printStackTrace( new PrintWriter( out ) );
                assertThat( out.toString(), containsString( "closeThisPagedFile" ) );
            }
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(0,PF_SHARED_WRITE_LOCK)) in method package pagedFileIoMustThrowIfFileIsUnmapped() : void from class org.neo4j.io.pagecache.PageCacheTest


    void addIndexDiff( MutableLongDiffSets diff )
    {
        if ( indexDiffs == null )
        {
            indexDiffs = Collections.newSetFromMap( new IdentityHashMap<>() );
        }
        indexDiffs.add( diff );
    }

    void addIndexDiff( MutableLongDiffSets diff )
    {
        if ( indexDiffs == null )
        {
            indexDiffs = Collections.newSetFromMap( new IdentityHashMap<MutableLongDiffSets, Boolean>() );
        }
        indexDiffs.add( diff );
    }

Replace Generic With Diamond IdentityHashMap<MutableLongDiffSets,Boolean> with IdentityHashMap<> in method package addIndexDiff(diff MutableLongDiffSets) : void from class org.neo4j.kernel.impl.api.state.NodeStateImpl


    @Before
    public void setup() throws Exception
    {
        procs.registerComponent( KernelTransaction.class, ctx -> ctx.get( KERNEL_TRANSACTION ), false );
        procs.registerComponent( DependencyResolver.class, ctx -> ctx.get( DEPENDENCY_RESOLVER ), false );
        procs.registerComponent( GraphDatabaseAPI.class, ctx -> ctx.get( GRAPHDATABASEAPI ), false );
        procs.registerComponent( SecurityContext.class, ctx -> ctx.get( SECURITY_CONTEXT ), true );

        procs.registerType( Node.class, NTNode );
        procs.registerType( Relationship.class, NTRelationship );
        procs.registerType( Path.class, NTPath );

        new SpecialBuiltInProcedures( "1.3.37", Edition.enterprise.toString() ).accept( procs );
        procs.registerProcedure( BuiltInProcedures.class );
        procs.registerProcedure( BuiltInDbmsProcedures.class );

        when( tx.acquireStatement() ).thenReturn( statement );
        when( tx.tokenRead() ).thenReturn( tokens );
        when( tx.dataRead() ).thenReturn( read );
        when( tx.schemaRead() ).thenReturn( schemaRead );

        when( tokens.propertyKeyGetAllTokens() ).thenAnswer( asTokens( propKeys ) );
        when( tokens.labelsGetAllTokens() ).thenAnswer( asTokens( labels ) );
        when( tokens.relationshipTypesGetAllTokens() ).thenAnswer( asTokens( relTypes ) );
        when( schemaRead.indexesGetAll() ).thenAnswer(
                i -> Iterators.concat( indexes.iterator(), uniqueIndexes.iterator() ) );
        when( schemaRead.index( anyInt(), anyInt() )).thenAnswer(
                (Answer<CapableIndexReference>) invocationOnMock -> {
                    int label = invocationOnMock.getArgument( 0 );
                    int prop = invocationOnMock.getArgument( 1 );
                    for ( IndexReference index : indexes )
                    {
                        if ( index.label() == label && prop == index.properties()[0] )
                        {
                            return new DefaultCapableIndexReference( index.isUnique(), null,
                                    InMemoryIndexProviderFactory.PROVIDER_DESCRIPTOR, label, prop );
                        }
                    }
                    for ( IndexReference index : uniqueIndexes )
                    {
                        if ( index.label() == label && prop == index.properties()[0] )
                        {
                            return new DefaultCapableIndexReference( index.isUnique(), null,
                                    InMemoryIndexProviderFactory.PROVIDER_DESCRIPTOR, label, prop );
                        }
                    }
                    throw new AssertionError(  );
                } );
        when( schemaRead.constraintsGetAll() ).thenAnswer( i -> constraints.iterator() );

        when( tokens.propertyKeyName( anyInt() ) )
                .thenAnswer( invocation -> propKeys.get( invocation.getArgument( 0 ) ) );
        when( tokens.nodeLabelName( anyInt() ) ).thenAnswer( invocation -> labels.get( invocation.getArgument( 0 ) ) );
        when( tokens.relationshipTypeName( anyInt() ) )
                .thenAnswer( invocation -> relTypes.get( invocation.getArgument( 0 ) ) );

        // Make it appear that labels are in use
        // TODO: We really should just have `labelsInUse()` on the Kernel API directly,
        //       it'd make testing much easier.
        when( schemaRead.constraintsGetForRelationshipType( anyInt() ) ).thenReturn( emptyIterator() );
        when( schemaRead.indexesGetForLabel( anyInt() ) ).thenReturn( emptyIterator() );
        when( schemaRead.constraintsGetForLabel( anyInt() ) ).thenReturn( emptyIterator() );
        when( read.countsForNode( anyInt() ) ).thenReturn( 1L );
        when( read.countsForRelationship( anyInt(), anyInt(), anyInt() ) ).thenReturn( 1L );
        when( schemaRead.indexGetState( any( IndexReference.class ) ) ).thenReturn( InternalIndexState.ONLINE );
    }

    @Before
    public void setup() throws Exception
    {
        procs.registerComponent( KernelTransaction.class, ctx -> ctx.get( KERNEL_TRANSACTION ), false );
        procs.registerComponent( DependencyResolver.class, ctx -> ctx.get( DEPENDENCY_RESOLVER ), false );
        procs.registerComponent( GraphDatabaseAPI.class, ctx -> ctx.get( GRAPHDATABASEAPI ), false );
        procs.registerComponent( SecurityContext.class, ctx -> ctx.get( SECURITY_CONTEXT ), true );

        procs.registerType( Node.class, NTNode );
        procs.registerType( Relationship.class, NTRelationship );
        procs.registerType( Path.class, NTPath );

        new SpecialBuiltInProcedures( "1.3.37", Edition.enterprise.toString() ).accept( procs );
        procs.registerProcedure( BuiltInProcedures.class );
        procs.registerProcedure( BuiltInDbmsProcedures.class );

        when( tx.acquireStatement() ).thenReturn( statement );
        when( tx.tokenRead() ).thenReturn( tokens );
        when( tx.dataRead() ).thenReturn( read );
        when( tx.schemaRead() ).thenReturn( schemaRead );

        when( tokens.propertyKeyGetAllTokens() ).thenAnswer( asTokens( propKeys ) );
        when( tokens.labelsGetAllTokens() ).thenAnswer( asTokens( labels ) );
        when( tokens.relationshipTypesGetAllTokens() ).thenAnswer( asTokens( relTypes ) );
        when( schemaRead.indexesGetAll() ).thenAnswer(
                i -> Iterators.concat( indexes.iterator(), uniqueIndexes.iterator() ) );
    when( schemaRead.index( anyInt(), anyInt() )).thenAnswer( new Answer<CapableIndexReference>()
    {
        @Override
        public CapableIndexReference answer( InvocationOnMock invocationOnMock ) throws Throwable
        {
            int label = invocationOnMock.getArgument( 0 );
            int prop = invocationOnMock.getArgument( 1 );
            for ( IndexReference index : indexes )
            {
                if ( index.label() == label && prop == index.properties()[0] )
                {
                    return new DefaultCapableIndexReference( index.isUnique(), null,
                            InMemoryIndexProviderFactory.PROVIDER_DESCRIPTOR, label, prop );
                }
            }
            for ( IndexReference index : uniqueIndexes )
            {
                if ( index.label() == label && prop == index.properties()[0] )
                {
                    return new DefaultCapableIndexReference( index.isUnique(), null,
                            InMemoryIndexProviderFactory.PROVIDER_DESCRIPTOR, label, prop );
                }
            }
            throw new AssertionError(  );
        }
    } );
        when( schemaRead.constraintsGetAll() ).thenAnswer( i -> constraints.iterator() );

        when( tokens.propertyKeyName( anyInt() ) )
                .thenAnswer( invocation -> propKeys.get( invocation.getArgument( 0 ) ) );
        when( tokens.nodeLabelName( anyInt() ) ).thenAnswer( invocation -> labels.get( invocation.getArgument( 0 ) ) );
        when( tokens.relationshipTypeName( anyInt() ) )
                .thenAnswer( invocation -> relTypes.get( invocation.getArgument( 0 ) ) );

        // Make it appear that labels are in use
        // TODO: We really should just have `labelsInUse()` on the Kernel API directly,
        //       it'd make testing much easier.
        when( schemaRead.constraintsGetForRelationshipType( anyInt() ) ).thenReturn( emptyIterator() );
        when( schemaRead.indexesGetForLabel( anyInt() ) ).thenReturn( emptyIterator() );
        when( schemaRead.constraintsGetForLabel( anyInt() ) ).thenReturn( emptyIterator() );
        when( read.countsForNode( anyInt() ) ).thenReturn( 1L );
        when( read.countsForRelationship( anyInt(), anyInt(), anyInt() ) ).thenReturn( 1L );
        when( schemaRead.indexGetState( any( IndexReference.class ) ) ).thenReturn( InternalIndexState.ONLINE );
    }

Replace Anonymous With Lambda org.neo4j.kernel.builtinprocs.BuiltInProceduresTest.setup.thenAnswer.new Answer<CapableIndexReference> with invocationOnMock -> {int label=invocationOnMock.getArgument(0); in method public setup() : void from class org.neo4j.kernel.builtinprocs.BuiltInProceduresTest


    @Test
    public void shouldAbortStoreScanWaitOnDrop() throws Exception
    {
        // given the proxy structure
        FakePopulatingIndexProxy delegate = new FakePopulatingIndexProxy();
        FlippableIndexProxy flipper = new FlippableIndexProxy( delegate );
        OtherThreadExecutor<Void> waiter = cleanup.add( new OtherThreadExecutor<>( "Waiter", null ) );

        // and a thread stuck in the awaitStoreScanCompletion loop
        Future<Object> waiting = waiter.executeDontWait( state -> flipper.awaitStoreScanCompleted() );
        while ( !delegate.awaitCalled )
        {
            Thread.sleep( 10 );
        }

        // when
        flipper.drop();

        // then the waiting should quickly be over
        waiting.get( 10, SECONDS );
    }

    @Test
    public void shouldAbortStoreScanWaitOnDrop() throws Exception
    {
        // given the proxy structure
        FakePopulatingIndexProxy delegate = new FakePopulatingIndexProxy();
        FlippableIndexProxy flipper = new FlippableIndexProxy( delegate );
        OtherThreadExecutor<Void> waiter = cleanup.add( new OtherThreadExecutor<Void>( "Waiter", null ) );

        // and a thread stuck in the awaitStoreScanCompletion loop
        Future<Object> waiting = waiter.executeDontWait( state -> flipper.awaitStoreScanCompleted() );
        while ( !delegate.awaitCalled )
        {
            Thread.sleep( 10 );
        }

        // when
        flipper.drop();

        // then the waiting should quickly be over
        waiting.get( 10, SECONDS );
    }

Replace Generic With Diamond OtherThreadExecutor<Void> with OtherThreadExecutor<> in method public shouldAbortStoreScanWaitOnDrop() : void from class org.neo4j.kernel.impl.api.index.FlippableIndexProxyTest


    @Test
    public void shouldNotOpenStoreWithNodesOrRelationshipsInIt() throws Exception
    {
        // GIVEN
        someDataInTheDatabase();

        // WHEN
        try
        {
            RecordFormats recordFormats = RecordFormatSelector.selectForConfig( Config.defaults(), NullLogProvider.getInstance() );
            try ( BatchingNeoStores store = BatchingNeoStores.batchingNeoStores( storage.fileSystem(), storage.directory().absolutePath(), recordFormats,
                    DEFAULT, NullLogService.getInstance(), EMPTY, Config.defaults() ) )
            {
                store.createNew();
                fail( "Should fail on existing data" );
            }
        }
        catch ( IllegalStateException e )
        {
            // THEN
            assertThat( e.getMessage(), containsString( "already contains" ) );
        }
    }

    @Test
    public void shouldNotOpenStoreWithNodesOrRelationshipsInIt() throws Exception
    {
        // GIVEN
        someDataInTheDatabase();

        // WHEN
        try
        {
            RecordFormats recordFormats = RecordFormatSelector.selectForConfig( Config.defaults(),
                    NullLogProvider.getInstance() );
            BatchingNeoStores store = BatchingNeoStores.batchingNeoStores( storage.fileSystem(), storage.directory().absolutePath(),
                    recordFormats, DEFAULT, NullLogService.getInstance(), EMPTY, Config.defaults() );
            store.createNew();
            fail( "Should fail on existing data" );
        }
        catch ( IllegalStateException e )
        {
            // THEN
            assertThat( e.getMessage(), containsString( "already contains" ) );
        }
    }

Try With Resources try(BatchingNeoStores store=BatchingNeoStores.batchingNeoStores(storage.fileSystem(),storage.directory().absolutePath(),recordFormats,DEFAULT,NullLogService.getInstance(),EMPTY,Config.defaults())) in method public shouldNotOpenStoreWithNodesOrRelationshipsInIt() : void from class org.neo4j.unsafe.impl.batchimport.store.BatchingNeoStoresTest


        private Election( WinnerStrategy winnerStrategy )
        {
            this.winnerStrategy = winnerStrategy;
            this.votes = new HashMap<>();
        }

        private Election( WinnerStrategy winnerStrategy )
        {
            this.winnerStrategy = winnerStrategy;
            this.votes = new HashMap<InstanceId, Vote>();
        }

Replace Generic With Diamond HashMap<InstanceId,Vote> with HashMap<> in method private Election(winnerStrategy WinnerStrategy) from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.context.ElectionContextImpl.Election


    @Test
    public void testElectionOkNoFailed()
    {
        Set<InstanceId> failed = new HashSet<>();

        baseTestForElectionOk( failed, false );
    }

    @Test
    public void testElectionOkNoFailed()
    {
        Set<InstanceId> failed = new HashSet<InstanceId>();

        baseTestForElectionOk( failed, false );
    }

Replace Generic With Diamond HashSet<InstanceId> with HashSet<> in method public testElectionOkNoFailed() : void from class org.neo4j.cluster.protocol.election.ElectionContextTest


    @Test
    public void testElectionOkLessThanQuorumFailed()
    {
        Set<InstanceId> failed = new HashSet<>();
        failed.add( new InstanceId( 1 ) );

        baseTestForElectionOk( failed, false );
    }

    @Test
    public void testElectionOkLessThanQuorumFailed()
    {
        Set<InstanceId> failed = new HashSet<InstanceId>();
        failed.add( new InstanceId( 1 ) );

        baseTestForElectionOk( failed, false );
    }

Replace Generic With Diamond HashSet<InstanceId> with HashSet<> in method public testElectionOkLessThanQuorumFailed() : void from class org.neo4j.cluster.protocol.election.ElectionContextTest


    @Test
    public void testElectionNotOkMoreThanQuorumFailed()
    {
        Set<InstanceId> failed = new HashSet<>();
        failed.add( new InstanceId( 1 ) );
        failed.add( new InstanceId( 2 ) );

        baseTestForElectionOk( failed, true );
    }

    @Test
    public void testElectionNotOkMoreThanQuorumFailed()
    {
        Set<InstanceId> failed = new HashSet<InstanceId>();
        failed.add( new InstanceId( 1 ) );
        failed.add( new InstanceId( 2 ) );

        baseTestForElectionOk( failed, true );
    }

Replace Generic With Diamond HashSet<InstanceId> with HashSet<> in method public testElectionNotOkMoreThanQuorumFailed() : void from class org.neo4j.cluster.protocol.election.ElectionContextTest


    private void create( File file, FileSystemAbstraction fileSystem, long indexVersion ) throws IOException
    {
        if ( fileSystem.fileExists( file ) && fileSystem.getFileSize( file ) > 0 )
        {
            throw new IllegalArgumentException( file + " already exist" );
        }

        try ( StoreChannel fileChannel = fileSystem.open( file, OpenMode.READ_WRITE ) )
        {
            write( fileChannel, System.currentTimeMillis(), random.nextLong(), 0, 1, indexVersion );
        }
    }

    private void create( File file, FileSystemAbstraction fileSystem, long indexVersion ) throws IOException
    {
        if ( fileSystem.fileExists( file ) && fileSystem.getFileSize( file ) > 0 )
        {
            throw new IllegalArgumentException( file + " already exist" );
        }

        StoreChannel fileChannel = null;
        try
        {
            fileChannel = fileSystem.open( file, OpenMode.READ_WRITE );
            write( fileChannel, System.currentTimeMillis(), random.nextLong(),
                    0, 1, indexVersion );
        }
        finally
        {
            if ( fileChannel != null )
            {
                fileChannel.close();
            }
        }
    }

Try With Resources try(StoreChannel fileChannel=fileSystem.open(file,OpenMode.READ_WRITE)) in method private create(file File, fileSystem FileSystemAbstraction, indexVersion long) : void from class org.neo4j.kernel.impl.index.IndexProviderStore


    @Override
    public void setProperty( String key, Object value )
    {
        KernelTransaction transaction = spi.kernelTransaction();
        int propertyKeyId;
        try
        {
            propertyKeyId = transaction.tokenWrite().propertyKeyGetOrCreateForName( key );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e );
        }

        try ( Statement ignore = transaction.acquireStatement() )
        {
            transaction.dataWrite().nodeSetProperty( nodeId, propertyKeyId, Values.of( value, false ) );
        }
        catch ( ConstraintValidationException e )
        {
            throw new ConstraintViolationException(
                    e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
        }
        catch ( IllegalArgumentException e )
        {
            // Trying to set an illegal value is a critical error - fail this transaction
            spi.failTransaction();
            throw e;
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( AutoIndexingKernelException e )
        {
            throw new IllegalStateException( "Auto indexing encountered a failure while setting property: "
                                             + e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public void setProperty( String key, Object value )
    {
        KernelTransaction transaction = spi.kernelTransaction();
        int propertyKeyId;
        try
        {
            propertyKeyId = transaction.tokenWrite().propertyKeyGetOrCreateForName( key );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e );
        }

        try
        {
            transaction.dataWrite().nodeSetProperty( nodeId, propertyKeyId, Values.of( value, false ) );
        }
        catch ( ConstraintValidationException e )
        {
            throw new ConstraintViolationException(
                    e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
        }
        catch ( IllegalArgumentException e )
        {
            // Trying to set an illegal value is a critical error - fail this transaction
            spi.failTransaction();
            throw e;
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( AutoIndexingKernelException e )
        {
            throw new IllegalStateException( "Auto indexing encountered a failure while setting property: "
                                             + e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=transaction.acquireStatement()) in method public setProperty(key String, value Object) : void from class org.neo4j.kernel.impl.core.NodeProxy


    @Override
    public void addLabel( Label label )
    {
        KernelTransaction transaction = spi.kernelTransaction();
        try ( Statement ignore = transaction.acquireStatement() )
        {
            transaction.dataWrite().nodeAddLabel( getId(),
                    transaction.tokenWrite().labelGetOrCreateForName( label.name() ) );
        }
        catch ( ConstraintValidationException e )
        {
            throw new ConstraintViolationException(
                    e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new ConstraintViolationException( format( "Invalid label name '%s'.", label.name() ), e );
        }
        catch ( TooManyLabelsException e )
        {
            throw new ConstraintViolationException( "Unable to add label.", e );
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( "No node with id " + getId() + " found.", e );
        }
        catch ( KernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public void addLabel( Label label )
    {
        KernelTransaction transaction = spi.kernelTransaction();
        try
        {
            transaction.dataWrite().nodeAddLabel( getId(),
                    transaction.tokenWrite().labelGetOrCreateForName( label.name() ) );
        }
        catch ( ConstraintValidationException e )
        {
            throw new ConstraintViolationException(
                    e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new ConstraintViolationException( format( "Invalid label name '%s'.", label.name() ), e );
        }
        catch ( TooManyLabelsException e )
        {
            throw new ConstraintViolationException( "Unable to add label.", e );
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( "No node with id " + getId() + " found.", e );
        }
        catch ( KernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=transaction.acquireStatement()) in method public addLabel(label Label) : void from class org.neo4j.kernel.impl.core.NodeProxy


    @Override
    public Relationship getRelationshipById( long id )
    {
        if ( id < 0 )
        {
            throw new NotFoundException( format( "Relationship %d not found", id ),
                    new EntityNotFoundException( EntityType.RELATIONSHIP, id ) );
        }

        KernelTransaction ktx = statementContext.getKernelTransactionBoundToThisThread( true );
        assertTransactionOpen( ktx );
        try ( Statement ignore = statementContext.get() )
        {
            if ( !ktx.dataRead().relationshipExists( id ) )
            {
                throw new NotFoundException( format( "Relationship %d not found", id ),
                        new EntityNotFoundException( EntityType.RELATIONSHIP, id ) );
            }
            return newRelationshipProxy( id );
        }
    }

    @Override
    public Relationship getRelationshipById( long id )
    {
        if ( id < 0 )
        {
            throw new NotFoundException( format( "Relationship %d not found", id ),
                    new EntityNotFoundException( EntityType.RELATIONSHIP, id ) );
        }
        try ( Statement statement = statementContext.get() )
        {
            try
            {
                RelationshipProxy relationship = newRelationshipProxy( id );
                statement.readOperations().relationshipVisit( id, relationship );
                return relationship;
            }
            catch ( EntityNotFoundException e )
            {
                throw new NotFoundException( format( "Relationship %d not found", id ), e );
            }
        }
    }

Try With Resources try(Statement ignore=statementContext.get()) in method public getRelationshipById(id long) : Relationship from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    public static <VALUE> PrimitiveIntObjectMap<VALUE> intObjectMap( int initialCapacity )
    {
        return new PrimitiveIntObjectHashMap<>( new IntKeyObjectValueTable<>( initialCapacity ), NO_MONITOR );
    }

    public static <VALUE> PrimitiveIntObjectMap<VALUE> intObjectMap( int initialCapacity )
    {
        return new PrimitiveIntObjectHashMap<>( new IntKeyObjectValueTable<VALUE>( initialCapacity ), NO_MONITOR );
    }

Replace Generic With Diamond PrimitiveIntObjectHashMap<> with PrimitiveIntObjectHashMap<> in method public intObjectMap(initialCapacity int) : PrimitiveIntObjectMap<VALUE> from class org.neo4j.collection.primitive.Primitive


    @Test
    public void shouldReadYourOwnWrites() throws Exception
    {
        try ( Transaction tx = env.graph().beginTx() )
        {
            Node node = env.graph().createNode( Label.label( "A" ) );
            node.setProperty( "prop", "one" );
            tx.success();
        }

        BinaryLatch latch = new BinaryLatch();

        long dbVersion = env.lastClosedTxId();
        Thread thread = new Thread( () -> {
            try ( BoltStateMachine machine = env.newMachine( boltChannel ) )
            {
                machine.init( USER_AGENT, emptyMap(), null );
                latch.await();
                machine.run( "MATCH (n:A) SET n.prop = 'two'", EMPTY_MAP, nullResponseHandler() );
                machine.pullAll( nullResponseHandler() );
            }
            catch ( BoltConnectionFatality connectionFatality )
            {
                throw new RuntimeException( connectionFatality );
            }
        } );
        thread.start();

        long dbVersionAfterWrite = dbVersion + 1;
        try ( BoltStateMachine machine = env.newMachine( boltChannel ) )
        {
            BoltResponseRecorder recorder = new BoltResponseRecorder();
            machine.init( USER_AGENT, emptyMap(), null );
            latch.release();
            final String bookmark = "neo4j:bookmark:v1:tx" + Long.toString( dbVersionAfterWrite );
            machine.run( "BEGIN", ValueUtils.asMapValue( singletonMap( "bookmark", bookmark ) ), nullResponseHandler() );
            machine.pullAll( recorder );
            machine.run( "MATCH (n:A) RETURN n.prop", EMPTY_MAP, nullResponseHandler() );
            machine.pullAll( recorder );
            machine.run( "COMMIT", EMPTY_MAP, nullResponseHandler() );
            machine.pullAll( recorder );

            assertThat( recorder.nextResponse(), succeededWithMetadata( "bookmark", BOOKMARK_PATTERN ) );
            assertThat( recorder.nextResponse(), succeededWithRecord( "two" ) );
            assertThat( recorder.nextResponse(), succeededWithMetadata( "bookmark", BOOKMARK_PATTERN ) );
        }

        thread.join();
    }

    @Test
    public void shouldReadYourOwnWrites() throws Exception
    {
        try ( Transaction tx = env.graph().beginTx() )
        {
            Node node = env.graph().createNode( Label.label( "A" ) );
            node.setProperty( "prop", "one" );
            tx.success();
        }

        BinaryLatch latch = new BinaryLatch();

        long dbVersion = env.lastClosedTxId();
        Thread thread = new Thread()
        {
            @Override
            public void run()
            {
                try ( BoltStateMachine machine = env.newMachine( boltChannel ) )
                {
                    machine.init( USER_AGENT, emptyMap(), null );
                    latch.await();
                    machine.run( "MATCH (n:A) SET n.prop = 'two'", EMPTY_MAP, nullResponseHandler() );
                    machine.pullAll( nullResponseHandler() );
                }
                catch ( BoltConnectionFatality connectionFatality )
                {
                    throw new RuntimeException( connectionFatality );
                }
            }
        };
        thread.start();

        long dbVersionAfterWrite = dbVersion + 1;
        try ( BoltStateMachine machine = env.newMachine( boltChannel ) )
        {
            BoltResponseRecorder recorder = new BoltResponseRecorder();
            machine.init( USER_AGENT, emptyMap(), null );
            latch.release();
            final String bookmark = "neo4j:bookmark:v1:tx" + Long.toString( dbVersionAfterWrite );
            machine.run( "BEGIN", ValueUtils.asMapValue( singletonMap( "bookmark", bookmark ) ), nullResponseHandler() );
            machine.pullAll( recorder );
            machine.run( "MATCH (n:A) RETURN n.prop", EMPTY_MAP, nullResponseHandler() );
            machine.pullAll( recorder );
            machine.run( "COMMIT", EMPTY_MAP, nullResponseHandler() );
            machine.pullAll( recorder );

            assertThat( recorder.nextResponse(), succeededWithMetadata( "bookmark", BOOKMARK_PATTERN ) );
            assertThat( recorder.nextResponse(), succeededWithRecord( "two" ) );
            assertThat( recorder.nextResponse(), succeededWithMetadata( "bookmark", BOOKMARK_PATTERN ) );
        }

        thread.join();
    }

Replace Anonymous With Lambda org.neo4j.bolt.v1.runtime.integration.TransactionIT.shouldReadYourOwnWrites.thread.new Thread with () -> {try(BoltStateMachine machine=env.newMachine(boltChannel))machine.init(USER_AGENT,emptyMap(),null); in method public shouldReadYourOwnWrites() : void from class org.neo4j.bolt.v1.runtime.integration.TransactionIT


    @Test
    public void shouldTerminateQueriesEvenIfUsingPeriodicCommit() throws Exception
    {
        // Spawns a throttled HTTP server, runs a PERIODIC COMMIT that fetches data from this server,
        // and checks that the query able to be terminated

        // We start with 3, because that is how many actors we have -
        // 1. the http server
        // 2. the running query
        // 3. the one terminating 2
        final DoubleLatch latch = new DoubleLatch( 3, true );

        // This is used to block the http server between the first and second batch
        final Barrier.Control barrier = new Barrier.Control();

        // Serve CSV via local web server, let Jetty find a random port for us
        Server server = createHttpServer( latch, barrier, 20, 30 );
        server.start();
        int localPort = getLocalPort( server );

        final BoltStateMachine[] machine = {null};

        Thread thread = new Thread( () -> {
            try ( BoltStateMachine stateMachine = env.newMachine( mock( BoltChannel.class ) ) )
            {
                machine[0] = stateMachine;
                stateMachine.init( USER_AGENT, emptyMap(), null );
                String query = format( "USING PERIODIC COMMIT 10 LOAD CSV FROM 'http://localhost:%d' AS line " +
                                       "CREATE (n:A {id: line[0], square: line[1]}) " +
                                       "WITH count(*) as number " +
                                       "CREATE (n:ShouldNotExist)",
                                       localPort );
                try
                {
                    latch.start();
                    stateMachine.run( query, EMPTY_MAP, nullResponseHandler() );
                    stateMachine.pullAll( nullResponseHandler() );
                }
                finally
                {
                    latch.finish();
                }
            }
            catch ( BoltConnectionFatality connectionFatality )
            {
                throw new RuntimeException( connectionFatality );
            }
        } );
        thread.setName( "query runner" );
        thread.start();

        // We block this thread here, waiting for the http server to spin up and the running query to get started
        latch.startAndWaitForAllToStart();
        Thread.sleep( 1000 );

        // This is the call that RESETs the Bolt connection and will terminate the running query
        machine[0].reset( nullResponseHandler() );

        barrier.release();

        // We block again here, waiting for the running query to have been terminated, and for the server to have
        // wrapped up and finished streaming http results
        latch.finishAndWaitForAllToFinish();

        // And now we check that the last node did not get created
        try ( Transaction ignored = env.graph().beginTx() )
        {
            assertFalse( "Query was not terminated in time - nodes were created!",
                         env.graph().findNodes( Label.label( "ShouldNotExist" ) ).hasNext() );
        }
    }

    @Test
    public void shouldTerminateQueriesEvenIfUsingPeriodicCommit() throws Exception
    {
        // Spawns a throttled HTTP server, runs a PERIODIC COMMIT that fetches data from this server,
        // and checks that the query able to be terminated

        // We start with 3, because that is how many actors we have -
        // 1. the http server
        // 2. the running query
        // 3. the one terminating 2
        final DoubleLatch latch = new DoubleLatch( 3, true );

        // This is used to block the http server between the first and second batch
        final Barrier.Control barrier = new Barrier.Control();

        // Serve CSV via local web server, let Jetty find a random port for us
        Server server = createHttpServer( latch, barrier, 20, 30 );
        server.start();
        int localPort = getLocalPort( server );

        final BoltStateMachine[] machine = {null};

        Thread thread = new Thread()
        {
            @Override
            public void run()
            {
                try ( BoltStateMachine stateMachine = env.newMachine( mock( BoltChannel.class ) ) )
                {
                    machine[0] = stateMachine;
                    stateMachine.init( USER_AGENT, emptyMap(), null );
                    String query = format( "USING PERIODIC COMMIT 10 LOAD CSV FROM 'http://localhost:%d' AS line " +
                                           "CREATE (n:A {id: line[0], square: line[1]}) " +
                                           "WITH count(*) as number " +
                                           "CREATE (n:ShouldNotExist)",
                                           localPort );
                    try
                    {
                        latch.start();
                        stateMachine.run( query, EMPTY_MAP, nullResponseHandler() );
                        stateMachine.pullAll( nullResponseHandler() );
                    }
                    finally
                    {
                        latch.finish();
                    }
                }
                catch ( BoltConnectionFatality connectionFatality )
                {
                    throw new RuntimeException( connectionFatality );
                }
            }
        };
        thread.setName( "query runner" );
        thread.start();

        // We block this thread here, waiting for the http server to spin up and the running query to get started
        latch.startAndWaitForAllToStart();
        Thread.sleep( 1000 );

        // This is the call that RESETs the Bolt connection and will terminate the running query
        machine[0].reset( nullResponseHandler() );

        barrier.release();

        // We block again here, waiting for the running query to have been terminated, and for the server to have
        // wrapped up and finished streaming http results
        latch.finishAndWaitForAllToFinish();

        // And now we check that the last node did not get created
        try ( Transaction ignored = env.graph().beginTx() )
        {
            assertFalse( "Query was not terminated in time - nodes were created!",
                         env.graph().findNodes( Label.label( "ShouldNotExist" ) ).hasNext() );
        }
    }

Replace Anonymous With Lambda org.neo4j.bolt.v1.runtime.integration.TransactionIT.shouldTerminateQueriesEvenIfUsingPeriodicCommit.thread.new Thread with () -> {try(BoltStateMachine stateMachine=env.newMachine(mock(BoltChannel.class)))machine[0]=stateMachine; in method public shouldTerminateQueriesEvenIfUsingPeriodicCommit() : void from class org.neo4j.bolt.v1.runtime.integration.TransactionIT


    @Override
    public Iterator<T> iterator()
    {
        return new FilteringIterator<>( source.iterator(), predicate );
    }

    @Override
    public Iterator<T> iterator()
    {
        return new FilteringIterator<T>( source.iterator(), predicate );
    }

Replace Generic With Diamond FilteringIterator<T> with FilteringIterator<> in method public iterator() : Iterator<T> from class org.neo4j.helpers.collection.FilteringIterable


    public static <T> Iterable<T> notNull( Iterable<T> source )
    {
        return new FilteringIterable<>( source, Predicates.notNull() );
    }

    public static <T> Iterable<T> notNull( Iterable<T> source )
    {
        return new FilteringIterable<T>( source, Predicates.notNull() );
    }

Replace Generic With Diamond FilteringIterable<T> with FilteringIterable<> in method public notNull(source Iterable<T>) : Iterable<T> from class org.neo4j.helpers.collection.FilteringIterable


    public static <T> Iterable<T> noDuplicates( Iterable<T> source )
    {
        return new FilteringIterable<>( source, Predicates.noDuplicates() );
    }

    public static <T> Iterable<T> noDuplicates( Iterable<T> source )
    {
        return new FilteringIterable<T>( source, Predicates.noDuplicates() );
    }

Replace Generic With Diamond FilteringIterable<T> with FilteringIterable<> in method public noDuplicates(source Iterable<T>) : Iterable<T> from class org.neo4j.helpers.collection.FilteringIterable


    /**
     * Creates a collection from an iterable.
     *
     * @param iterable The iterable to create the collection from.
     * @param <T> The generic type of both the iterable and the collection.
     * @return a collection containing all items from the iterable.
     */
    public static <T> Collection<T> asCollection( Iterable<T> iterable )
    {
        return addToCollection( iterable, new ArrayList<>() );
    }

    /**
     * Creates a collection from an iterable.
     *
     * @param iterable The iterable to create the collection from.
     * @param <T> The generic type of both the iterable and the collection.
     * @return a collection containing all items from the iterable.
     */
    public static <T> Collection<T> asCollection( Iterable<T> iterable )
    {
        return addToCollection( iterable, new ArrayList<T>() );
    }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method public asCollection(iterable Iterable<T>) : Collection<T> from class org.neo4j.helpers.collection.Iterables


    public static <T> List<T> asList( Iterable<T> iterator )
    {
        return addToCollection( iterator, new ArrayList<>() );
    }

    public static <T> List<T> asList( Iterable<T> iterator )
    {
        return addToCollection( iterator, new ArrayList<T>() );
    }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method public asList(iterator Iterable<T>) : List<T> from class org.neo4j.helpers.collection.Iterables


    /**
     * Creates a {@link Set} from an {@link Iterable}.
     *
     * @param iterable The items to create the set from.
     * @param <T> The generic type of items.
     * @return a set containing all items from the {@link Iterable}.
     */
    public static <T> Set<T> asSet( Iterable<T> iterable )
    {
        return addToCollection( iterable, new HashSet<>() );
    }

    /**
     * Creates a {@link Set} from an {@link Iterable}.
     *
     * @param iterable The items to create the set from.
     * @param <T> The generic type of items.
     * @return a set containing all items from the {@link Iterable}.
     */
    public static <T> Set<T> asSet( Iterable<T> iterable )
    {
        return addToCollection( iterable, new HashSet<T>() );
    }

Replace Generic With Diamond HashSet<T> with HashSet<> in method public asSet(iterable Iterable<T>) : Set<T> from class org.neo4j.helpers.collection.Iterables


    public static <T> Collection<T> asCollection( Iterator<T> iterable )
    {
        return addToCollection( iterable, new ArrayList<>() );
    }

    public static <T> Collection<T> asCollection( Iterator<T> iterable )
    {
        return addToCollection( iterable, new ArrayList<T>() );
    }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method public asCollection(iterable Iterator<T>) : Collection<T> from class org.neo4j.helpers.collection.Iterators


    public static <T> List<T> asList( Iterator<T> iterator )
    {
        return addToCollection( iterator, new ArrayList<>() );
    }

    public static <T> List<T> asList( Iterator<T> iterator )
    {
        return addToCollection( iterator, new ArrayList<T>() );
    }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method public asList(iterator Iterator<T>) : List<T> from class org.neo4j.helpers.collection.Iterators


    public static <T> Set<T> asSet( Iterator<T> iterator )
    {
        return addToCollection( iterator, new HashSet<>() );
    }

    public static <T> Set<T> asSet( Iterator<T> iterator )
    {
        return addToCollection( iterator, new HashSet<T>() );
    }

Replace Generic With Diamond HashSet<T> with HashSet<> in method public asSet(iterator Iterator<T>) : Set<T> from class org.neo4j.helpers.collection.Iterators


    @Override
    public ResourceIterator<T> iterator()
    {
        return new LimitingResourceIterator<>( Iterators.asResourceIterator( source.iterator() ), limit );
    }

    @Override
    public ResourceIterator<T> iterator()
    {
        return new LimitingResourceIterator<T>( Iterators.asResourceIterator( source.iterator() ), limit );
    }

Replace Generic With Diamond LimitingResourceIterator<T> with LimitingResourceIterator<> in method public iterator() : ResourceIterator<T> from class org.neo4j.helpers.collection.LimitingResourceIterable


    public static <K,V> Map<K, V> toMap( Iterator<Pair<K, V>> pairs )
    {
        Map<K,V> result = new HashMap<>();
        while ( pairs.hasNext() )
        {
            Pair<K,V> pair = pairs.next();
            result.put( pair.first(), pair.other() );
        }
        return result;
    }

    public static <K,V> Map<K, V> toMap( Iterator<Pair<K, V>> pairs )
    {
        Map<K,V> result = new HashMap<K,V>();
        while ( pairs.hasNext() )
        {
            Pair<K,V> pair = pairs.next();
            result.put( pair.first(), pair.other() );
        }
        return result;
    }

Replace Generic With Diamond HashMap<K,V> with HashMap<> in method public toMap(pairs Iterator<Pair<K,V>>) : Map<K,V> from class org.neo4j.helpers.collection.MapUtil


    @Test
    public void testCachingIterator()
    {
        Iterator<Integer> source = new RangeIterator( 8 );
        CachingIterator<Integer> caching = new CachingIterator<>( source );

        try
        {
            caching.previous();
            fail( "Should throw exception" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }

        try
        {
            caching.current();
            fail( "Should throw exception" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }

        // Next and previous
        assertEquals( 0, caching.position() );
        assertTrue( caching.hasNext() );
        assertEquals( 0, caching.position() );
        assertFalse( caching.hasPrevious() );
        assertEquals( (Integer) 0, caching.next() );
        assertTrue( caching.hasNext() );
        assertTrue( caching.hasPrevious() );
        assertEquals( (Integer) 1, caching.next() );
        assertTrue( caching.hasPrevious() );
        assertEquals( (Integer) 1, caching.current() );
        assertEquals( (Integer) 2, caching.next() );
        assertEquals( (Integer) 2, caching.current() );
        assertEquals( (Integer) 3, (Integer) caching.position() );
        assertEquals( (Integer) 2, caching.current() );
        assertTrue( caching.hasPrevious() );
        assertEquals( (Integer) 2, caching.previous() );
        assertEquals( (Integer) 2, caching.current() );
        assertEquals( (Integer) 2, (Integer) caching.position() );
        assertEquals( (Integer) 1, caching.previous() );
        assertEquals( (Integer) 1, caching.current() );
        assertEquals( (Integer) 1, (Integer) caching.position() );
        assertEquals( (Integer) 0, caching.previous() );
        assertEquals( (Integer) 0, (Integer) caching.position() );
        assertFalse( caching.hasPrevious() );

        // Positioning
        try
        {
            caching.position( -1 );
            fail( "Shouldn't be able to set a lower value than 0" );
        }
        catch ( IllegalArgumentException e )
        { /* Good */ }
        assertEquals( (Integer) 0, caching.current() );
        assertEquals( 0, caching.position( 3 ) );
        try
        {
            caching.current();
            fail( "Shouldn't be able to call current() after a call to position(int)" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }
        assertTrue( caching.hasNext() );
        assertEquals( (Integer) 3, caching.next() );
        assertEquals( (Integer) 3, caching.current() );
        assertTrue( caching.hasPrevious() );
        assertEquals( (Integer) 4, caching.next() );
        assertEquals( 5, caching.position() );
        assertEquals( (Integer) 4, caching.previous() );
        assertEquals( (Integer) 4, caching.current() );
        assertEquals( (Integer) 4, caching.current() );
        assertEquals( 4, caching.position() );
        assertEquals( (Integer) 3, caching.previous() );
        assertEquals( 3, caching.position() );
        try
        {
            caching.position( 9 );
            fail( "Shouldn't be able to set a position which is too big" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }
        assertEquals( 3, caching.position( 8 ) );
        assertTrue( caching.hasPrevious() );
        assertFalse( caching.hasNext() );
        try
        {
            caching.next();
            fail( "Shouldn't be able to go beyond last item" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }
        assertEquals( 8, caching.position() );
        assertEquals( (Integer) 7, caching.previous() );
        assertEquals( (Integer) 6, caching.previous() );
        assertEquals( 6, caching.position( 0 ) );
        assertEquals( (Integer) 0, caching.next() );
    }

    @Test
    public void testCachingIterator()
    {
        Iterator<Integer> source = new RangeIterator( 8 );
        CachingIterator<Integer> caching = new CachingIterator<Integer>( source );

        try
        {
            caching.previous();
            fail( "Should throw exception" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }

        try
        {
            caching.current();
            fail( "Should throw exception" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }

        // Next and previous
        assertEquals( 0, caching.position() );
        assertTrue( caching.hasNext() );
        assertEquals( 0, caching.position() );
        assertFalse( caching.hasPrevious() );
        assertEquals( (Integer) 0, caching.next() );
        assertTrue( caching.hasNext() );
        assertTrue( caching.hasPrevious() );
        assertEquals( (Integer) 1, caching.next() );
        assertTrue( caching.hasPrevious() );
        assertEquals( (Integer) 1, caching.current() );
        assertEquals( (Integer) 2, caching.next() );
        assertEquals( (Integer) 2, caching.current() );
        assertEquals( (Integer) 3, (Integer) caching.position() );
        assertEquals( (Integer) 2, caching.current() );
        assertTrue( caching.hasPrevious() );
        assertEquals( (Integer) 2, caching.previous() );
        assertEquals( (Integer) 2, caching.current() );
        assertEquals( (Integer) 2, (Integer) caching.position() );
        assertEquals( (Integer) 1, caching.previous() );
        assertEquals( (Integer) 1, caching.current() );
        assertEquals( (Integer) 1, (Integer) caching.position() );
        assertEquals( (Integer) 0, caching.previous() );
        assertEquals( (Integer) 0, (Integer) caching.position() );
        assertFalse( caching.hasPrevious() );

        // Positioning
        try
        {
            caching.position( -1 );
            fail( "Shouldn't be able to set a lower value than 0" );
        }
        catch ( IllegalArgumentException e )
        { /* Good */ }
        assertEquals( (Integer) 0, caching.current() );
        assertEquals( 0, caching.position( 3 ) );
        try
        {
            caching.current();
            fail( "Shouldn't be able to call current() after a call to position(int)" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }
        assertTrue( caching.hasNext() );
        assertEquals( (Integer) 3, caching.next() );
        assertEquals( (Integer) 3, caching.current() );
        assertTrue( caching.hasPrevious() );
        assertEquals( (Integer) 4, caching.next() );
        assertEquals( 5, caching.position() );
        assertEquals( (Integer) 4, caching.previous() );
        assertEquals( (Integer) 4, caching.current() );
        assertEquals( (Integer) 4, caching.current() );
        assertEquals( 4, caching.position() );
        assertEquals( (Integer) 3, caching.previous() );
        assertEquals( 3, caching.position() );
        try
        {
            caching.position( 9 );
            fail( "Shouldn't be able to set a position which is too big" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }
        assertEquals( 3, caching.position( 8 ) );
        assertTrue( caching.hasPrevious() );
        assertFalse( caching.hasNext() );
        try
        {
            caching.next();
            fail( "Shouldn't be able to go beyond last item" );
        }
        catch ( NoSuchElementException e )
        { /* Good */ }
        assertEquals( 8, caching.position() );
        assertEquals( (Integer) 7, caching.previous() );
        assertEquals( (Integer) 6, caching.previous() );
        assertEquals( 6, caching.position( 0 ) );
        assertEquals( (Integer) 0, caching.next() );
    }

Replace Generic With Diamond CachingIterator<Integer> with CachingIterator<> in method public testCachingIterator() : void from class org.neo4j.helpers.collection.TestCommonIterators


    @Test
    public void testPagingIterator()
    {
        Iterator<Integer> source = new RangeIterator( 24 );
        PagingIterator<Integer> pager = new PagingIterator<>( source, 10 );
        assertEquals( 0, pager.page() );
        assertTrue( pager.hasNext() );
        assertPage( pager.nextPage(), 10, 0 );
        assertTrue( pager.hasNext() );

        assertEquals( 1, pager.page() );
        assertTrue( pager.hasNext() );
        assertPage( pager.nextPage(), 10, 10 );
        assertTrue( pager.hasNext() );

        assertEquals( 2, pager.page() );
        assertTrue( pager.hasNext() );
        assertPage( pager.nextPage(), 4, 20 );
        assertFalse( pager.hasNext() );

        pager.page( 1 );
        assertEquals( 1, pager.page() );
        assertTrue( pager.hasNext() );
        assertPage( pager.nextPage(), 10, 10 );
        assertTrue( pager.hasNext() );
    }

    @Test
    public void testPagingIterator()
    {
        Iterator<Integer> source = new RangeIterator( 24 );
        PagingIterator<Integer> pager = new PagingIterator<Integer>( source, 10 );
        assertEquals( 0, pager.page() );
        assertTrue( pager.hasNext() );
        assertPage( pager.nextPage(), 10, 0 );
        assertTrue( pager.hasNext() );

        assertEquals( 1, pager.page() );
        assertTrue( pager.hasNext() );
        assertPage( pager.nextPage(), 10, 10 );
        assertTrue( pager.hasNext() );

        assertEquals( 2, pager.page() );
        assertTrue( pager.hasNext() );
        assertPage( pager.nextPage(), 4, 20 );
        assertFalse( pager.hasNext() );

        pager.page( 1 );
        assertEquals( 1, pager.page() );
        assertTrue( pager.hasNext() );
        assertPage( pager.nextPage(), 10, 10 );
        assertTrue( pager.hasNext() );
    }

Replace Generic With Diamond PagingIterator<Integer> with PagingIterator<> in method public testPagingIterator() : void from class org.neo4j.helpers.collection.TestCommonIterators


    public RecordSet<RelationshipRecord> findRelationshipChainsThatThisRecordShouldBelongTo(
            RelationshipRecord relationship )
    {
        RecordSet<RelationshipRecord> records = new RecordSet<>();
        for ( RelationshipNodeField field : RelationshipNodeField.values() )
        {
            long nodeId = field.get( relationship );
            nodeStore.getRecord( nodeId, nodeRecord, RecordLoad.FORCE );
            records.addAll( relationshipChainExplorer.followChainFromNode( nodeId, nodeRecord.getNextRel() ) );
        }
        return records;
    }

    public RecordSet<RelationshipRecord> findRelationshipChainsThatThisRecordShouldBelongTo(
            RelationshipRecord relationship )
    {
        RecordSet<RelationshipRecord> records = new RecordSet<RelationshipRecord>();
        for ( RelationshipNodeField field : RelationshipNodeField.values() )
        {
            long nodeId = field.get( relationship );
            nodeStore.getRecord( nodeId, nodeRecord, RecordLoad.FORCE );
            records.addAll( relationshipChainExplorer.followChainFromNode( nodeId, nodeRecord.getNextRel() ) );
        }
        return records;
    }

Replace Generic With Diamond RecordSet<RelationshipRecord> with RecordSet<> in method public findRelationshipChainsThatThisRecordShouldBelongTo(relationship RelationshipRecord) : RecordSet<RelationshipRecord> from class org.neo4j.consistency.repair.OwningNodeRelationshipChain


    RecordSet<R> union( RecordSet<R> other )
    {
        RecordSet<R> set = new RecordSet<>();
        set.addAll( this );
        set.addAll( other );
        return set;
    }

    RecordSet<R> union( RecordSet<R> other )
    {
        RecordSet<R> set = new RecordSet<R>();
        set.addAll( this );
        set.addAll( other );
        return set;
    }

Replace Generic With Diamond RecordSet<R> with RecordSet<> in method package union(other RecordSet<R>) : RecordSet<R> from class org.neo4j.consistency.repair.RecordSet


    public static <R extends AbstractBaseRecord> RecordSet<R> asSet( R... records )
    {
        RecordSet<R> set = new RecordSet<>();
        for ( R record : records )
        {
            set.add( record );
        }
        return set;
    }

    public static <R extends AbstractBaseRecord> RecordSet<R> asSet( R... records )
    {
        RecordSet<R> set = new RecordSet<R>();
        for ( R record : records )
        {
            set.add( record );
        }
        return set;
    }

Replace Generic With Diamond RecordSet<R> with RecordSet<> in method public asSet(records R...) : RecordSet<R> from class org.neo4j.consistency.repair.RecordSet


    public RecordSet<RelationshipRecord> exploreRelationshipRecordChainsToDepthTwo( RelationshipRecord record )
    {
        RecordSet<RelationshipRecord> records = new RecordSet<>();
        for ( RelationshipNodeField nodeField : RelationshipNodeField.values() )
        {
            long nodeId = nodeField.get( record );
            records.addAll( expandChains( expandChainInBothDirections( record, nodeId ), nodeId ) );
        }
        return records;
    }

    public RecordSet<RelationshipRecord> exploreRelationshipRecordChainsToDepthTwo( RelationshipRecord record )
    {
        RecordSet<RelationshipRecord> records = new RecordSet<RelationshipRecord>();
        for ( RelationshipNodeField nodeField : RelationshipNodeField.values() )
        {
            long nodeId = nodeField.get( record );
            records.addAll( expandChains( expandChainInBothDirections( record, nodeId ), nodeId ) );
        }
        return records;
    }

Replace Generic With Diamond RecordSet<RelationshipRecord> with RecordSet<> in method public exploreRelationshipRecordChainsToDepthTwo(record RelationshipRecord) : RecordSet<RelationshipRecord> from class org.neo4j.consistency.repair.RelationshipChainExplorer


    private RecordSet<RelationshipRecord> expandChains( RecordSet<RelationshipRecord> records, long otherNodeId )
    {
        RecordSet<RelationshipRecord> chains = new RecordSet<>();
        for ( RelationshipRecord record : records )
        {
            chains.addAll( expandChainInBothDirections( record,
                    record.getFirstNode() == otherNodeId ? record.getSecondNode() : record.getFirstNode() ) );
        }
        return chains;
    }

    private RecordSet<RelationshipRecord> expandChains( RecordSet<RelationshipRecord> records, long otherNodeId )
    {
        RecordSet<RelationshipRecord> chains = new RecordSet<RelationshipRecord>();
        for ( RelationshipRecord record : records )
        {
            chains.addAll( expandChainInBothDirections( record,
                    record.getFirstNode() == otherNodeId ? record.getSecondNode() : record.getFirstNode() ) );
        }
        return chains;
    }

Replace Generic With Diamond RecordSet<RelationshipRecord> with RecordSet<> in method private expandChains(records RecordSet<RelationshipRecord>, otherNodeId long) : RecordSet<RelationshipRecord> from class org.neo4j.consistency.repair.RelationshipChainExplorer


    public MetaDataStoreCheckTest()
    {
        super( new NeoStoreCheck( new PropertyChain<>( from -> null ) ),
                ConsistencyReport.NeoStoreConsistencyReport.class, new int[0] );
    }

    public MetaDataStoreCheckTest()
    {
        super( new NeoStoreCheck( new PropertyChain<NeoStoreRecord,ConsistencyReport.NeoStoreConsistencyReport>(
                        from -> null ) ),
                ConsistencyReport.NeoStoreConsistencyReport.class, new int[0] );
    }

Replace Generic With Diamond NeoStoreCheck with NeoStoreCheck in method public MetaDataStoreCheckTest() from class org.neo4j.consistency.checking.MetaDataStoreCheckTest


    @Test
    public void toStringShouldPlaceEachRecordOnItsOwnLine() throws Exception
    {
        // given
        NodeRecord record1 = new NodeRecord( 1, false, 1, 1 );
        NodeRecord record2 = new NodeRecord( 2, false, 2, 2 );
        RecordSet<NodeRecord> set = new RecordSet<>();
        set.add( record1 );
        set.add( record2 );

        // when
        String string = set.toString();

        // then
        String[] lines = string.split( "\n" );
        assertEquals(4, lines.length);
        assertEquals( "[", lines[0] );
        assertEquals( record1.toString() + ",", lines[1] );
        assertEquals( record2.toString() + ",", lines[2] );
        assertEquals( "]", lines[3] );
    }

    @Test
    public void toStringShouldPlaceEachRecordOnItsOwnLine() throws Exception
    {
        // given
        NodeRecord record1 = new NodeRecord( 1, false, 1, 1 );
        NodeRecord record2 = new NodeRecord( 2, false, 2, 2 );
        RecordSet<NodeRecord> set = new RecordSet<NodeRecord>();
        set.add( record1 );
        set.add( record2 );

        // when
        String string = set.toString();

        // then
        String[] lines = string.split( "\n" );
        assertEquals(4, lines.length);
        assertEquals( "[", lines[0] );
        assertEquals( record1.toString() + ",", lines[1] );
        assertEquals( record2.toString() + ",", lines[2] );
        assertEquals( "]", lines[3] );
    }

Replace Generic With Diamond RecordSet<NodeRecord> with RecordSet<> in method public toStringShouldPlaceEachRecordOnItsOwnLine() : void from class org.neo4j.consistency.repair.RecordSetTest


    @SuppressWarnings( "unchecked" )
    private static <T extends AbstractBaseRecord> Matcher<RecordReference<T>> isDirectReferenceTo( T record )
    {
        return (Matcher) new DirectReferenceMatcher<>( record );
    }

    @SuppressWarnings( "unchecked" )
    private static <T extends AbstractBaseRecord> Matcher<RecordReference<T>> isDirectReferenceTo( T record )
    {
        return (Matcher) new DirectReferenceMatcher<T>( record );
    }

Replace Generic With Diamond DirectReferenceMatcher<T> with DirectReferenceMatcher<> in method private isDirectReferenceTo(record T) : Matcher<RecordReference<T>> from class org.neo4j.consistency.store.CacheSmallStoresRecordAccessTest


    private static LinkedList<Node> getAncestorsPlusSelf( Node node, PathExpander expander )
    {
        LinkedList<Node> ancestors = new LinkedList<>();
        ancestors.add( node );
        ResourceIterator<Relationship> relIterator =
                Iterators.asResourceIterator( expander.expand( singleNodePath( node ), NO_STATE ).iterator() );
        while ( relIterator.hasNext() )
        {
            Relationship rel = relIterator.next();
            node = rel.getOtherNode( node );
            ancestors.add( node );
            relIterator.close();
            relIterator = Iterators.asResourceIterator( expander.expand( singleNodePath( node ), NO_STATE ).iterator() );
        }
        return ancestors;
    }

    private static LinkedList<Node> getAncestorsPlusSelf( Node node, PathExpander expander )
    {
        LinkedList<Node> ancestors = new LinkedList<Node>();
        ancestors.add( node );
        ResourceIterator<Relationship> relIterator =
                Iterators.asResourceIterator( expander.expand( singleNodePath( node ), NO_STATE ).iterator() );
        while ( relIterator.hasNext() )
        {
            Relationship rel = relIterator.next();
            node = rel.getOtherNode( node );
            ancestors.add( node );
            relIterator.close();
            relIterator = Iterators.asResourceIterator( expander.expand( singleNodePath( node ), NO_STATE ).iterator() );
        }
        return ancestors;
    }

Replace Generic With Diamond LinkedList<Node> with LinkedList<> in method private getAncestorsPlusSelf(node Node, expander PathExpander) : LinkedList<Node> from class org.neo4j.graphalgo.impl.ancestor.AncestorsUtil