    PhysicalLogVersionedStoreChannel openLogChannel( long version ) throws IOException
    {
        File fileToOpen = fileHelper.getLogFileForVersion( version );

        if ( !fileSystem.fileExists( fileToOpen ) )
        {
            throw new FileNotFoundException( fileToOpen.getCanonicalPath() );
        }

        StoreChannel rawChannel = null;
        try
        {
            rawChannel = fileSystem.read( fileToOpen );
            try ( var scopedBuffer = new HeapScopedBuffer( CURRENT_FORMAT_LOG_HEADER_SIZE, logFilesContext.getMemoryTracker() ) )
            {
                var buffer = scopedBuffer.getBuffer();
                LogHeader header = readLogHeader( buffer, rawChannel, true, fileToOpen );
                if ( (header == null) || (header.getLogVersion() != version) )
                {
                    throw new IllegalStateException(
                            format( "Unexpected log file header. Expected header version: %d, actual header: %s", version,
                                    header != null ? header.toString() : "null header." ) );
                }
                var versionedStoreChannel = new PhysicalLogVersionedStoreChannel( rawChannel, version, header.getLogFormatVersion(),
                        fileToOpen, nativeChannelAccessor );
                nativeChannelAccessor.adviseSequentialAccessAndKeepInCache( rawChannel, version );
                return versionedStoreChannel;
            }
        }
        catch ( FileNotFoundException cause )
        {
            throw (FileNotFoundException) new FileNotFoundException( fileToOpen.getCanonicalPath() ).initCause( cause );
        }
        catch ( Throwable unexpectedError )
        {
            if ( rawChannel != null )
            {
                // If we managed to open the file before failing, then close the channel
                try
                {
                    rawChannel.close();
                }
                catch ( IOException e )
                {
                    unexpectedError.addSuppressed( e );
                }
            }
            throw unexpectedError;
        }
    }

    PhysicalLogVersionedStoreChannel openLogChannel( long version ) throws IOException
    {
        File fileToOpen = fileHelper.getLogFileForVersion( version );

        if ( !fileSystem.fileExists( fileToOpen ) )
        {
            throw new FileNotFoundException( fileToOpen.getCanonicalPath() );
        }

        StoreChannel rawChannel = null;
        try
        {
            rawChannel = fileSystem.read( fileToOpen );
            ByteBuffer buffer = ByteBuffers.allocate( CURRENT_FORMAT_LOG_HEADER_SIZE );
            LogHeader header = readLogHeader( buffer, rawChannel, true, fileToOpen );
            if ( (header == null) || (header.getLogVersion() != version) )
            {
                throw new IllegalStateException(
                        format( "Unexpected log file header. Expected header version: %d, actual header: %s", version,
                                header != null ? header.toString() : "null header." ) );
            }
            var versionedStoreChannel = new PhysicalLogVersionedStoreChannel( rawChannel, version, header.getLogFormatVersion(),
                    fileToOpen, nativeChannelAccessor );
            nativeChannelAccessor.adviseSequentialAccessAndKeepInCache( rawChannel, version );
            return versionedStoreChannel;
        }
        catch ( FileNotFoundException cause )
        {
            throw (FileNotFoundException) new FileNotFoundException( fileToOpen.getCanonicalPath() ).initCause( cause );
        }
        catch ( Throwable unexpectedError )
        {
            if ( rawChannel != null )
            {
                // If we managed to open the file before failing, then close the channel
                try
                {
                    rawChannel.close();
                }
                catch ( IOException e )
                {
                    unexpectedError.addSuppressed( e );
                }
            }
            throw unexpectedError;
        }
    }

Try With Resources try(var scopedBuffer=new HeapScopedBuffer(CURRENT_FORMAT_LOG_HEADER_SIZE,logFilesContext.getMemoryTracker())) in method package openLogChannel(version long) : PhysicalLogVersionedStoreChannel from class org.neo4j.kernel.impl.transaction.log.files.TransactionLogChannelAllocator


    private void verifyNoMoreReadableDataAvailable( long version, LogVersionedStoreChannel channel, LogPosition logPosition, long channelLeftovers )
            throws IOException
    {
        long initialPosition = channel.position();
        try
        {
            channel.position( logPosition.getByteOffset() );
            try ( var scopedBuffer = new HeapScopedBuffer( safeCastLongToInt( min( kibiBytes( 12 ), channelLeftovers ) ), memoryTracker ) )
            {
                ByteBuffer byteBuffer = scopedBuffer.getBuffer();
                channel.readAll( byteBuffer );
                byteBuffer.flip();
                if ( !isAllZerosBuffer( byteBuffer ) )
                {
                    throw new RuntimeException( format( "Transaction log files with version %d has some data available after last readable log entry. " +
                            "Last readable position %d, read ahead buffer content: %s.", version, logPosition.getByteOffset(),
                            dumpBufferToString( byteBuffer ) ) );
                }
            }
        }
        finally
        {
            channel.position( initialPosition );
        }
    }

    private void verifyNoMoreReadableDataAvailable( long version, LogVersionedStoreChannel channel, LogPosition logPosition, long channelLeftovers )
            throws IOException
    {
        long initialPosition = channel.position();
        try
        {
            channel.position( logPosition.getByteOffset() );
            ByteBuffer byteBuffer = ByteBuffers.allocate( safeCastLongToInt( min( kibiBytes( 12 ), channelLeftovers ) ) );
            channel.readAll( byteBuffer );
            byteBuffer.flip();
            if ( !isAllZerosBuffer( byteBuffer ) )
            {
                throw new RuntimeException( format( "Transaction log files with version %d has some data available after last readable log entry. " +
                                "Last readable position %d, read ahead buffer content: %s.", version, logPosition.getByteOffset(),
                        dumpBufferToString( byteBuffer ) ) );
            }
        }
        finally
        {
            channel.position( initialPosition );
        }
    }

Try With Resources try(var scopedBuffer=new HeapScopedBuffer(safeCastLongToInt(min(kibiBytes(12),channelLeftovers)),memoryTracker)) in method private verifyNoMoreReadableDataAvailable(version long, channel LogVersionedStoreChannel, logPosition LogPosition, channelLeftovers long) : void from class org.neo4j.kernel.recovery.LogTailScanner


    @Test
    void shouldGiveBackCompletionPercentage()
    {
        // given
        long total = 10;
        for ( long i = 0; i < total; i++ )
        {
            cursors.withNode( i );
        }

        MutableInt read = new MutableInt();
        final PercentageSupplier percentageSupplier = new PercentageSupplier();
        final PropertyAwareEntityStoreScan<StorageNodeCursor,RuntimeException> scan =
                new PropertyAwareEntityStoreScan<>( cursors, total, IntPredicates.alwaysTrue(),
                        id -> locks.acquireNodeLock( id, LockService.LockType.READ_LOCK ), PageCursorTracer.NULL, INSTANCE )
                {
                    @Override
                    public boolean process( StorageNodeCursor node )
                    {
                        // then
                        read.incrementAndGet();
                        float expected = (float) read.intValue() / total;
                        float actual = percentageSupplier.get();
                        assertEquals( expected, actual, 0.0, String.format( "%f==%f", expected, actual ) );
                        return false;
                    }

                    @Override
                    protected StorageNodeCursor allocateCursor( StorageReader storageReader, PageCursorTracer cursorTracer )
                    {
                        return storageReader.allocateNodeCursor( cursorTracer );
                    }
                };
        percentageSupplier.setStoreScan( scan );

        // when
        scan.run();

        // then
        assertEquals( total, read.intValue() );
    }

    @Test
    void shouldGiveBackCompletionPercentage()
    {
        // given
        long total = 10;
        for ( long i = 0; i < total; i++ )
        {
            cursors.withNode( i );
        }

        MutableInt read = new MutableInt();
        final PercentageSupplier percentageSupplier = new PercentageSupplier();
        final PropertyAwareEntityStoreScan<StorageNodeCursor,RuntimeException> scan =
                new PropertyAwareEntityStoreScan<StorageNodeCursor,RuntimeException>( cursors, total, IntPredicates.alwaysTrue(),
                        id -> locks.acquireNodeLock( id, LockService.LockType.READ_LOCK ), PageCursorTracer.NULL )
                {
                    @Override
                    public boolean process( StorageNodeCursor node )
                    {
                        // then
                        read.incrementAndGet();
                        float expected = (float) read.intValue() / total;
                        float actual = percentageSupplier.get();
                        assertEquals( expected, actual, 0.0, String.format( "%f==%f", expected, actual ) );
                        return false;
                    }

                    @Override
                    protected StorageNodeCursor allocateCursor( StorageReader storageReader, PageCursorTracer cursorTracer )
                    {
                        return storageReader.allocateNodeCursor( cursorTracer );
                    }
                };
        percentageSupplier.setStoreScan( scan );

        // when
        scan.run();

        // then
        assertEquals( total, read.intValue() );
    }

Replace Generic With Diamond PropertyAwareEntityStoreScan<StorageNodeCursor,RuntimeException> with PropertyAwareEntityStoreScan<> in method package shouldGiveBackCompletionPercentage() : void from class org.neo4j.kernel.impl.transaction.state.PropertyAwareEntityStoreScanTest


    /**
     * Scans the store using store view and populates all participating {@link IndexPopulator} with data relevant to
     * each index.
     * The scan continues as long as there's at least one non-failed populator.
     */
    @Override
    public void run()
    {
        try ( var cursorTracer = pageCacheTracer.createPageCursorTracer( INDEX_POPULATION_TAG ) )
        {
            if ( !multiPopulator.hasPopulators() )
            {
                return;
            }
            if ( storeScan != null )
            {
                throw new IllegalStateException( "Population already started." );
            }

            try
            {
                multiPopulator.create( cursorTracer );
                multiPopulator.resetIndexCounts( cursorTracer );

                monitor.indexPopulationScanStarting();
                indexAllEntities( cursorTracer );
                monitor.indexPopulationScanComplete();
                if ( stopped )
                {
                    multiPopulator.stop( cursorTracer );
                    // We remain in POPULATING state
                    return;
                }
                multiPopulator.flipAfterStoreScan( verifyBeforeFlipping, cursorTracer );
            }
            catch ( Throwable t )
            {
                multiPopulator.cancel( t, cursorTracer );
            }
        }
        finally
        {
            // will only close "additional" resources, not the actual populators, since that's managed by flip
            Runnables.runAll( "Failed to close resources in IndexPopulationJob",
                    multiPopulator::close,
                    () -> monitor.populationJobCompleted( memoryAllocationTracker.peakMemoryUsage() ),
                    bufferFactory::close,
                    doneSignal::countDown );
        }
    }

    /**
     * Scans the store using store view and populates all participating {@link IndexPopulator} with data relevant to
     * each index.
     * The scan continues as long as there's at least one non-failed populator.
     */
    @Override
    public void run()
    {
        try
        {
            if ( !multiPopulator.hasPopulators() )
            {
                return;
            }
            if ( storeScan != null )
            {
                throw new IllegalStateException( "Population already started." );
            }

            try
            {
                multiPopulator.create();
                multiPopulator.resetIndexCounts();

                monitor.indexPopulationScanStarting();
                indexAllEntities();
                monitor.indexPopulationScanComplete();
                if ( stopped )
                {
                    multiPopulator.stop();
                    // We remain in POPULATING state
                    return;
                }
                multiPopulator.flipAfterStoreScan( verifyBeforeFlipping );
            }
            catch ( Throwable t )
            {
                multiPopulator.cancel( t );
            }
        }
        finally
        {
            // will only close "additional" resources, not the actual populators, since that's managed by flip
            Runnables.runAll( "Failed to close resources in IndexPopulationJob",
                    multiPopulator::close,
                    () -> monitor.populationJobCompleted( memoryAllocationTracker.peakMemoryUsage() ),
                    bufferFactory::close,
                    doneSignal::countDown );
        }
    }

Try With Resources try(var cursorTracer=pageCacheTracer.createPageCursorTracer(INDEX_POPULATION_TAG)) in method public run() : void from class org.neo4j.kernel.impl.api.index.IndexPopulationJob


    private void performRecoveredIndexDropActions()
    {
        indexesToDropAfterCompletedRecovery.values().forEach( index ->
        {
            try
            {
                index.drop();
            }
            catch ( Exception e )
            {
                // This is OK to get during recovery because the underlying index can be in any unknown state
                // while we're recovering. Let's just move on to closing it instead.
                try ( var cursorTracer = pageCacheTracer.createPageCursorTracer( INDEX_SERVICE_INDEX_CLOSING_TAG ) )
                {
                    index.close( cursorTracer );
                }
                catch ( IOException closeException )
                {
                    // This is OK for the same reason as above
                }
            }
        } );
        indexesToDropAfterCompletedRecovery.clear();
    }

    private void performRecoveredIndexDropActions()
    {
        indexesToDropAfterCompletedRecovery.values().forEach( index ->
        {
            try
            {
                index.drop();
            }
            catch ( Exception e )
            {
                // This is OK to get during recovery because the underlying index can be in any unknown state
                // while we're recovering. Let's just move on to closing it instead.
                try
                {
                    index.close();
                }
                catch ( IOException closeException )
                {
                    // This is OK for the same reason as above
                }
            }
        } );
        indexesToDropAfterCompletedRecovery.clear();
    }

Try With Resources try(var cursorTracer=pageCacheTracer.createPageCursorTracer(INDEX_SERVICE_INDEX_CLOSING_TAG)) in method private performRecoveredIndexDropActions() : void from class org.neo4j.kernel.impl.api.index.IndexingService


    private void flush( IndexPopulation population )
    {
        phaseTracker.enterPhase( PhaseTracker.Phase.WRITE );
        activeTasks.incrementAndGet();
        List<IndexEntryUpdate<?>> batch = population.takeCurrentBatchFromScan();

        jobScheduler.schedule( Group.INDEX_POPULATION_WORK, () ->
        {
            try ( var cursorTracer = cacheTracer.createPageCursorTracer( POPULATION_WORK_FLUSH_TAG ) )
            {
                String batchDescription = "EMPTY";
                if ( PRINT_DEBUG )
                {
                    if ( !batch.isEmpty() )
                    {
                        batchDescription = format( "[%d, %d - %d]", batch.size(), batch.get( 0 ).getEntityId(), batch.get( batch.size() - 1 ).getEntityId() );
                    }
                    log.info( "Applying scan batch %s", batchDescription );
                }
                population.populator.add( batch, cursorTracer );
                if ( PRINT_DEBUG )
                {
                    log.info( "Applied scan batch %s", batchDescription );
                }
            }
            catch ( Throwable failure )
            {
                cancel( population, failure, cursorTracer );
            }
            finally
            {
                activeTasks.decrementAndGet();
            }
        } );
    }

    private void flush( IndexPopulation population )
    {
        phaseTracker.enterPhase( PhaseTracker.Phase.WRITE );
        activeTasks.incrementAndGet();
        List<IndexEntryUpdate<?>> batch = population.takeCurrentBatchFromScan();

        jobScheduler.schedule( Group.INDEX_POPULATION_WORK, () ->
        {
            try
            {
                String batchDescription = "EMPTY";
                if ( PRINT_DEBUG )
                {
                    if ( !batch.isEmpty() )
                    {
                        batchDescription = format( "[%d, %d - %d]", batch.size(), batch.get( 0 ).getEntityId(), batch.get( batch.size() - 1 ).getEntityId() );
                    }
                    log.info( "Applying scan batch %s", batchDescription );
                }
                population.populator.add( batch );
                if ( PRINT_DEBUG )
                {
                    log.info( "Applied scan batch %s", batchDescription );
                }
            }
            catch ( Throwable failure )
            {
                cancel( population, failure );
            }
            finally
            {
                activeTasks.decrementAndGet();
            }
        } );
    }

Try With Resources try(var cursorTracer=cacheTracer.createPageCursorTracer(POPULATION_WORK_FLUSH_TAG)) in method private flush(population IndexPopulation) : void from class org.neo4j.kernel.impl.api.index.MultipleIndexPopulator


    @Override
    public long receive( final long ticket, final T batch )
    {
        // Don't go too far ahead
        incrementQueue();
        long nanoTime = nanoTime();
        executor.submit( sender ->
        {
            assertHealthy();
            sender.initialize( ticket );
            try ( var cursorTracer = pageCacheTracer.createPageCursorTracer( name() ) )
            {
                long startTime = nanoTime();
                process( batch, sender, cursorTracer );
                if ( downstream == null )
                {
                    // No batches were emitted so we couldn't track done batches in that way.
                    // We can see that we're the last step so increment here instead
                    doneBatches.incrementAndGet();
                    control.recycle( batch );
                }
                totalProcessingTime.add( nanoTime() - startTime - sender.sendTime );

                decrementQueue();
                checkNotifyEndDownstream();
            }
            catch ( Throwable e )
            {
                issuePanic( e );
            }
        } );
        return nanoTime() - nanoTime;
    }

    @Override
    public long receive( final long ticket, final T batch )
    {
        // Don't go too far ahead
        incrementQueue();
        long nanoTime = nanoTime();
        executor.submit( sender ->
        {
            assertHealthy();
            sender.initialize( ticket );
            try
            {
                long startTime = nanoTime();
                process( batch, sender );
                if ( downstream == null )
                {
                    // No batches were emitted so we couldn't track done batches in that way.
                    // We can see that we're the last step so increment here instead
                    doneBatches.incrementAndGet();
                    control.recycle( batch );
                }
                totalProcessingTime.add( nanoTime() - startTime - sender.sendTime );

                decrementQueue();
                checkNotifyEndDownstream();
            }
            catch ( Throwable e )
            {
                issuePanic( e );
            }
        } );
        return nanoTime() - nanoTime;
    }

Try With Resources try(var cursorTracer=pageCacheTracer.createPageCursorTracer(name())) in method public receive(ticket long, batch T) : long from class org.neo4j.internal.batchimport.staging.ProcessorStep


/**
     * Select record format for the given store directory.
     *

     * Note: package private only for testing.
     *
     * @param databaseLayout directory with the store
     * @param fs file system used to access store files
     * @param pageCache page cache to read store files
     * @param pageCacheTracer underlying page cache operations tracer.
     * @return record format of the given store or null if {@link DatabaseLayout#metadataStore()} file not
     * found or can't be read
     */
    @Nullable
    public static RecordFormats selectForStore( DatabaseLayout databaseLayout, FileSystemAbstraction fs, PageCache pageCache, LogProvider logProvider,
            PageCacheTracer pageCacheTracer )
    {
        File neoStoreFile = databaseLayout.metadataStore();
        if ( fs.fileExists( neoStoreFile ) )
        {
            try ( var cursorTracer = pageCacheTracer.createPageCursorTracer( STORE_SELECTION_TAG ) )
            {
                long value = MetaDataStore.getRecord( pageCache, neoStoreFile, STORE_VERSION, cursorTracer );
                if ( value != MetaDataRecordFormat.FIELD_NOT_PRESENT )
                {
                    String storeVersion = MetaDataStore.versionLongToString( value );

                    for ( RecordFormats format : allFormats() )
                    {
                        if ( format.storeVersion().equals( storeVersion ) )
                        {
                            info( logProvider, "Selected " + format + " record format from store " + databaseLayout.databaseDirectory() );
                            return format;
                        }
                    }
                }
            }
            catch ( IOException e )
            {
                info( logProvider, format( "Unable to read format for store %s. %s ", databaseLayout.databaseDirectory(), e.getMessage() ) );
            }
        }
        return null;
    }

/**
     * Select record format for the given store directory.
     *

     * Note: package private only for testing.
     *
     * @param databaseLayout directory with the store
     * @param fs file system used to access store files
     * @param pageCache page cache to read store files
     * @return record format of the given store or null if {@link DatabaseLayout#metadataStore()} file not
     * found or can't be read
     */
    @Nullable
    public static RecordFormats selectForStore( DatabaseLayout databaseLayout, FileSystemAbstraction fs, PageCache pageCache, LogProvider logProvider )
    {
        File neoStoreFile = databaseLayout.metadataStore();
        if ( fs.fileExists( neoStoreFile ) )
        {
            try
            {
                long value = MetaDataStore.getRecord( pageCache, neoStoreFile, STORE_VERSION );
                if ( value != MetaDataRecordFormat.FIELD_NOT_PRESENT )
                {
                    String storeVersion = MetaDataStore.versionLongToString( value );

                    for ( RecordFormats format : allFormats() )
                    {
                        if ( format.storeVersion().equals( storeVersion ) )
                        {
                            info( logProvider, "Selected " + format + " record format from store " + databaseLayout.databaseDirectory() );
                            return format;
                        }
                    }
                }
            }
            catch ( IOException e )
            {
                info( logProvider, format( "Unable to read format for store %s. %s ", databaseLayout.databaseDirectory(), e.getMessage() ) );
            }
        }
        return null;
    }

Try With Resources try(var cursorTracer=pageCacheTracer.createPageCursorTracer(STORE_SELECTION_TAG)) in method public selectForStore(databaseLayout DatabaseLayout, fs FileSystemAbstraction, pageCache PageCache, logProvider LogProvider, pageCacheTracer PageCacheTracer) : RecordFormats from class org.neo4j.kernel.impl.store.format.RecordFormatSelector


    @Test
    void testCreatesLockFile() throws Exception
    {
        try ( var inserter = BatchInserters.inserter( databaseLayout, fileSystem ) )
        {
            assertTrue( databaseLayout.databaseLockFile().exists() );
        }
    }

    @Test
    void testCreatesLockFile() throws Exception
    {
        BatchInserter inserter = BatchInserters.inserter( databaseLayout, fileSystem );
        try
        {
            assertTrue( databaseLayout.databaseLockFile().exists() );
        }
        finally
        {
            inserter.shutdown();
        }
    }

Try With Resources try(var inserter=BatchInserters.inserter(databaseLayout,fileSystem)) in method package testCreatesLockFile() : void from class org.neo4j.batchinsert.internal.BatchInserterImplTest


    @Override
    public Iterable<RelationshipType> getRelationshipTypes()
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        try ( RelationshipGroupCursor relationships = transaction.cursors().allocateRelationshipGroupCursor( transaction.pageCursorTracer() ) )
        {
            NodeCursor nodes = transaction.ambientNodeCursor();
            TokenRead tokenRead = transaction.tokenRead();
            singleNode( transaction, nodes );
            nodes.relationshipGroups( relationships );
            List<RelationshipType> types = new ArrayList<>();
            while ( relationships.next() )
            {
                // only include this type if there are any relationships with this type
                if ( relationships.totalCount() > 0 )
                {
                    types.add( RelationshipType.withName( tokenRead.relationshipTypeName( relationships.type() ) ) );
                }
            }

            return types;
        }
        catch ( KernelException e )
        {
            throw new NotFoundException( "Relationship name not found.", e );
        }
    }

    @Override
    public Iterable<RelationshipType> getRelationshipTypes()
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        try
        {
            NodeCursor nodes = transaction.ambientNodeCursor();
            TokenRead tokenRead = transaction.tokenRead();
            singleNode( transaction, nodes );
            Degrees degrees = nodes.degrees( ALL_RELATIONSHIPS );
            List<RelationshipType> types = new ArrayList<>();
            for ( int type : degrees.types() )
            {
                // only include this type if there are any relationships with this type
                if ( degrees.totalDegree( type ) > 0 )
                {
                    types.add( RelationshipType.withName( tokenRead.relationshipTypeName( type ) ) );
                }
            }

            return types;
        }
        catch ( KernelException e )
        {
            throw new NotFoundException( "Relationship name not found.", e );
        }
    }

Try With Resources try(RelationshipGroupCursor relationships=transaction.cursors().allocateRelationshipGroupCursor(transaction.pageCursorTracer())) in method public getRelationshipTypes() : Iterable<RelationshipType> from class org.neo4j.kernel.impl.core.NodeEntity


    @Override
    public <RECORD extends AbstractBaseRecord,REPORT extends ConsistencyReport> REPORT report( RECORD record,
            Class<REPORT> cls, RecordType recordType )
    {
        ProxyFactory<REPORT> proxyFactory = ProxyFactory.get( cls );
        ReportInvocationHandler<RECORD,REPORT> handler = new ReportHandler<>( report, proxyFactory, recordType, records, record, monitor, pageCacheTracer )
        {
            @Override
            protected void inconsistencyReported()
            {
            }
        };
        return handler.report();
    }

    @Override
    public <RECORD extends AbstractBaseRecord,REPORT extends ConsistencyReport> REPORT report( RECORD record,
            Class<REPORT> cls, RecordType recordType )
    {
        ProxyFactory<REPORT> proxyFactory = ProxyFactory.get( cls );
        ReportInvocationHandler<RECORD,REPORT> handler =
                new ReportHandler<RECORD,REPORT>( report, proxyFactory, recordType, records, record, monitor )
                {
                    @Override
                    protected void inconsistencyReported()
                    {
                    }
                };
        return handler.report();
    }

Replace Generic With Diamond ReportHandler<RECORD,REPORT> with ReportHandler<> in method public report(record RECORD, cls Class<REPORT>, recordType RecordType) : REPORT from class org.neo4j.consistency.report.ConsistencyReporter


    @Test
    void shouldDoProcessingInitializationInOrder() throws Throwable
    {
        // GIVEN
        final Race race = new Race();
        final AtomicInteger coordination = new AtomicInteger( -1 );
        final AtomicInteger expected = new AtomicInteger();
        final int threads = 30;
        @SuppressWarnings( "unchecked" )
        final RecordCheckWorker<Integer>[] workers = new RecordCheckWorker[threads];
        final RecordProcessor<Integer> processor = new RecordProcessor.Adapter<>()
        {
            @Override
            public void process( Integer record, PageCursorTracer cursorTracer )
            {
                // We're testing init() here, not really process()
            }

            @Override
            public void init( int id )
            {
                assertEquals( id, expected.getAndAdd( 1 ) );
            }
        };
        for ( int id = 0; id < threads; id++ )
        {
            ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>( 10 );
            race.addContestant( workers[id] = new RecordCheckWorker<>( id, coordination, queue, processor, PageCacheTracer.NULL ) );
        }
        race.addContestant( () ->
        {
            try
            {
                long end = currentTimeMillis() + SECONDS.toMillis( 100 );
                while ( currentTimeMillis() < end && expected.get() < threads )
                {
                    parkNanos( MILLISECONDS.toNanos( 10 ) );
                }
                assertEquals( threads, expected.get() );
            }
            finally
            {
                for ( RecordCheckWorker<Integer> worker : workers )
                {
                    worker.done();
                }
            }
        } );

        // WHEN
        race.go();
    }

    @Test
    void shouldDoProcessingInitializationInOrder() throws Throwable
    {
        // GIVEN
        final Race race = new Race();
        final AtomicInteger coordination = new AtomicInteger( -1 );
        final AtomicInteger expected = new AtomicInteger();
        final int threads = 30;
        @SuppressWarnings( "unchecked" )
        final RecordCheckWorker<Integer>[] workers = new RecordCheckWorker[threads];
        final RecordProcessor<Integer> processor = new RecordProcessor.Adapter<Integer>()
        {
            @Override
            public void process( Integer record )
            {
                // We're testing init() here, not really process()
            }

            @Override
            public void init( int id )
            {
                assertEquals( id, expected.getAndAdd( 1 ) );
            }
        };
        for ( int id = 0; id < threads; id++ )
        {
            ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>( 10 );
            race.addContestant( workers[id] = new RecordCheckWorker<>( id, coordination, queue, processor ) );
        }
        race.addContestant( () ->
        {
            try
            {
                long end = currentTimeMillis() + SECONDS.toMillis( 100 );
                while ( currentTimeMillis() < end && expected.get() < threads )
                {
                    parkNanos( MILLISECONDS.toNanos( 10 ) );
                }
                assertEquals( threads, expected.get() );
            }
            finally
            {
                for ( RecordCheckWorker<Integer> worker : workers )
                {
                    worker.done();
                }
            }
        } );

        // WHEN
        race.go();
    }

Replace Generic With Diamond RecordProcessor.Adapter<Integer> with RecordProcessor.Adapter<> in method package shouldDoProcessingInitializationInOrder() : void from class org.neo4j.consistency.checking.full.RecordCheckWorkerTest


    public <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
    CheckerEngine<RECORD, REPORT> engine( final RECORD record, final REPORT report )
    {
        return new Engine<>( report )
        {
            @Override
            @SuppressWarnings( "unchecked" )
            void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference, AbstractBaseRecord newReference )
            {
                checker.checkReference( record, newReference, this, RecordAccessStub.this, NULL );
            }
        };
    }

    public <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
    CheckerEngine<RECORD, REPORT> engine( final RECORD record, final REPORT report )
    {
        return new Engine<RECORD, REPORT>( report )
        {
            @Override
            @SuppressWarnings( "unchecked" )
            void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference,
                                 AbstractBaseRecord newReference )
            {
                checker.checkReference( record, newReference, this, RecordAccessStub.this );
            }
        };
    }

Replace Generic With Diamond Engine<RECORD,REPORT> with Engine<> in method public engine(record RECORD, report REPORT) : CheckerEngine<RECORD,REPORT> from class org.neo4j.consistency.store.RecordAccessStub


    public <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
    CheckerEngine<RECORD, REPORT> engine( final RECORD oldRecord, final RECORD newRecord, REPORT report )
    {
        return new Engine<>( report )
        {
            @Override
            @SuppressWarnings( "unchecked" )
            void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference, AbstractBaseRecord newReference )
            {
                checker.checkReference( newRecord, newReference, this, RecordAccessStub.this, NULL );
            }
        };
    }

    public <RECORD extends AbstractBaseRecord, REPORT extends ConsistencyReport>
    CheckerEngine<RECORD, REPORT> engine( final RECORD oldRecord, final RECORD newRecord, REPORT report )
    {
        return new Engine<RECORD, REPORT>( report )
        {
            @Override
            @SuppressWarnings( "unchecked" )
            void checkReference( ComparativeRecordChecker checker, AbstractBaseRecord oldReference,
                                 AbstractBaseRecord newReference )
            {
                checker.checkReference( newRecord, newReference, this, RecordAccessStub.this );
            }
        };
    }

Replace Generic With Diamond Engine<RECORD,REPORT> with Engine<> in method public engine(oldRecord RECORD, newRecord RECORD, report REPORT) : CheckerEngine<RECORD,REPORT> from class org.neo4j.consistency.store.RecordAccessStub


    public void populateCache()
    {
        CacheTask action = new CacheTask.CacheNextRel( CheckStage.Stage3_NS_NextRel, cacheAccess,
                resourceIterable( new IterableWrapper<>( nodes.values() )
                {
                    @Override
                    protected NodeRecord underlyingObjectToObject( Delta<NodeRecord> node )
                    {
                        return node.newRecord;
                    }
                } ), PageCacheTracer.NULL );
        action.run();
    }

    public void populateCache()
    {
        CacheTask action = new CacheTask.CacheNextRel( CheckStage.Stage3_NS_NextRel, cacheAccess,
                resourceIterable( new IterableWrapper<NodeRecord,Delta<NodeRecord>>( nodes.values() )
        {
            @Override
            protected NodeRecord underlyingObjectToObject( Delta<NodeRecord> node )
            {
                return node.newRecord;
            }
        } ) );
        action.run();
    }

Replace Generic With Diamond CacheTask.CacheNextRel with CacheTask.CacheNextRel in method public populateCache() : void from class org.neo4j.consistency.store.RecordAccessStub


    @Override
    public Iterator<PropertyRecord> rawPropertyChain( final long firstId, PageCursorTracer cursorTracer )
    {
        return new PrefetchingIterator<>()
        {
            private long next = firstId;

            @Override
            protected PropertyRecord fetchNextOrNull()
            {
                if ( Record.NO_NEXT_PROPERTY.is( next ) )
                {
                    return null;
                }
                PropertyRecord record = reference( properties, next, Version.LATEST ).record();
                next = record.getNextProp();
                return record;
            }
        };
    }

    @Override
    public Iterator<PropertyRecord> rawPropertyChain( final long firstId )
    {
        return new PrefetchingIterator<PropertyRecord>()
        {
            private long next = firstId;

            @Override
            protected PropertyRecord fetchNextOrNull()
            {
                if ( Record.NO_NEXT_PROPERTY.is( next ) )
                {
                    return null;
                }
                PropertyRecord record = reference( properties, next, Version.LATEST ).record();
                next = record.getNextProp();
                return record;
            }
        };
    }

Replace Generic With Diamond PrefetchingIterator<PropertyRecord> with PrefetchingIterator<> in method public rawPropertyChain(firstId long, cursorTracer PageCursorTracer) : Iterator<PropertyRecord> from class org.neo4j.consistency.store.RecordAccessStub


    public GBPTreeCountsStore( PageCache pageCache, File file, RecoveryCleanupWorkCollector recoveryCollector,
            CountsBuilder initialCountsBuilder, boolean readOnly, PageCacheTracer pageCacheTracer, Monitor monitor ) throws IOException
    {
        this.readOnly = readOnly;
        this.monitor = monitor;

        // First just read the header so that we can avoid creating it if this store is read-only
        CountsHeader header = new CountsHeader( NEEDS_REBUILDING_HIGH_ID );
        this.tree = instantiateTree( pageCache, file, recoveryCollector, readOnly, header, pageCacheTracer );
        boolean successful = false;
        try ( var cursorTracer = pageCacheTracer.createPageCursorTracer( OPEN_COUNT_STORE_TAG ) )
        {
            this.txIdInformation = readTxIdInformation( header.highestGapFreeTxId(), cursorTracer );
            // Recreate the tx id state as it was from last checkpoint (or base if empty)
            this.idSequence = new ArrayQueueOutOfOrderSequence( txIdInformation.highestGapFreeTxId, 200, EMPTY_LONG_ARRAY );
            this.txIdInformation.strayTxIds.forEach( txId -> idSequence.offer( txId, EMPTY_LONG_ARRAY ) );
            // Only care about initial counts rebuilding if the tree was created right now when opening this tree
            // The actual rebuilding will happen in start()
            this.initialCountsBuilder = header.wasRead() && header.highestGapFreeTxId() != NEEDS_REBUILDING_HIGH_ID ? null : initialCountsBuilder;
            successful = true;
        }
        finally
        {
            if ( !successful )
            {
                closeAllUnchecked( tree );
            }
        }
    }

    public GBPTreeCountsStore( PageCache pageCache, File file, RecoveryCleanupWorkCollector recoveryCollector,
            CountsBuilder initialCountsBuilder, boolean readOnly, Monitor monitor ) throws IOException
    {
        this.readOnly = readOnly;
        this.monitor = monitor;

        // First just read the header so that we can avoid creating it if this store is read-only
        CountsHeader header = new CountsHeader( NEEDS_REBUILDING_HIGH_ID );
        this.tree = instantiateTree( pageCache, file, recoveryCollector, readOnly, header );
        boolean successful = false;
        try
        {
            this.txIdInformation = readTxIdInformation( header.highestGapFreeTxId() );
            // Recreate the tx id state as it was from last checkpoint (or base if empty)
            this.idSequence = new ArrayQueueOutOfOrderSequence( txIdInformation.highestGapFreeTxId, 200, EMPTY_LONG_ARRAY );
            this.txIdInformation.strayTxIds.forEach( txId -> idSequence.offer( txId, EMPTY_LONG_ARRAY ) );
            // Only care about initial counts rebuilding if the tree was created right now when opening this tree
            // The actual rebuilding will happen in start()
            this.initialCountsBuilder = header.wasRead() && header.highestGapFreeTxId() != NEEDS_REBUILDING_HIGH_ID ? null : initialCountsBuilder;
            successful = true;
        }
        finally
        {
            if ( !successful )
            {
                closeAllUnchecked( tree );
            }
        }
    }

Try With Resources try(var cursorTracer=pageCacheTracer.createPageCursorTracer(OPEN_COUNT_STORE_TAG)) in method public GBPTreeCountsStore(pageCache PageCache, file File, recoveryCollector RecoveryCleanupWorkCollector, initialCountsBuilder CountsBuilder, readOnly boolean, pageCacheTracer PageCacheTracer, monitor Monitor) from class org.neo4j.internal.counts.GBPTreeCountsStore


    @Override
    public Iterable<RecordProxy<RECORD,ADDITIONAL>> changes()
    {
        return new IterableWrapper<>( delegate.changes() )
        {
            @Override
            protected RecordProxy<RECORD,ADDITIONAL> underlyingObjectToObject( RecordProxy<RECORD,ADDITIONAL> actual )
            {
                return new TrackingRecordProxy<>( actual, false, tracker );
            }
        };
    }

    @Override
    public Iterable<RecordProxy<RECORD,ADDITIONAL>> changes()
    {
        return new IterableWrapper<RecordProxy<RECORD,ADDITIONAL>,RecordProxy<RECORD,ADDITIONAL>>(
                delegate.changes() )
        {
            @Override
            protected RecordProxy<RECORD,ADDITIONAL> underlyingObjectToObject(
                    RecordProxy<RECORD,ADDITIONAL> actual )
            {
                return new TrackingRecordProxy<>( actual, false, tracker );
            }
        };
    }

Replace Generic With Diamond IterableWrapper<RecordProxy<RECORD,ADDITIONAL>,RecordProxy<RECORD,ADDITIONAL>> with IterableWrapper<> in method public changes() : Iterable<RecordProxy<RECORD,ADDITIONAL>> from class org.neo4j.kernel.impl.transaction.state.TrackingRecordAccess


    @Test
    void shouldStopProcessingRecordsWhenSignalledToStop()
    {
        // given
        ConsistencyReport.Reporter reporter = mock( ConsistencyReport.Reporter.class );
        StoreProcessor processor = new StoreProcessor( CheckDecorator.NONE,
                reporter, Stage.SEQUENTIAL_FORWARD, CacheAccess.EMPTY );
        RecordStore<NodeRecord> nodeStore = new RecordStore.Delegator<>( getNeoStores().getNodeStore() )
        {
            @Override
            public void getRecordByCursor( long id, NodeRecord target, RecordLoad mode, PageCursor cursor ) throws InvalidRecordException
            {
                if ( id == 3 )
                {
                    processor.stop();
                }
                super.getRecordByCursor( id, target, mode, cursor );
            }
        };
        nodeStore.updateRecord( node( 0, false, 0, 0 ) );
        nodeStore.updateRecord( node( 1, false, 0, 0 ) );
        nodeStore.updateRecord( node( 2, false, 0, 0 ) );
        nodeStore.updateRecord( node( 3, false, 0, 0 ) );
        nodeStore.updateRecord( node( 4, false, 0, 0 ) );
        nodeStore.setHighestPossibleIdInUse( 4 );

        // when
        processor.applyFiltered( nodeStore );

        // then
        verify( reporter, times( 3 ) ).forNode( any( NodeRecord.class ), any( RecordCheck.class ) );
    }

    @Test
    void shouldStopProcessingRecordsWhenSignalledToStop() throws Exception
    {
        // given
        ConsistencyReport.Reporter reporter = mock( ConsistencyReport.Reporter.class );
        StoreProcessor processor = new StoreProcessor( CheckDecorator.NONE,
                reporter, Stage.SEQUENTIAL_FORWARD, CacheAccess.EMPTY );
        RecordStore<NodeRecord> nodeStore = new RecordStore.Delegator<NodeRecord>( getNeoStores().getNodeStore() )
        {
            @Override
            public void getRecordByCursor( long id, NodeRecord target, RecordLoad mode, PageCursor cursor ) throws InvalidRecordException
            {
                if ( id == 3 )
                {
                    processor.stop();
                }
                super.getRecordByCursor( id, target, mode, cursor );
            }
        };
        nodeStore.updateRecord( node( 0, false, 0, 0 ) );
        nodeStore.updateRecord( node( 1, false, 0, 0 ) );
        nodeStore.updateRecord( node( 2, false, 0, 0 ) );
        nodeStore.updateRecord( node( 3, false, 0, 0 ) );
        nodeStore.updateRecord( node( 4, false, 0, 0 ) );
        nodeStore.setHighestPossibleIdInUse( 4 );

        // when
        processor.applyFiltered( nodeStore );

        // then
        verify( reporter, times( 3 ) ).forNode( any( NodeRecord.class ), any( RecordCheck.class ) );
    }

Replace Generic With Diamond RecordStore.Delegator<NodeRecord> with RecordStore.Delegator<> in method package shouldStopProcessingRecordsWhenSignalledToStop() : void from class org.neo4j.consistency.checking.full.StoreProcessorIT


    public static Matcher<TransportConnection> eventuallyDisconnects()
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( TransportConnection connection )
            {
                BooleanSupplier condition = () ->
                {
                    try
                    {
                        connection.send( new byte[]{0, 0} );
                        connection.recv( 1 );
                    }
                    catch ( Exception e )
                    {
                        // take an IOException on send/receive as evidence of disconnection
                        return e instanceof IOException;
                    }
                    return false;
                };
                try
                {
                    Predicates.await( condition, 2, TimeUnit.SECONDS );
                    return true;
                }
                catch ( Exception e )
                {
                    return false;
                }
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "Eventually Disconnects" );
            }
        };
    }

    public static Matcher<TransportConnection> eventuallyDisconnects()
    {
        return new TypeSafeMatcher<TransportConnection>()
        {
            @Override
            protected boolean matchesSafely( TransportConnection connection )
            {
                BooleanSupplier condition = () ->
                {
                    try
                    {
                        connection.send( new byte[]{0,0});
                        connection.recv( 1 );
                    }
                    catch ( Exception e )
                    {
                        // take an IOException on send/receive as evidence of disconnection
                        return e instanceof IOException;
                    }
                    return false;
                };
                try
                {
                    Predicates.await( condition, 2, TimeUnit.SECONDS );
                    return true;
                }
                catch ( Exception e )
                {
                    return false;
                }
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( "Eventually Disconnects" );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<TransportConnection> with TypeSafeMatcher<> in method public eventuallyDisconnects() : Matcher<TransportConnection> from class org.neo4j.bolt.testing.TransportTestUtil


    @SafeVarargs
    private static Matcher<List<String>> containsAtLeastTheseLines( final Matcher<String>... expectedLinePatterns )
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( List<String> lines )
            {
                if ( expectedLinePatterns.length > lines.size() )
                {
                    return false;
                }

                for ( int i = 0, e = 0; i < lines.size(); i++ )
                {
                    String line = lines.get( i );
                    while ( !expectedLinePatterns[e].matches( line ) )
                    {
                        if ( ++i >= lines.size() )
                        {
                            return false;
                        }
                        line = lines.get( i );
                    }
                    e++;
                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendList( "", "\n", "", asList( expectedLinePatterns ) );
            }
        };
    }

    @SafeVarargs
    private static Matcher<List<String>> containsAtLeastTheseLines( final Matcher<String>... expectedLinePatterns )
    {
        return new TypeSafeMatcher<List<String>>()
        {
            @Override
            protected boolean matchesSafely( List<String> lines )
            {
                if ( expectedLinePatterns.length > lines.size() )
                {
                    return false;
                }

                for ( int i = 0, e = 0; i < lines.size(); i++ )
                {
                    String line = lines.get( i );
                    while ( !expectedLinePatterns[e].matches( line ) )
                    {
                        if ( ++i >= lines.size() )
                        {
                            return false;
                        }
                        line = lines.get( i );
                    }
                    e++;

                }
                return true;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendList( "", "\n", "", asList(expectedLinePatterns) );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<List<String>> with TypeSafeMatcher<> in method private containsAtLeastTheseLines(expectedLinePatterns Matcher<String>...) : Matcher<List<String>> from class org.neo4j.server.StartupLoggingIT


    public static Matcher<String> line( final String level, final String messagePattern )
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( String line )
            {
                return line.matches( ".*" + level + "\\s+" + messagePattern );
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( level ).appendText( " " ).appendText( messagePattern );
            }
        };
    }

    public static Matcher<String> line( final String level, final String messagePattern )
    {
        return new TypeSafeMatcher<String>()
        {
            @Override
            protected boolean matchesSafely( String line )
            {
                return line.matches( ".*" + level + "\\s+" + messagePattern );
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendText( level ).appendText( " " ).appendText( messagePattern );
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<String> with TypeSafeMatcher<> in method public line(level String, messagePattern String) : Matcher<String> from class org.neo4j.server.StartupLoggingIT


    /**
     * This matcher is hardcoded to check for a list containing one deleted node and one map with a
     * deleted node mapped to the key `someKey`.
     */
    private static Matcher<? super Response> restContainsNestedDeleted()
    {
        return new TypeSafeMatcher<>()
        {
            @Override
            protected boolean matchesSafely( HTTP.Response response )
            {
                try
                {
                    JsonNode list = TransactionMatchers.getJsonNodeWithName( response, "rest" ).iterator().next();

                    assertThat( list.get( 0 ).get( "metadata" ).get( "deleted" ).asBoolean(), equalTo( Boolean.TRUE ) );
                    assertThat( list.get( 1 ).get( "someKey" ).get( "metadata" ).get( "deleted" ).asBoolean(), equalTo( Boolean.TRUE ) );

                    return true;
                }
                catch ( JsonParseException e )
                {
                    return false;
                }
            }

            @Override
            public void describeTo( Description description )
            {
            }
        };
    }

    /**
     * This matcher is hardcoded to check for a list containing one deleted node and one map with a
     * deleted node mapped to the key `someKey`.
     */
    private static Matcher<? super Response> restContainsNestedDeleted()
    {
        return new TypeSafeMatcher<Response>()
        {
            @Override
            protected boolean matchesSafely( HTTP.Response response )
            {
                try
                {
                    JsonNode list = TransactionMatchers.getJsonNodeWithName( response, "rest" ).iterator().next();

                    assertThat( list.get( 0 ).get( "metadata" ).get( "deleted" ).asBoolean(), equalTo( Boolean.TRUE ) );
                    assertThat( list.get( 1 ).get( "someKey" ).get( "metadata" ).get( "deleted" ).asBoolean(),
                            equalTo( Boolean.TRUE ) );

                    return true;
                }
                catch ( JsonParseException e )
                {
                    return false;
                }
            }

            @Override
            public void describeTo( Description description )
            {
            }
        };
    }

Replace Generic With Diamond TypeSafeMatcher<Response> with TypeSafeMatcher<> in method private restContainsNestedDeleted() : Matcher<? super Response> from class org.neo4j.server.http.cypher.integration.QueryResultsSerializationTest


    private static void storeProperties( File file, Properties properties )
    {
        try ( OutputStream out = new FileOutputStream( file ) )
        {
            properties.store( out, "" );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

    private static void storeProperties( File file, Properties properties )
    {
        OutputStream out = null;
        try
        {
            out = new FileOutputStream( file );
            properties.store( out, "" );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
        finally
        {
            safeClose( out );
        }
    }

Try With Resources try(OutputStream out=new FileOutputStream(file)) in method private storeProperties(file File, properties Properties) : void from class org.neo4j.server.ServerTestUtils


    private static Properties loadProperties( File file )
    {
        Properties properties = new Properties();
        if ( file.exists() )
        {
            try ( InputStream in = new FileInputStream( file ) )
            {
                properties.load( in );
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
        }
        return properties;
    }

    private static Properties loadProperties( File file )
    {
        Properties properties = new Properties();
        if ( file.exists() )
        {
            InputStream in = null;
            try
            {
                in = new FileInputStream( file );
                properties.load( in );
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
            finally
            {
                safeClose( in );
            }
        }
        return properties;
    }

Try With Resources try(InputStream in=new FileInputStream(file)) in method private loadProperties(file File) : Properties from class org.neo4j.server.ServerTestUtils


    /** Match a RecordChangeSet */
    public DiffAssert<RecordChangeSet> containsChanges( AbstractBaseRecord... expectedChanges )
    {
        DiffAssert<Iterable<? extends AbstractBaseRecord>> nodes = containsRecords( "nodes", filterType( expectedChanges, NodeRecord.class ) );
        DiffAssert<Iterable<? extends AbstractBaseRecord>> rels = containsRecords( "relationships", filterType( expectedChanges, RelationshipRecord.class ) );
        DiffAssert<Iterable<? extends AbstractBaseRecord>> groups =
                containsRecords( "relationship groups", filterType( expectedChanges, RelationshipGroupRecord.class ) );

        return new DiffAssert<>()
        {
            @Override
            String diff( RecordChangeSet actual )
            {
                String diff;

                diff = nodes.diff( records( actual.getNodeRecords().changes() ) );
                if ( diff != null )
                {
                    return diff;
                }

                diff = rels.diff( records( actual.getRelRecords().changes() ) );
                if ( diff != null )
                {
                    return diff;
                }

                diff = groups.diff( records( actual.getRelGroupRecords().changes() ) );
                return diff;
            }
        };
    }

    /** Match a RecordChangeSet */
    public static DiffMatcher<RecordChangeSet> containsChanges( AbstractBaseRecord... expectedChanges )
    {
        DiffMatcher<Iterable<? extends AbstractBaseRecord>> nodes =
                containsRecords( "nodes", filterType( expectedChanges, NodeRecord.class ) );
        DiffMatcher<Iterable<? extends AbstractBaseRecord>> rels =
                containsRecords( "relationships",
                        filterType( expectedChanges, RelationshipRecord.class ) );
        DiffMatcher<Iterable<? extends AbstractBaseRecord>> groups =
                containsRecords( "relationship groups",
                        filterType( expectedChanges, RelationshipGroupRecord.class ) );

        return new DiffMatcher<RecordChangeSet>()
        {
            @Override
            String diff( RecordChangeSet actual )
            {
                String diff;

                diff = nodes.diff( records( actual.getNodeRecords().changes() ) );
                if ( diff != null )
                {
                    return diff;
                }

                diff = rels.diff( records( actual.getRelRecords().changes() )  );
                if ( diff != null )
                {
                    return diff;
                }

                diff = groups.diff( records( actual.getRelGroupRecords().changes() )  );
                if ( diff != null )
                {
                    return diff;
                }

                return null;
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendValueList( "[", ",", "]", expectedChanges );
            }
        };
    }

Replace Generic With Diamond DiffMatcher<RecordChangeSet> with DiffAssert<> in method public containsChanges(expectedChanges AbstractBaseRecord...) : DiffAssert<RecordChangeSet> from class org.neo4j.internal.recordstorage.RecordAssert


    public DiffAssert<Iterable<? extends AbstractBaseRecord>> containsRecords(
            String recordPlural, Stream<? extends AbstractBaseRecord> expected )
    {
        Map<Long,AbstractBaseRecord> expectedById = expected.collect( toMap( AbstractBaseRecord::getId, identity() ) );
        return new DiffAssert<>()
        {
            @Override
            String diff( Iterable<? extends AbstractBaseRecord> actual )
            {
                Set<Long> seen = new HashSet<>( expectedById.keySet() );
                for ( AbstractBaseRecord record : actual )
                {
                    seen.remove( record.getId() );
                    if ( !expectedById.containsKey( record.getId() ) )
                    {
                        return String.format( "This record was not expected: %s", record );
                    }

                    String diff = diff( expectedById.get( record.getId() ), record );
                    if ( diff != null )
                    {
                        return diff;
                    }
                }

                return null;
            }

            private String diff( AbstractBaseRecord expected, AbstractBaseRecord actual )
            {
                if ( expected instanceof NodeRecord )
                {
                    return diff( (NodeRecord) expected, (NodeRecord) actual );
                }
                if ( expected instanceof RelationshipRecord )
                {
                    return diff( (RelationshipRecord) expected, (RelationshipRecord) actual );
                }
                if ( expected instanceof RelationshipGroupRecord )
                {
                    return diff( (RelationshipGroupRecord) expected, (RelationshipGroupRecord) actual );
                }
                throw new UnsupportedOperationException( String.format( "No diff implementation (just add one, its easy) for: %s", expected ) );
            }

            private String diff( NodeRecord expected, NodeRecord actual )
            {
                if ( actual.getId() == expected.getId() && actual.getNextRel() == expected.getNextRel() && actual.getLabelField() == expected.getLabelField() &&
                        actual.getNextProp() == expected.getNextProp() && actual.isDense() == expected.isDense() && actual.isLight() == expected.isLight() )
                {
                    return null;
                }
                return describeDiff( expected.toString(), actual.toString() );
            }

            private String diff( RelationshipGroupRecord expected, RelationshipGroupRecord actual )
            {
                if ( actual.getId() == expected.getId() && actual.getType() == expected.getType() && actual.getNext() == expected.getNext() &&
                        actual.getFirstOut() == expected.getFirstOut() && actual.getFirstIn() == expected.getFirstIn() &&
                        actual.getFirstLoop() == expected.getFirstLoop() && actual.getOwningNode() == expected.getOwningNode() )
                {
                    return null;
                }
                return describeDiff( expected.toString(), actual.toString() );
            }

            private String diff( RelationshipRecord expected, RelationshipRecord actual )
            {
                if ( actual.getId() == expected.getId() && actual.getFirstNode() == expected.getFirstNode() &&
                        actual.getSecondNode() == expected.getSecondNode() && actual.getType() == expected.getType() &&
                        actual.getFirstPrevRel() == expected.getFirstPrevRel() && actual.getFirstNextRel() == expected.getFirstNextRel() &&
                        actual.getSecondPrevRel() == expected.getSecondPrevRel() && actual.getSecondNextRel() == expected.getSecondNextRel() &&
                        actual.isFirstInFirstChain() == expected.isFirstInFirstChain() && actual.isFirstInSecondChain() == expected.isFirstInSecondChain() )
                {
                    return null;
                }
                return describeDiff( expected.toString(), actual.toString() );
            }

            private String describeDiff( String expected, String actual )
            {
                StringBuilder arrow = new StringBuilder();
                char[] expectedChars = expected.toCharArray();
                char[] actualChars = actual.toCharArray();
                for ( int i = 0; i < Math.min( expectedChars.length, actualChars.length ); i++ )
                {
                    if ( expectedChars[i] != actualChars[i] )
                    {
                        break;
                    }
                    arrow.append( "-" );
                }
                return String.format( "Record fields don't match.\n" + "Expected: %s\n" + "Actual:   %s\n" + "          %s", expected, actual,
                        arrow.append( "^" ).toString() );
            }
        };
    }

    public static DiffMatcher<Iterable<? extends AbstractBaseRecord>> containsRecords(
            String recordPlural, Stream<? extends AbstractBaseRecord> expected )
    {
        Map<Long,AbstractBaseRecord> expectedById = expected.collect(
                Collectors.toMap( AbstractBaseRecord::getId, Functions.identity() ) );
        return new DiffMatcher<Iterable<? extends AbstractBaseRecord>>()
        {
            @Override
            String diff( Iterable<? extends AbstractBaseRecord> actual )
            {
                Set<Long> seen = new HashSet<>( expectedById.keySet() );
                for ( AbstractBaseRecord record : actual )
                {
                    seen.remove( record.getId() );
                    if ( !expectedById.containsKey( record.getId() ) )
                    {
                        return String.format( "This record was not expected: %s",
                                record );
                    }

                    String diff = diff( expectedById.get( record.getId() ), record );
                    if ( diff != null )
                    {
                        return diff;
                    }
                }

                return null;
            }

            private String diff( AbstractBaseRecord expected, AbstractBaseRecord actual )
            {
                if ( expected instanceof NodeRecord )
                {
                    return diff( (NodeRecord) expected, (NodeRecord) actual );
                }
                if ( expected instanceof RelationshipRecord )
                {
                    return diff( (RelationshipRecord) expected,
                            (RelationshipRecord) actual );
                }
                if ( expected instanceof RelationshipGroupRecord )
                {
                    return diff( (RelationshipGroupRecord) expected,
                            (RelationshipGroupRecord) actual );
                }
                throw new UnsupportedOperationException(
                        String.format( "No diff implementation (just add one, its easy) for: %s",
                                expected ) );
            }

            private String diff( NodeRecord expected, NodeRecord actual )
            {
                if ( actual.getId() == expected.getId() &&
                        actual.getNextRel() == expected.getNextRel() &&
                        actual.getLabelField() == expected.getLabelField() &&
                        actual.getNextProp() == expected.getNextProp() &&
                        actual.isDense() == expected.isDense() &&
                        actual.isLight() == expected.isLight() )
                {
                    return null;
                }
                return describeDiff( expected.toString(), actual.toString() );
            }

            private String diff( RelationshipGroupRecord expected, RelationshipGroupRecord actual )
            {
                if ( actual.getId() == expected.getId() &&
                        actual.getType() == expected.getType() &&
                        actual.getNext() == expected.getNext() &&
                        actual.getFirstOut() == expected.getFirstOut() &&
                        actual.getFirstIn() == expected.getFirstIn() &&
                        actual.getFirstLoop() == expected.getFirstLoop() &&
                        actual.getOwningNode() == expected.getOwningNode() )
                {
                    return null;
                }
                return describeDiff( expected.toString(), actual.toString() );
            }

            private String diff( RelationshipRecord expected, RelationshipRecord actual )
            {
                if ( actual.getId() == expected.getId() &&
                        actual.getFirstNode() == expected.getFirstNode() &&
                        actual.getSecondNode() == expected.getSecondNode() &&
                        actual.getType() == expected.getType() &&
                        actual.getFirstPrevRel() == expected.getFirstPrevRel() &&
                        actual.getFirstNextRel() == expected.getFirstNextRel() &&
                        actual.getSecondPrevRel() == expected.getSecondPrevRel() &&
                        actual.getSecondNextRel() == expected.getSecondNextRel() &&
                        actual.isFirstInFirstChain() == expected.isFirstInFirstChain() &&
                        actual.isFirstInSecondChain() == expected.isFirstInSecondChain() )
                {
                    return null;
                }
                return describeDiff( expected.toString(), actual.toString() );
            }

            private String describeDiff( String expected, String actual )
            {
                StringBuilder arrow = new StringBuilder();
                char[] expectedChars = expected.toCharArray();
                char[] actualChars = actual.toCharArray();
                for ( int i = 0; i < Math.min( expectedChars.length, actualChars.length );
                        i++ )
                {
                    if ( expectedChars[i] != actualChars[i] )
                    {
                        break;
                    }
                    arrow.append( "-" );
                }
                return String.format( "Record fields don't match.\n" + "Expected: %s\n" +
                                "Actual:   %s\n" + "          %s", expected, actual,
                        arrow.append( "^" ).toString() );
            }

            @Override
            public void describeTo( Description description )
            {
                description.appendValueList(
                        String.format( "%s matching:\n  ", recordPlural ), "\n  ", "",
                        expectedById.values() );
            }
        };
    }

Replace Generic With Diamond DiffMatcher<Iterable<? extends AbstractBaseRecord>> with DiffAssert<> in method public containsRecords(recordPlural String, expected Stream<? extends AbstractBaseRecord>) : DiffAssert<Iterable<? extends AbstractBaseRecord>> from class org.neo4j.internal.recordstorage.RecordAssert


    private LongPredicate createSamplingPredicate()
    {
        return indexId -> {
            DoubleLongRegister output = newDoubleLongRegister();
            indexStatisticsStore.indexUpdatesAndSize( indexId, output );
            long updates = output.readFirst();
            long size = output.readSecond();
            long threshold = Math.round( config.updateRatio() * size );
            return updates > threshold;
        };
    }

    private Predicate<Long> createSamplingPredicate()
    {
        return new Predicate<>()
        {
            private final DoubleLongRegister output = newDoubleLongRegister();

            @Override
            public boolean test( Long indexId )
            {
                indexStatisticsStore.indexUpdatesAndSize( indexId, output );
                long updates = output.readFirst();
                long size = output.readSecond();
                long threshold = Math.round( config.updateRatio() * size );
                return updates > threshold;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.sampling.IndexSamplingControllerFactory.createSamplingPredicate.new Predicate<> with indexId -> {DoubleLongRegister output=newDoubleLongRegister(); in method private createSamplingPredicate() : LongPredicate from class org.neo4j.kernel.impl.api.index.sampling.IndexSamplingControllerFactory


    @Override
    public void shutdown()
    {
        if ( isShutdown )
        {
            throw new IllegalStateException( "Batch inserter already has shutdown" );
        }
        isShutdown = true;

        flushStrategy.forceFlush();

        try ( var ignore = new Lifespan( life ); locker; neoStores )
        {
            rebuildCounts();
            NativeLabelScanStore labelIndex = buildLabelIndex();
            repopulateAllIndexes( labelIndex );
            idGeneratorFactory.visit( IdGenerator::markHighestWrittenAtHighId );
            neoStores.flush( IOLimiter.UNLIMITED );
            createEmptyTransactionLog();
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
        msgLog.info( Thread.currentThread() + " Clean shutdown on BatchInserter(" + this + ")" );
    }

    @Override
    public void shutdown()
    {
        if ( isShutdown )
        {
            throw new IllegalStateException( "Batch inserter already has shutdown" );
        }
        isShutdown = true;

        flushStrategy.forceFlush();

        try
        {
            rebuildCounts();
            NativeLabelScanStore labelIndex = buildLabelIndex();
            repopulateAllIndexes( labelIndex );
            idGeneratorFactory.visit( IdGenerator::markHighestWrittenAtHighId );
            neoStores.flush( IOLimiter.UNLIMITED );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
        finally
        {
            createEmptyTransactionLog();

            neoStores.close();
            try
            {
                locker.close();
            }
            catch ( IOException e )
            {
                throw new UnderlyingStorageException( "Could not release store lock", e );
            }

            msgLog.info( Thread.currentThread() + " Clean shutdown on BatchInserter(" + this + ")" );
            life.shutdown();
        }
    }

Try With Resources try(var ignore=new Lifespan(life); locker; neoStores) in method public shutdown() : void from class org.neo4j.batchinsert.internal.BatchInserterImpl


    @Override
    public Node createNode()
    {
        var ktx = kernelTransaction();
        try ( Statement ignore = ktx.acquireStatement() )
        {
            return newNodeEntity( ktx.dataWrite().nodeCreate() );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public Node createNode()
    {
        var ktx = kernelTransaction();
        try
        {
            return newNodeEntity( ktx.dataWrite().nodeCreate() );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=ktx.acquireStatement()) in method public createNode() : Node from class org.neo4j.kernel.impl.coreapi.TransactionImpl


    @Override
    public Node createNode( Label... labels )
    {
        var ktx = kernelTransaction();
        try ( Statement ignore = ktx.acquireStatement() )
        {
            TokenWrite tokenWrite = ktx.tokenWrite();
            int[] labelIds = new int[labels.length];
            String[] labelNames = new String[labels.length];
            for ( int i = 0; i < labelNames.length; i++ )
            {
                labelNames[i] = labels[i].name();
            }
            tokenWrite.labelGetOrCreateForNames( labelNames, labelIds );

            Write write = ktx.dataWrite();
            long nodeId = write.nodeCreateWithLabels( labelIds );
            return newNodeEntity( nodeId );
        }
        catch ( ConstraintValidationException e )
        {
            throw new ConstraintViolationException( "Unable to add label.", e );
        }
        catch ( SchemaKernelException e )
        {
            throw new IllegalArgumentException( e );
        }
        catch ( KernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public Node createNode( Label... labels )
    {
        var ktx = kernelTransaction();
        try
        {
            TokenWrite tokenWrite = ktx.tokenWrite();
            int[] labelIds = new int[labels.length];
            String[] labelNames = new String[labels.length];
            for ( int i = 0; i < labelNames.length; i++ )
            {
                labelNames[i] = labels[i].name();
            }
            tokenWrite.labelGetOrCreateForNames( labelNames, labelIds );

            Write write = ktx.dataWrite();
            long nodeId = write.nodeCreateWithLabels( labelIds );
            return newNodeEntity( nodeId );
        }
        catch ( ConstraintValidationException e )
        {
            throw new ConstraintViolationException( "Unable to add label.", e );
        }
        catch ( SchemaKernelException e )
        {
            throw new IllegalArgumentException( e );
        }
        catch ( KernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=ktx.acquireStatement()) in method public createNode(labels Label...) : Node from class org.neo4j.kernel.impl.coreapi.TransactionImpl


    @Override
    public void setProperty( String key, Object value )
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int propertyKeyId;
        try
        {
            propertyKeyId = transaction.tokenWrite().propertyKeyGetOrCreateForName( key );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e );
        }
        catch ( TokenCapacityExceededKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to create property key token", 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 )
        {
            try
            {
                transaction.rollback();
            }
            catch ( org.neo4j.internal.kernel.api.exceptions.TransactionFailureException ex )
            {
                ex.addSuppressed( e );
                throw new TransactionFailureException( "Fail to rollback transaction.", ex );
            }
            throw e;
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( KernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public void setProperty( String key, Object value )
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int propertyKeyId;
        try
        {
            propertyKeyId = transaction.tokenWrite().propertyKeyGetOrCreateForName( key );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e );
        }
        catch ( TokenCapacityExceededKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to create property key token", 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 )
        {
            try
            {
                transaction.rollback();
            }
            catch ( org.neo4j.internal.kernel.api.exceptions.TransactionFailureException ex )
            {
                ex.addSuppressed( e );
                throw new TransactionFailureException( "Fail to rollback transaction.", ex );
            }
            throw e;
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( 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.NodeEntity


    @Override
    public Object removeProperty( String key ) throws NotFoundException
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int propertyKeyId;
        try ( Statement ignore = transaction.acquireStatement() )
        {
            propertyKeyId = transaction.tokenWrite().propertyKeyGetOrCreateForName( key );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to get property key token", e );
        }

        try
        {
            return transaction.dataWrite().nodeRemoveProperty( nodeId, propertyKeyId ).asObjectCopy();
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public Object removeProperty( String key ) throws NotFoundException
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int propertyKeyId;
        try
        {
            propertyKeyId = transaction.tokenWrite().propertyKeyGetOrCreateForName( key );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to get property key token", e );
        }

        try
        {
            return transaction.dataWrite().nodeRemoveProperty( nodeId, propertyKeyId ).asObjectCopy();
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=transaction.acquireStatement()) in method public removeProperty(key String) : Object from class org.neo4j.kernel.impl.core.NodeEntity


    @Override
    public Relationship createRelationshipTo( Node otherNode, RelationshipType type )
    {
        if ( otherNode == null )
        {
            throw new IllegalArgumentException( "Other node is null." );
        }

        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int relationshipTypeId;
        try ( Statement ignore = transaction.acquireStatement() )
        {
            relationshipTypeId = transaction.tokenWrite().relationshipTypeGetOrCreateForName( type.name() );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( e );
        }
        catch ( TokenCapacityExceededKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to create relationship type token", e );
        }

        try
        {
            long relationshipId = transaction.dataWrite().relationshipCreate( nodeId, relationshipTypeId, otherNode.getId() );
            return internalTransaction.newRelationshipEntity( relationshipId, nodeId, relationshipTypeId, otherNode.getId() );
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( "Node[" + e.entityId() + "] is deleted and cannot be used to create a relationship" );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public Relationship createRelationshipTo( Node otherNode, RelationshipType type )
    {
        if ( otherNode == null )
        {
            throw new IllegalArgumentException( "Other node is null." );
        }

        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int relationshipTypeId;
        try
        {
            relationshipTypeId = transaction.tokenWrite().relationshipTypeGetOrCreateForName( type.name() );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( e );
        }
        catch ( TokenCapacityExceededKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to create relationship type token", e );
        }

        try
        {
            long relationshipId = transaction.dataWrite().relationshipCreate( nodeId, relationshipTypeId, otherNode.getId() );
            return internalTransaction.newRelationshipEntity( relationshipId, nodeId, relationshipTypeId, otherNode.getId() );
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( "Node[" + e.entityId() + "] is deleted and cannot be used to create a relationship" );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=transaction.acquireStatement()) in method public createRelationshipTo(otherNode Node, type RelationshipType) : Relationship from class org.neo4j.kernel.impl.core.NodeEntity


    @Override
    public void addLabel( Label label )
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int labelId;
        try ( Statement ignore = transaction.acquireStatement() )
        {
            labelId = transaction.tokenWrite().labelGetOrCreateForName( label.name() );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new ConstraintViolationException( format( "Invalid label name '%s'.", label.name() ), e );
        }
        catch ( TokenCapacityExceededKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to create label token", e );
        }

        try
        {
            transaction.dataWrite().nodeAddLabel( getId(), labelId );
        }
        catch ( ConstraintValidationException e )
        {
            throw new ConstraintViolationException(
            e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), 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 = internalTransaction.kernelTransaction();
        int labelId;
        try
        {
            labelId = transaction.tokenWrite().labelGetOrCreateForName( label.name() );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new ConstraintViolationException( format( "Invalid label name '%s'.", label.name() ), e );
        }
        catch ( TokenCapacityExceededKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to create label token", e );
        }

        try
        {
            transaction.dataWrite().nodeAddLabel( getId(), labelId );
        }
        catch ( ConstraintValidationException e )
        {
            throw new ConstraintViolationException(
            e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), 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.NodeEntity


    @Override
    public void removeLabel( Label label )
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        try ( Statement ignore = transaction.acquireStatement() )
        {
            int labelId = transaction.tokenRead().nodeLabel( label.name() );
            if ( labelId != TokenRead.NO_TOKEN )
            {
                transaction.dataWrite().nodeRemoveLabel( getId(), labelId );
            }
        }
        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 removeLabel( Label label )
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        try
        {
            int labelId = transaction.tokenRead().nodeLabel( label.name() );
            if ( labelId != TokenRead.NO_TOKEN )
            {
                transaction.dataWrite().nodeRemoveLabel( getId(), labelId );
            }
        }
        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 removeLabel(label Label) : void from class org.neo4j.kernel.impl.core.NodeEntity


    @Override
    public Iterable<Label> getLabels()
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        NodeCursor nodes = transaction.ambientNodeCursor();
        try ( Statement ignore = transaction.acquireStatement() )
        {
            singleNode( transaction, nodes );
            LabelSet labelSet = nodes.labels();
            TokenRead tokenRead = transaction.tokenRead();
            ArrayList<Label> list = new ArrayList<>( labelSet.numberOfLabels() );
            for ( int i = 0; i < labelSet.numberOfLabels(); i++ )
            {
                list.add( label( tokenRead.nodeLabelName( labelSet.label( i ) ) ) );
            }
            return list;
        }
        catch ( LabelNotFoundKernelException e )
        {
            throw new IllegalStateException( "Label retrieved through kernel API should exist.", e );
        }
    }

    @Override
    public Iterable<Label> getLabels()
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        NodeCursor nodes = transaction.ambientNodeCursor();
        try
        {
            singleNode( transaction, nodes );
            LabelSet labelSet = nodes.labels();
            TokenRead tokenRead = transaction.tokenRead();
            ArrayList<Label> list = new ArrayList<>( labelSet.numberOfLabels() );
            for ( int i = 0; i < labelSet.numberOfLabels(); i++ )
            {
                list.add( label( tokenRead.nodeLabelName( labelSet.label( i ) ) ) );
            }
            return list;
        }
        catch ( LabelNotFoundKernelException e )
        {
            throw new IllegalStateException( "Label retrieved through kernel API should exist.", e );
        }
    }

Try With Resources try(Statement ignore=transaction.acquireStatement()) in method public getLabels() : Iterable<Label> from class org.neo4j.kernel.impl.core.NodeEntity


    @Override
    public void setProperty( String key, Object value )
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int propertyKeyId;
        try
        {
            propertyKeyId = transaction.tokenWrite().propertyKeyGetOrCreateForName( key );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e );
        }
        catch ( TokenCapacityExceededKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to create property key token", e );
        }

        try ( Statement ignore = transaction.acquireStatement() )
        {
            transaction.dataWrite().relationshipSetProperty( id, propertyKeyId, Values.of( value, false ) );
        }
        catch ( IllegalArgumentException e )
        {
            try
            {
                transaction.rollback();
            }
            catch ( org.neo4j.internal.kernel.api.exceptions.TransactionFailureException ex )
            {
                ex.addSuppressed( e );
                throw new TransactionFailureException( "Fail to rollback transaction.", ex );
            }
            throw e;
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public void setProperty( String key, Object value )
    {
        KernelTransaction transaction = internalTransaction.kernelTransaction();
        int propertyKeyId;
        try
        {
            propertyKeyId = transaction.tokenWrite().propertyKeyGetOrCreateForName( key );
        }
        catch ( IllegalTokenNameException e )
        {
            throw new IllegalArgumentException( format( "Invalid property key '%s'.", key ), e );
        }
        catch ( TokenCapacityExceededKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( KernelException e )
        {
            throw new TransactionFailureException( "Unknown error trying to create property key token", e );
        }

        try
        {
            transaction.dataWrite().relationshipSetProperty( id, propertyKeyId, Values.of( value, false ) );
        }
        catch ( IllegalArgumentException e )
        {
            try
            {
                transaction.rollback();
            }
            catch ( org.neo4j.internal.kernel.api.exceptions.TransactionFailureException ex )
            {
                ex.addSuppressed( e );
                throw new TransactionFailureException( "Fail to rollback transaction.", ex );
            }
            throw e;
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( InvalidTransactionTypeKernelException 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.RelationshipEntity