    @Test
    public void shouldDetectCorrectDuplicateInputIdsWhereManyAccidentalInManyGroups() throws Exception
    {
        // GIVEN
        final ControlledEncoder encoder = new ControlledEncoder( new LongEncoder() );
        IdMapper mapper = mapper( encoder, Radix.LONG, NO_MONITOR );
        final int idsPerGroup = 20;
        int groups = 5;
        final AtomicReference<Group> group = new AtomicReference<>();
        LongFunction<Object> ids = nodeId ->
        {
            int groupId = toIntExact( nodeId / idsPerGroup );
            if ( groupId == groups )
            {
                return null;
            }
            group.set( new Group.Adapter( groupId, "Group " + groupId ) );

            // Let the first 10% in each group be accidental collisions with each other
            // i.e. all first 10% in each group collides with all other first 10% in each group
            if ( nodeId % idsPerGroup < 2 )
            {   // Let these colliding values encode into the same eId as well,
                // so that they are definitely marked as collisions
                encoder.useThisIdToEncodeNoMatterWhatComesIn( Long.valueOf( 1234567 ) );
                return Long.valueOf( nodeId % idsPerGroup );
            }

            // The other 90% will be accidental collisions for something else
            encoder.useThisIdToEncodeNoMatterWhatComesIn( Long.valueOf( 123456 - group.get().id() ) );
            return Long.valueOf( nodeId );
        };

        // WHEN
        int count = idsPerGroup * groups;
        for ( long nodeId = 0; nodeId < count; nodeId++ )
        {
            mapper.put( ids.apply( nodeId ), nodeId, group.get() );
        }
        Collector collector = mock( Collector.class );
        mapper.prepare( ids, collector, NONE );

        // THEN
        verifyNoMoreInteractions( collector );
        for ( long nodeId = 0; nodeId < count; nodeId++ )
        {
            assertEquals( nodeId, mapper.get( ids.apply( nodeId ), group.get() ) );
        }
    }

    @Test
    public void shouldDetectCorrectDuplicateInputIdsWhereManyAccidentalInManyGroups() throws Exception
    {
        // GIVEN
        final ControlledEncoder encoder = new ControlledEncoder( new LongEncoder() );
        IdMapper mapper = mapper( encoder, Radix.LONG, NO_MONITOR );
        final int idsPerGroup = 20;
        int groups = 5;
        final AtomicReference<Group> group = new AtomicReference<>();
        InputIterable<Object> ids = SimpleInputIteratorWrapper.wrap( "source", () -> new PrefetchingIterator<Object>()
        {
            private int i;

            @Override
            protected Object fetchNextOrNull()
            {
                // Change group every <idsPerGroup> id
                if ( i % idsPerGroup == 0 )
                {
                    int groupId = i / idsPerGroup;
                    if ( groupId == groups )
                    {
                        return null;
                    }
                    group.set( new Group.Adapter( groupId, "Group " + groupId ) );
                }
                try
                {
                    // Let the first 10% in each group be accidental collisions with each other
                    // i.e. all first 10% in each group collides with all other first 10% in each group
                    if ( i % idsPerGroup < 2 )
                    {   // Let these colliding values encode into the same eId as well,
                        // so that they are definitely marked as collisions
                        encoder.useThisIdToEncodeNoMatterWhatComesIn( Long.valueOf( 1234567 ) );
                        return Long.valueOf( i % idsPerGroup );
                    }

                    // The other 90% will be accidental collisions for something else
                    encoder.useThisIdToEncodeNoMatterWhatComesIn( Long.valueOf( 123456 - group.get().id() ) );
                    return Long.valueOf( i );
                }
                finally
                {
                    i++;
                }
            }
        } );

        // WHEN
        long actualId = 0;
        for ( Object id : ids )
        {
            mapper.put( id, actualId++, group.get() );
        }
        Collector collector = mock( Collector.class );
        mapper.prepare( ids, collector, NONE );

        // THEN
        verifyNoMoreInteractions( collector );
        actualId = 0;
        for ( Object id : ids )
        {
            assertEquals( actualId++, mapper.get( id, group.get() ) );
        }
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.cache.idmapping.string.EncodingIdMapperTest.shouldDetectCorrectDuplicateInputIdsWhereManyAccidentalInManyGroups.ids.wrap.new PrefetchingIterator<Object> with nodeId -> {int groupId=toIntExact(nodeId / idsPerGroup); in method public shouldDetectCorrectDuplicateInputIdsWhereManyAccidentalInManyGroups() : void from class org.neo4j.unsafe.impl.batchimport.cache.idmapping.string.EncodingIdMapperTest


    public InMemoryIndexProvider( int prio )
    {
        this( prio, new CopyOnWriteHashMap<>() );
    }

    public InMemoryIndexProvider( int prio )
    {
        this( prio, new CopyOnWriteHashMap<Long, InMemoryIndex>() );
    }

Replace Generic With Diamond CopyOnWriteHashMap<Long,InMemoryIndex> with CopyOnWriteHashMap<> in method public InMemoryIndexProvider(prio int) from class org.neo4j.kernel.impl.api.index.inmemory.InMemoryIndexProvider


    private void writeConfigToFile( Config config, File file ) throws IOException
    {
        try ( Writer fileWriter = new BufferedWriter( new FileWriter( file ) ) )
        {
            for ( Map.Entry<String,String> entry : config.getRaw().entrySet() )
            {
                fileWriter.write( String.format( "%s=%s\n", entry.getKey(), entry.getValue() ) );
            }
        }
    }

    private void writeConfigToFile( Config config, File file )
    {
        try
        {
            Writer fileWriter = new BufferedWriter( new FileWriter( file ) );
            for ( Map.Entry<String,String> entry : config.getRaw().entrySet() )
            {
                fileWriter.write( String.format( "%s=%s\n", entry.getKey(), entry.getValue() ) );
            }
            fileWriter.close();
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

Try With Resources try(Writer fileWriter=new BufferedWriter(new FileWriter(file))) in method private writeConfigToFile(config Config, file File) : void from class org.neo4j.backup.impl.OnlineBackupCommandBuilder


    private void writeToFile( File output, String input ) throws IOException
    {
        try ( BufferedWriter bw = new BufferedWriter( new FileWriter( output ) ) )
        {
            bw.write( input );
            bw.close();
        }
    }

    private void writeToFile( File output, String input )
    {
        try
        {
            BufferedWriter bw = new BufferedWriter( new FileWriter( output ) );
            bw.write( input );
            bw.close();
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

Try With Resources try(BufferedWriter bw=new BufferedWriter(new FileWriter(output))) in method private writeToFile(output File, input String) : void from class org.neo4j.com.storecopy.FileMoveProviderTest


    BackupOutcome executeBackup( HostnamePort hostnamePort, Path to, ConsistencyCheck consistencyCheck,
                                 Config config, long timeout, boolean forensics ) throws ToolFailureException
    {
        try
        {
            systemOut.println( "Performing backup from '" + hostnamePort + "'" );
            String host = hostnamePort.getHost();
            int port = hostnamePort.getPort();

            BackupOutcome outcome = backupProtocolService.doIncrementalBackupOrFallbackToFull( host, port, to, consistencyCheck, config, timeout, forensics );
            systemOut.println( "Done" );
            return outcome;
        }
        catch ( UnexpectedStoreVersionException | IncrementalBackupNotPossibleException e )
        {
            throw new ToolFailureException( e.getMessage(), e );
        }
        catch ( MismatchingStoreIdException e )
        {
            throw new ToolFailureException( String.format( MISMATCHED_STORE_ID, e.getExpected(), e.getEncountered() ) );
        }
        catch ( ComException e )
        {
            throw new ToolFailureException( "Couldn't connect to '" + hostnamePort + "'", e );
        }
    }

    BackupOutcome executeBackup( HostnamePort hostnamePort, File to, ConsistencyCheck consistencyCheck,
            Config config, long timeout, boolean forensics ) throws ToolFailureException
    {
        try
        {
            systemOut.println( "Performing backup from '" + hostnamePort + "'" );
            String host = hostnamePort.getHost();
            int port = hostnamePort.getPort();

            BackupOutcome outcome = backupProtocolService.doIncrementalBackupOrFallbackToFull( host, port, to, consistencyCheck, config, timeout, forensics );
            systemOut.println( "Done" );
            return outcome;
        }
        catch ( UnexpectedStoreVersionException e )
        {
            throw new ToolFailureException( e.getMessage(), e );
        }
        catch ( MismatchingStoreIdException e )
        {
            throw new ToolFailureException( String.format( MISMATCHED_STORE_ID, e.getExpected(), e.getEncountered() ) );
        }
        catch ( ComException e )
        {
            throw new ToolFailureException( "Couldn't connect to '" + hostnamePort + "'", e );
        }
        catch ( IncrementalBackupNotPossibleException e )
        {
            throw new ToolFailureException( e.getMessage(), e );
        }
    }

Merge Catch [catch(UnexpectedStoreVersionException e), catch(IncrementalBackupNotPossibleException e)] to catch(UnexpectedStoreVersionException|IncrementalBackupNotPossibleException e) in method package executeBackup(hostnamePort HostnamePort, to Path, consistencyCheck ConsistencyCheck, config Config, timeout long, forensics boolean) : BackupOutcome from class org.neo4j.backup.BackupTool


    @Override
    public void delete()
    {
        try ( Statement ignore = actions.statement() )
        {
            boolean deleted = actions.kernelTransaction().dataWrite().nodeDelete( getId() );
            if ( !deleted )
            {
                throw new NotFoundException( "Unable to delete Node[" + nodeId +
                                             "] since it has already been deleted." );
            }
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( AutoIndexingKernelException e )
        {
            throw new IllegalStateException( "Auto indexing encountered a failure while deleting the node: "
                                             + e.getMessage(), e );
        }
    }

    @Override
    public void delete()
    {
        try
        {
            boolean deleted = actions.kernelTransaction().dataWrite().nodeDelete( getId() );
            if ( !deleted )
            {
                throw new NotFoundException( "Unable to delete Node[" + nodeId +
                                             "] since it has already been deleted." );
            }
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
        catch ( AutoIndexingKernelException e )
        {
            throw new IllegalStateException( "Auto indexing encountered a failure while deleting the node: "
                                             + e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=actions.statement()) in method public delete() : void from class org.neo4j.kernel.impl.core.NodeProxy


    @Override
    public Node createNode()
    {
        try ( Statement ignore = spi.currentStatement() )
        {
            return new NodeProxy( nodeActions, spi.currentTransaction().dataWrite().nodeCreate() );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public Node createNode()
    {
        try
        {
            return new NodeProxy( nodeActions, spi.currentTransaction().dataWrite().nodeCreate() );
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=spi.currentStatement()) in method public createNode() : Node from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    @Override
    public Long createNodeId()
    {
        try ( Statement ignore = spi.currentStatement() )
        {
            return spi.currentTransaction().dataWrite().nodeCreate();
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

    @Override
    public Long createNodeId()
    {
        try
        {
            return spi.currentTransaction().dataWrite().nodeCreate();
        }
        catch ( InvalidTransactionTypeKernelException e )
        {
            throw new ConstraintViolationException( e.getMessage(), e );
        }
    }

Try With Resources try(Statement ignore=spi.currentStatement()) in method public createNodeId() : Long from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    @Override
    public Object getProperty( String key ) throws NotFoundException
    {
        if ( null == key )
        {
            throw new IllegalArgumentException( "(null) property key is not allowed" );
        }
        KernelTransaction transaction = actions.kernelTransaction();
        CursorFactory cursors = transaction.cursors();
        try ( NodeCursor nodes = cursors.allocateNodeCursor();
              PropertyCursor properties = cursors.allocatePropertyCursor()
        )
        {
            int propertyKey = transaction.token().propertyKey( key );
            if ( propertyKey == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                throw new NotFoundException( format( "No such property, '%s'.", key ) );
            }
            transaction.dataRead().singleNode( nodeId, nodes );
            if ( !nodes.next() )
            {
                throw new NotFoundException( new EntityNotFoundException( EntityType.NODE, nodeId ) );
            }
            nodes.properties( properties );
            while ( properties.next() )
            {
                if ( propertyKey == properties.propertyKey()  )
                {
                    Value value = properties.propertyValue();
                    if ( value == Values.NO_VALUE )
                    {
                        throw new NotFoundException( format( "No such property, '%s'.", key ) );
                    }
                    return value.asObjectCopy();
                }
            }
            throw new NotFoundException( format( "No such property, '%s'.", key ) );
        }
    }

    @Override
    public Object getProperty( String key ) throws NotFoundException
    {
        if ( null == key )
        {
            throw new IllegalArgumentException( "(null) property key is not allowed" );
        }

        try ( Statement statement = actions.statement() )
        {
            try
            {
                int propertyKeyId = statement.readOperations().propertyKeyGetForName( key );
                if ( propertyKeyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
                {
                    throw new NotFoundException( format( "No such property, '%s'.", key ) );
                }

                Value value = statement.readOperations().nodeGetProperty( nodeId, propertyKeyId );

                if ( value == Values.NO_VALUE )
                {
                    throw new PropertyNotFoundException( propertyKeyId, EntityType.NODE, nodeId );
                }

                return value.asObjectCopy();

            }
            catch ( EntityNotFoundException | PropertyNotFoundException e )
            {
                throw new NotFoundException(
                        e.getUserMessage( new StatementTokenNameLookup( statement.readOperations() ) ), e );
            }
        }
    }

Try With Resources try(NodeCursor nodes=cursors.allocateNodeCursor(); PropertyCursor properties=cursors.allocatePropertyCursor()) in method public getProperty(key String) : Object from class org.neo4j.kernel.impl.core.NodeProxy


    @Override
    public void startAutoIndexingProperty( String propName )
    {
        propertyKeysToInclude.getAndUpdate( current ->
        {
            Set<String> updated = new HashSet<>();
            updated.addAll( current );
            updated.add( propName );
            return updated;
        });
    }

    @Override
    public void startAutoIndexingProperty( String propName )
    {
        propertyKeysToInclude.getAndUpdate( current ->
        {
            Set<String> updated = new HashSet<String>();
            updated.addAll( current );
            updated.add( propName );
            return updated;
        });
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public startAutoIndexingProperty(propName String) : void from class org.neo4j.kernel.impl.api.explicitindex.InternalAutoIndexOperations


    @Override
    public void stopAutoIndexingProperty( String propName )
    {
        propertyKeysToInclude.getAndUpdate( current ->
        {
            Set<String> updated = new HashSet<>();
            updated.addAll( current );
            updated.remove( propName );
            return updated;
        });
    }

    @Override
    public void stopAutoIndexingProperty( String propName )
    {
        propertyKeysToInclude.getAndUpdate( current ->
        {
            Set<String> updated = new HashSet<String>();
            updated.addAll( current );
            updated.remove( propName );
            return updated;
        });
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public stopAutoIndexingProperty(propName String) : void from class org.neo4j.kernel.impl.api.explicitindex.InternalAutoIndexOperations


    @Test
    public void requestForSecondUpdaterMustThrow() throws Exception
    {
        // given
        try ( IndexUpdater ignored = accessor.newUpdater( ONLINE ) )
        {
            // then
            expected.expect( IllegalStateException.class );

            // when
            accessor.newUpdater( ONLINE );
        }
    }

    @Test
    public void requestForSecondUpdaterMustThrow() throws Exception
    {
        // given
        try ( IndexUpdater ignored = accessor.newUpdater( ONLINE ) )
        {
            // when
            try
            {
                accessor.newUpdater( ONLINE );
                fail( "Should have failed" );
            }
            catch ( IllegalStateException e )
            {
                // then good
            }
        }
    }

Try With Resources try(IndexUpdater ignored=accessor.newUpdater(ONLINE)) in method public requestForSecondUpdaterMustThrow() : void from class org.neo4j.kernel.impl.index.schema.NativeSchemaNumberIndexAccessorTest


        @Override
        public Iterator<DataFactory<ENTITY>> iterator()
        {
            return Iterators.iterator( config -> new Data<ENTITY>()
            {
                @Override
                public CharReadable stream()
                {
                    return last = factory.apply( config );
                }

                @Override
                public Decorator<ENTITY> decorator()
                {
                    return decorator;
                }
            } );
        }

        @Override
        public Iterator<DataFactory<ENTITY>> iterator()
        {
            return Iterators.iterator( new DataFactory<ENTITY>()
            {
                @Override
                public Data<ENTITY> create( Configuration config )
                {
                    return new Data<ENTITY>()
                    {

                        @Override
                        public CharReadable stream()
                        {
                            return last = factory.apply( config );
                        }

                        @Override
                        public Decorator<ENTITY> decorator()
                        {
                            return decorator;
                        }
                    };
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.input.csv.CsvInputTest.CapturingDataFactories.iterator.iterator.new DataFactory<ENTITY> with config -> new Data<ENTITY>(){ in method public iterator() : Iterator<DataFactory<ENTITY>> from class org.neo4j.unsafe.impl.batchimport.input.csv.CsvInputTest.CapturingDataFactories


    FulltextIndexConfiguration( Document doc )
    {
        properties = new HashSet<>( Arrays.asList( doc.getValues( FIELD_CONFIG_PROPERTIES ) ) );
        analyzerClassName = doc.get( FIELD_CONFIG_ANALYZER );
    }

    FulltextIndexConfiguration( Document doc )
    {
        properties = new HashSet<String>( Arrays.asList( doc.getValues( FIELD_CONFIG_PROPERTIES ) ) );
        analyzerClassName = doc.get( FIELD_CONFIG_ANALYZER );
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method package FulltextIndexConfiguration(doc Document) from class org.neo4j.kernel.api.impl.fulltext.FulltextIndexConfiguration


    @Description( "List all labels in the database." )
    @Procedure( name = "db.labels", mode = READ )
    public Stream<LabelResult> listLabels()
    {
        try ( Statement statement = tx.acquireStatement() )
        {
            // Ownership of the reference to the acquired statement is transfered to the returned iterator stream,
            // but we still want to eagerly consume the labels, so we can catch any exceptions,
            List<LabelResult> labelResults = asList( TokenAccess.LABELS.inUse( statement ).map( LabelResult::new ) );
            return labelResults.stream();
        }
    }

    @Description( "List all labels in the database." )
    @Procedure( name = "db.labels", mode = READ )
    public Stream<LabelResult> listLabels()
    {
        Statement statement = tx.acquireStatement();
        try
        {
            // Ownership of the reference to the acquired statement is transfered to the returned iterator stream,
            // but we still want to eagerly consume the labels, so we can catch any exceptions,
            List<LabelResult> labelResults = asList( TokenAccess.LABELS.inUse( statement ).map( LabelResult::new ) );
            return labelResults.stream();
        }
        catch ( Throwable t )
        {
            statement.close();
            throw t;
        }
    }

Try With Resources try(Statement statement=tx.acquireStatement()) in method public listLabels() : Stream<LabelResult> from class org.neo4j.kernel.builtinprocs.BuiltInProcedures


    @Description( "List all property keys in the database." )
    @Procedure( name = "db.propertyKeys", mode = READ )
    public Stream<PropertyKeyResult> listPropertyKeys()
    {
        try ( Statement statement = tx.acquireStatement() )
        {
            // Ownership of the reference to the acquired statement is transfered to the returned iterator stream,
            // but we still want to eagerly consume the labels, so we can catch any exceptions,
            List<PropertyKeyResult> propertyKeys =
                    asList( TokenAccess.PROPERTY_KEYS.inUse( statement ).map( PropertyKeyResult::new ) );
            statement.close();
            return propertyKeys.stream();
        }
    }

    @Description( "List all property keys in the database." )
    @Procedure( name = "db.propertyKeys", mode = READ )
    public Stream<PropertyKeyResult> listPropertyKeys()
    {
        Statement statement = tx.acquireStatement();
        try
        {
            // Ownership of the reference to the acquired statement is transfered to the returned iterator stream,
            // but we still want to eagerly consume the labels, so we can catch any exceptions,
            List<PropertyKeyResult> propertyKeys =
                    asList( TokenAccess.PROPERTY_KEYS.inUse( statement ).map( PropertyKeyResult::new ) );
            return propertyKeys.stream();
        }
        catch ( Throwable t )
        {
            statement.close();
            throw t;
        }
    }

Try With Resources try(Statement statement=tx.acquireStatement()) in method public listPropertyKeys() : Stream<PropertyKeyResult> from class org.neo4j.kernel.builtinprocs.BuiltInProcedures


    @Description( "List all relationship types in the database." )
    @Procedure( name = "db.relationshipTypes", mode = READ )
    public Stream<RelationshipTypeResult> listRelationshipTypes()
    {
        try ( Statement statement = tx.acquireStatement() )
        {
            // Ownership of the reference to the acquired statement is transfered to the returned iterator stream,
            // but we still want to eagerly consume the labels, so we can catch any exceptions,
            List<RelationshipTypeResult> relationshipTypes =
                    asList( TokenAccess.RELATIONSHIP_TYPES.inUse( statement ).map( RelationshipTypeResult::new ) );
            return relationshipTypes.stream();
        }
    }

    @Description( "List all relationship types in the database." )
    @Procedure( name = "db.relationshipTypes", mode = READ )
    public Stream<RelationshipTypeResult> listRelationshipTypes()
    {
        Statement statement = tx.acquireStatement();
        try
        {
            // Ownership of the reference to the acquired statement is transfered to the returned iterator stream,
            // but we still want to eagerly consume the labels, so we can catch any exceptions,
            List<RelationshipTypeResult> relationshipTypes =
                    asList( TokenAccess.RELATIONSHIP_TYPES.inUse( statement ).map( RelationshipTypeResult::new ) );
            return relationshipTypes.stream();
        }
        catch ( Throwable t )
        {
            statement.close();
            throw t;
        }
    }

Try With Resources try(Statement statement=tx.acquireStatement()) in method public listRelationshipTypes() : Stream<RelationshipTypeResult> from class org.neo4j.kernel.builtinprocs.BuiltInProcedures


    @Test
    public void shouldNotAddConstraintAlreadyExistsInTheStore() throws Exception
    {
        // given
        UniquenessConstraintDescriptor constraint = ConstraintDescriptorFactory.uniqueForSchema( descriptor );
        TransactionState txState = mock( TransactionState.class );
        when( txState.nodesWithLabelChanged( anyInt() ) ).thenReturn( new DiffSets<>() );
        when( txState.hasChanges() ).thenReturn( true );
        KernelStatement state = mockedState( txState );
        when( inner.constraintsGetForSchema( any() ) ).thenReturn( iterator( constraint ) );
        StateHandlingStatementOperations context = newTxStateOps( inner );

        // when
        context.uniquePropertyConstraintCreate( state, descriptor );

        // then
        verify( txState ).indexDoUnRemove( eq( constraint.ownedIndexDescriptor() ) );
    }

    @Test
    public void shouldNotAddConstraintAlreadyExistsInTheStore() throws Exception
    {
        // given
        UniquenessConstraintDescriptor constraint = ConstraintDescriptorFactory.uniqueForSchema( descriptor );
        TransactionState txState = mock( TransactionState.class );
        when( txState.nodesWithLabelChanged( anyInt() ) ).thenReturn( new DiffSets<Long>() );
        when( txState.hasChanges() ).thenReturn( true );
        KernelStatement state = mockedState( txState );
        when( inner.constraintsGetForSchema( any() ) ).thenReturn( iterator( constraint ) );
        StateHandlingStatementOperations context = newTxStateOps( inner );

        // when
        context.uniquePropertyConstraintCreate( state, descriptor );

        // then
        verify( txState ).indexDoUnRemove( eq( constraint.ownedIndexDescriptor() ) );
    }

Replace Generic With Diamond DiffSets<Long> with DiffSets<> in method public shouldNotAddConstraintAlreadyExistsInTheStore() : void from class org.neo4j.kernel.impl.api.state.StateHandlingStatementOperationsTest


        @Override
        public Map<String,Object> getAllProperties()
        {
            return new HashMap<>();
        }

        @Override
        public Map<String,Object> getAllProperties()
        {
            return new HashMap<String,Object>();
        }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public getAllProperties() : Map<String,Object> from class org.neo4j.kernel.builtinprocs.SchemaProcedure.VirtualRelationshipHack


    @Override
    public void init()
    {
        this.filesystemFacade = config.get( Configuration.ephemeral ) ? LuceneFilesystemFacade.MEMORY
                : LuceneFilesystemFacade.FS;
        readOnly = isReadOnly( config, operationalMode );
        indexSearchers = new IndexClockCache( config.get( Configuration.lucene_searcher_cache_size ) );
        this.baseStorePath = this.filesystemFacade.ensureDirectoryExists( fileSystemAbstraction,
                getLuceneIndexStoreDirectory( storeDir ) );
        this.filesystemFacade.cleanWriteLocks( baseStorePath );
        this.typeCache = new IndexTypeCache( indexStore );
        this.indexReferenceFactory = readOnly ?
                                     new ReadOnlyIndexReferenceFactory( filesystemFacade, baseStorePath, typeCache ) :
                                     new WritableIndexReferenceFactory( filesystemFacade, baseStorePath, typeCache );
        this.indexTypeMap = new ConcurrentHashMap<>();
        closed = false;
    }

    @Override
    public void init()
    {
        this.filesystemFacade = config.get( Configuration.ephemeral ) ? LuceneFilesystemFacade.MEMORY
                : LuceneFilesystemFacade.FS;
        readOnly = isReadOnly( config, operationalMode );
        indexSearchers = new IndexClockCache( config.get( Configuration.lucene_searcher_cache_size ) );
        this.baseStorePath = this.filesystemFacade.ensureDirectoryExists( fileSystemAbstraction,
                getLuceneIndexStoreDirectory( storeDir ) );
        this.filesystemFacade.cleanWriteLocks( baseStorePath );
        this.typeCache = new IndexTypeCache( indexStore );
        this.indexReferenceFactory = readOnly ?
                                     new ReadOnlyIndexReferenceFactory( filesystemFacade, baseStorePath, typeCache ) :
                                     new WritableIndexReferenceFactory( filesystemFacade, baseStorePath, typeCache );
        this.indexTypeMap = new HashMap<IndexIdentifier,Map<String,DocValuesType>>();
        closed = false;
    }

Replace Generic With Diamond HashMap<IndexIdentifier,Map<String,DocValuesType>> with ConcurrentHashMap<> in method public init() : void from class org.neo4j.index.impl.lucene.legacy.LuceneDataSource


    private ThrowingFunction<LogPosition,TransactionCursor,IOException> log( int... transactionCounts ) throws IOException
    {
        long baseOffset = LogPosition.start( 0 ).getByteOffset();

        @SuppressWarnings( "unchecked" )
        ThrowingFunction<LogPosition,TransactionCursor,IOException> result = mock( ThrowingFunction.class );
        AtomicLong txId = new AtomicLong( 0 );
        CommittedTransactionRepresentation[][] logs = new CommittedTransactionRepresentation[transactionCounts.length][];
        for ( int logVersion = 0; logVersion < transactionCounts.length; logVersion++ )
        {
            logs[logVersion] = transactions( transactionCounts[logVersion], txId );
        }

        when( result.apply( any( LogPosition.class ) ) ).thenAnswer( invocation ->
        {
            LogPosition position = invocation.getArgumentAt( 0, LogPosition.class );
            if ( position == null )
            {
                // A mockito issue when calling the "when" methods, I believe
                return null;
            }

            // For simplicity the offset means, in this test, the array offset
            CommittedTransactionRepresentation[] transactions = logs[toIntExact( position.getLogVersion() )];
            CommittedTransactionRepresentation[] subset =
                    copyOfRange( transactions, toIntExact( position.getByteOffset() - baseOffset ), transactions.length );
            ArrayUtil.reverse( subset );
            return given( subset );
        } );
        return result;
    }

    private ThrowingFunction<LogPosition,TransactionCursor,IOException> log( int... transactionCounts ) throws IOException
    {
        long baseOffset = LogPosition.start( 0 ).getByteOffset();

        @SuppressWarnings( "unchecked" )
        ThrowingFunction<LogPosition,TransactionCursor,IOException> result = mock( ThrowingFunction.class );
        AtomicLong txId = new AtomicLong( 0 );
        CommittedTransactionRepresentation[][] logs = new CommittedTransactionRepresentation[transactionCounts.length][];
        for ( int logVersion = 0; logVersion < transactionCounts.length; logVersion++ )
        {
            logs[logVersion] = transactions( transactionCounts[logVersion], txId );
        }

        when( result.apply( any( LogPosition.class ) ) ).thenAnswer( new Answer<TransactionCursor>()
        {
            @Override
            public TransactionCursor answer( InvocationOnMock invocation ) throws Throwable
            {
                LogPosition position = invocation.getArgumentAt( 0, LogPosition.class );
                if ( position == null )
                {
                    // A mockito issue when calling the "when" methods, I believe
                    return null;
                }

                // For simplicity the offset means, in this test, the array offset
                CommittedTransactionRepresentation[] transactions = logs[toIntExact( position.getLogVersion() )];
                CommittedTransactionRepresentation[] subset =
                        copyOfRange( transactions, toIntExact( position.getByteOffset() - baseOffset ), transactions.length );
                ArrayUtil.reverse( subset );
                return given( subset );
            }
        } );
        return result;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.ReversedMultiFileTransactionCursorTest.log.thenAnswer.new Answer<TransactionCursor> with invocation -> {LogPosition position=invocation.getArgumentAt(0,LogPosition.class); in method private log(transactionCounts int...) : ThrowingFunction<LogPosition,TransactionCursor,IOException> from class org.neo4j.kernel.impl.transaction.log.ReversedMultiFileTransactionCursorTest


    private void testYoyoArrayBase( boolean withNewTx )
    {
        Relationship rel = getGraphDb().createNode().createRelationshipTo( getGraphDb().createNode(),
                RelationshipType.withName( "LOCKS" ) );

        long recordsInUseAtStart = propertyRecordsInUse();
        long valueRecordsInUseAtStart = dynamicArrayRecordsInUse();

        List<Long> theYoyoData = new ArrayList<>();
        for ( int i = 0; i < PropertyType.getPayloadSizeLongs() - 1; i++ )
        {
            theYoyoData.add( 1L << 63 );
            Long[] value = theYoyoData.toArray( new Long[] {} );
            rel.setProperty( "yoyo", value );
            if ( withNewTx )
            {
                newTransaction();
                assertEquals( recordsInUseAtStart + 1, propertyRecordsInUse() );
                assertEquals( valueRecordsInUseAtStart, dynamicArrayRecordsInUse() );
            }
        }

        theYoyoData.add( 1L << 63 );
        Long[] value = theYoyoData.toArray( new Long[] {} );
        rel.setProperty( "yoyo", value );

        newTransaction();
        assertEquals( recordsInUseAtStart + 1, propertyRecordsInUse() );
        assertEquals( valueRecordsInUseAtStart + 1, dynamicArrayRecordsInUse() );
        rel.setProperty( "filler", new long[] { 1 << 63, 1 << 63, 1 << 63 } );
        newTransaction();
        assertEquals( recordsInUseAtStart + 2, propertyRecordsInUse() );
    }

    private void testYoyoArrayBase( boolean withNewTx )
    {
        Relationship rel = getGraphDb().createNode().createRelationshipTo( getGraphDb().createNode(),
                RelationshipType.withName( "LOCKS" ) );

        long recordsInUseAtStart = propertyRecordsInUse();
        long valueRecordsInUseAtStart = dynamicArrayRecordsInUse();

        List<Long> theYoyoData = new ArrayList<Long>();
        for ( int i = 0; i < PropertyType.getPayloadSizeLongs() - 1; i++ )
        {
            theYoyoData.add( 1L << 63 );
            Long[] value = theYoyoData.toArray( new Long[] {} );
            rel.setProperty( "yoyo", value );
            if ( withNewTx )
            {
                newTransaction();
                assertEquals( recordsInUseAtStart + 1, propertyRecordsInUse() );
                assertEquals( valueRecordsInUseAtStart, dynamicArrayRecordsInUse() );
            }
        }

        theYoyoData.add( 1L << 63 );
        Long[] value = theYoyoData.toArray( new Long[] {} );
        rel.setProperty( "yoyo", value );

        newTransaction();
        assertEquals( recordsInUseAtStart + 1, propertyRecordsInUse() );
        assertEquals( valueRecordsInUseAtStart + 1, dynamicArrayRecordsInUse() );
        rel.setProperty( "filler", new long[] { 1 << 63, 1 << 63, 1 << 63 } );
        newTransaction();
        assertEquals( recordsInUseAtStart + 2, propertyRecordsInUse() );
    }

Replace Generic With Diamond ArrayList<Long> with ArrayList<> in method private testYoyoArrayBase(withNewTx boolean) : void from class org.neo4j.kernel.impl.store.TestPropertyBlocks


    @Test
    public void shouldRemoveRelationProperties() throws Exception
    {
        long relId = graphdbHelper.createRelationship( "PAIR-PROGRAMS_WITH" );
        Map<String, Object> map = new HashMap<>();
        map.put( "foo", "bar" );
        map.put( "baz", 22 );
        graphdbHelper.setRelationshipProperties( relId, map );

        actions.removeAllRelationshipProperties( relId );

        assertTrue( graphdbHelper.getRelationshipProperties( relId )
                .isEmpty() );
    }

    @Test
    public void shouldRemoveRelationProperties() throws Exception
    {
        long relId = graphdbHelper.createRelationship( "PAIR-PROGRAMS_WITH" );
        Map<String, Object> map = new HashMap<String, Object>();
        map.put( "foo", "bar" );
        map.put( "baz", 22 );
        graphdbHelper.setRelationshipProperties( relId, map );

        actions.removeAllRelationshipProperties( relId );

        assertTrue( graphdbHelper.getRelationshipProperties( relId )
                .isEmpty() );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public shouldRemoveRelationProperties() : void from class org.neo4j.server.rest.web.DatabaseActionsTest


    @Test
    public void shouldRemoveRelationshipProperty() throws Exception
    {
        long relId = graphdbHelper.createRelationship( "PAIR-PROGRAMS_WITH" );
        Map<String, Object> map = new HashMap<>();
        map.put( "foo", "bar" );
        map.put( "baz", 22 );
        graphdbHelper.setRelationshipProperties( relId, map );

        actions.removeRelationshipProperty( relId, "foo" );
        assertEquals( 1, graphdbHelper.getRelationshipProperties( relId )
                .size() );
    }

    @Test
    public void shouldRemoveRelationshipProperty() throws Exception
    {
        long relId = graphdbHelper.createRelationship( "PAIR-PROGRAMS_WITH" );
        Map<String, Object> map = new HashMap<String, Object>();
        map.put( "foo", "bar" );
        map.put( "baz", 22 );
        graphdbHelper.setRelationshipProperties( relId, map );

        actions.removeRelationshipProperty( relId, "foo" );
        assertEquals( 1, graphdbHelper.getRelationshipProperties( relId )
                .size() );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public shouldRemoveRelationshipProperty() : void from class org.neo4j.server.rest.web.DatabaseActionsTest


    @Test
    public void shouldAddLabelToNode() throws Exception
    {
        // GIVEN
        long node = actions.createNode( null ).getId();
        Collection<String> labels = new ArrayList<>();
        String labelName = "Wonk";
        labels.add( labelName );

        // WHEN
        actions.addLabelToNode( node, labels );

        // THEN
        try ( Transaction transaction = graph.beginTx() )
        {
            Iterable<String> result = graphdbHelper.getNodeLabels( node );
            assertEquals( labelName, single( result ) );
        }
    }

    @Test
    public void shouldAddLabelToNode() throws Exception
    {
        // GIVEN
        long node = actions.createNode( null ).getId();
        Collection<String> labels = new ArrayList<String>();
        String labelName = "Wonk";
        labels.add( labelName );

        // WHEN
        actions.addLabelToNode( node, labels );

        // THEN
        try ( Transaction transaction = graph.beginTx() )
        {
            Iterable<String> result = graphdbHelper.getNodeLabels( node );
            assertEquals( labelName, single( result ) );
        }
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public shouldAddLabelToNode() : void from class org.neo4j.server.rest.web.DatabaseActionsTest


    public static <T> IterableMatcher<T> matchesIterable( Iterable<T> toMatch )
    {
        return new IterableMatcher<>( toMatch );
    }

    public static <T> IterableMatcher<T> matchesIterable( Iterable<T> toMatch )
    {
        return new IterableMatcher<T>( toMatch );
    }

Replace Generic With Diamond IterableMatcher<T> with IterableMatcher<> in method public matchesIterable(toMatch Iterable<T>) : IterableMatcher<T> from class org.neo4j.test.mockito.matcher.IterableMatcher


    @Test
    public void updaterShouldThrowOnDuplicateValues() throws Exception
    {
        // given
        populator.create();
        IndexEntryUpdate<IndexDescriptor>[] updates = layoutUtil.someUpdatesWithDuplicateValues();
        try ( IndexUpdater updater = populator.newPopulatingUpdater( null_property_accessor ) )
        {
            // when
            for ( IndexEntryUpdate<IndexDescriptor> update : updates )
            {
                updater.process( update );
            }
            fail( "Updates should have conflicted" );
        }
        catch ( IndexEntryConflictException e )
        {
            // then good
        }

        populator.close( true );
    }

    @Test
    public void updaterShouldThrowOnDuplicateValues() throws Exception
    {
        // given
        populator.create();
        IndexEntryUpdate<IndexDescriptor>[] updates = layoutUtil.someUpdatesWithDuplicateValues();
        IndexUpdater updater = populator.newPopulatingUpdater( null_property_accessor );

        // when
        for ( IndexEntryUpdate<IndexDescriptor> update : updates )
        {
            updater.process( update );
        }
        try
        {
            updater.close();
            fail( "Updates should have conflicted" );
        }
        catch ( Throwable e )
        {
            // then
            assertTrue( e.getMessage(), Exceptions.contains( e, IndexEntryConflictException.class ) );
        }
        finally
        {
            populator.close( true );
        }
    }

Try With Resources try(IndexUpdater updater=populator.newPopulatingUpdater(null_property_accessor)) in method public updaterShouldThrowOnDuplicateValues() : void from class org.neo4j.kernel.impl.index.schema.NativeUniqueSchemaNumberIndexPopulatorTest


    @Test
    public void shouldGiveNiceMessageAtFailWhenTryingToKill() throws Throwable
    {
        String query = "CALL dbms.killQuery('query-9999999999')";
        Map<String,String> expected = new HashMap<>();
        expected.put( "queryId",  "query-9999999999" );
        expected.put( "username",  "n/a" );
        expected.put( "message",  "No Query found with this id" );
        assertSuccess( adminSubject, query, r -> assertThat(r.next(), equalTo( expected )));
    }

    @Test
    public void shouldGiveNiceMessageAtFailWhenTryingToKill() throws Throwable
    {
        String query = "CALL dbms.killQuery('query-9999999999')";
        Map<String,String> expected = new HashMap<String,String>();
        expected.put( "queryId",  "query-9999999999" );
        expected.put( "username",  "n/a" );
        expected.put( "message",  "No Query found with this id" );
        assertSuccess( adminSubject, query, r -> assertThat(r.next(), equalTo( expected )));
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public shouldGiveNiceMessageAtFailWhenTryingToKill() : void from class org.neo4j.server.security.enterprise.auth.BuiltInProceduresInteractionTestBase


    private Map<String, Object> toMap( Object[] keyValuePairs )
    {
        Map<String, Object> map = new HashMap<>();
        for ( int i = 0; i < keyValuePairs.length; i++ )
        {
            map.put( keyValuePairs[i++].toString(), keyValuePairs[i] );
        }
        return map;
    }

    private Map<String, Object> toMap( Object[] keyValuePairs )
    {
        Map<String, Object> map = new HashMap<String, Object>();
        for ( int i = 0; i < keyValuePairs.length; i++ )
        {
            map.put( keyValuePairs[i++].toString(), keyValuePairs[i] );
        }
        return map;
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method private toMap(keyValuePairs Object[]) : Map<String,Object> from class common.SimpleGraphBuilder


        @Override
        public StandardExpander remove( RelationshipType type )
        {
            Map<String, Exclusion> exclude = new HashMap<>();
            exclude.put( type.name(), Exclusion.ALL );
            return new ExcludingExpander( Exclusion.include( direction ), exclude );
        }

        @Override
        public StandardExpander remove( RelationshipType type )
        {
            Map<String, Exclusion> exclude = new HashMap<String, Exclusion>();
            exclude.put( type.name(), Exclusion.ALL );
            return new ExcludingExpander( Exclusion.include( direction ), exclude );
        }

Replace Generic With Diamond HashMap<String,Exclusion> with HashMap<> in method public remove(type RelationshipType) : StandardExpander from class org.neo4j.graphdb.impl.StandardExpander.AllExpander


        @Override
        public StandardExpander remove( RelationshipType type )
        {
            Exclusion excluded = exclusion.get( type.name() );
            if ( excluded == Exclusion.ALL )
            {
                return this;
            }
            Map<String, Exclusion> newExclusion = new HashMap<>( exclusion );
            newExclusion.put( type.name(), Exclusion.ALL );
            return new ExcludingExpander( defaultExclusion, newExclusion );
        }

        @Override
        public StandardExpander remove( RelationshipType type )
        {
            Exclusion excluded = exclusion.get( type.name() );
            if ( excluded == Exclusion.ALL )
            {
                return this;
            }
            Map<String, Exclusion> newExclusion = new HashMap<String, Exclusion>(
                    exclusion );
            newExclusion.put( type.name(), Exclusion.ALL );
            return new ExcludingExpander( defaultExclusion, newExclusion );
        }

Replace Generic With Diamond HashMap<String,Exclusion> with HashMap<> in method public remove(type RelationshipType) : StandardExpander from class org.neo4j.graphdb.impl.StandardExpander.ExcludingExpander


        @Override
        public StandardExpander reverse()
        {
            Map<String, Exclusion> newExclusion = new HashMap<>();
            for ( Map.Entry<String, Exclusion> entry : exclusion.entrySet() )
            {
                newExclusion.put( entry.getKey(), entry.getValue().reversed() );
            }
            return new ExcludingExpander( defaultExclusion.reversed(), newExclusion );
        }

        @Override
        public StandardExpander reverse()
        {
            Map<String, Exclusion> newExclusion = new HashMap<String, Exclusion>();
            for ( Map.Entry<String, Exclusion> entry : exclusion.entrySet() )
            {
                newExclusion.put( entry.getKey(), entry.getValue().reversed() );
            }
            return new ExcludingExpander( defaultExclusion.reversed(), newExclusion );
        }

Replace Generic With Diamond HashMap<String,Exclusion> with HashMap<> in method public reverse() : StandardExpander from class org.neo4j.graphdb.impl.StandardExpander.ExcludingExpander


        @Override
        ResourceIterator<Relationship> doExpand( Path path, BranchState state )
        {
            final Node node = path.endNode();
            if ( directions.length == 1 )
            {
                DirectionAndTypes direction = directions[0];
                return asResourceIterator( node.getRelationships( direction.direction, direction.types ).iterator() );
            }
            else
            {
                return new NestingResourceIterator<Relationship, DirectionAndTypes>( new ArrayIterator<>( directions ) )
                {
                    @Override
                    protected ResourceIterator<Relationship> createNestedIterator( DirectionAndTypes item )
                    {
                        return asResourceIterator( node.getRelationships( item.direction, item.types ).iterator() );
                    }
                };
            }
        }

        @Override
        Iterator<Relationship> doExpand( Path path, BranchState state )
        {
            final Node node = path.endNode();
            if ( directions.length == 1 )
            {
                DirectionAndTypes direction = directions[0];
                return node.getRelationships( direction.direction, direction.types ).iterator();
            }
            else
            {
                return new NestingIterator<Relationship, DirectionAndTypes>( new ArrayIterator<DirectionAndTypes>(
                        directions ) )
                {
                    @Override
                    protected Iterator<Relationship> createNestedIterator( DirectionAndTypes item )
                    {
                        return node.getRelationships( item.direction, item.types ).iterator();
                    }
                };
            }
        }

Replace Generic With Diamond NestingIterator<Relationship,DirectionAndTypes> with NestingResourceIterator<Relationship,DirectionAndTypes> in method package doExpand(path Path, state BranchState) : ResourceIterator<Relationship> from class org.neo4j.graphdb.impl.StandardExpander.RegularExpander


    private static Map<Direction, RelationshipType[]> toTypeMap(
            Map<Direction, Collection<RelationshipType>> tempMap )
    {
        // Remove OUT/IN where there is a BOTH
        Collection<RelationshipType> both = tempMap.get( Direction.BOTH );
        tempMap.get( Direction.OUTGOING ).removeAll( both );
        tempMap.get( Direction.INCOMING ).removeAll( both );

        // Convert into a final map
        Map<Direction, RelationshipType[]> map = new EnumMap<>( Direction.class );
        for ( Map.Entry<Direction, Collection<RelationshipType>> entry : tempMap.entrySet() )
        {
            if ( !entry.getValue().isEmpty() )
            {
                map.put( entry.getKey(), entry.getValue().toArray( new RelationshipType[entry.getValue().size()] ) );
            }
        }
        return map;
    }

    private static Map<Direction, RelationshipType[]> toTypeMap(
            Map<Direction, Collection<RelationshipType>> tempMap )
    {
        // Remove OUT/IN where there is a BOTH
        Collection<RelationshipType> both = tempMap.get( Direction.BOTH );
        tempMap.get( Direction.OUTGOING ).removeAll( both );
        tempMap.get( Direction.INCOMING ).removeAll( both );

        // Convert into a final map
        Map<Direction, RelationshipType[]> map = new EnumMap<Direction, RelationshipType[]>( Direction.class );
        for ( Map.Entry<Direction, Collection<RelationshipType>> entry : tempMap.entrySet() )
        {
            if ( !entry.getValue().isEmpty() )
            {
                map.put( entry.getKey(), entry.getValue().toArray( new RelationshipType[entry.getValue().size()] ) );
            }
        }
        return map;
    }

Replace Generic With Diamond EnumMap<Direction,RelationshipType[]> with EnumMap<> in method private toTypeMap(tempMap Map<Direction,Collection<RelationshipType>>) : Map<Direction,RelationshipType[]> from class org.neo4j.graphdb.impl.StandardExpander


    private static Map<Direction, Collection<RelationshipType>> temporaryTypeMap()
    {
        Map<Direction, Collection<RelationshipType>> map = new EnumMap<>( Direction.class );
        for ( Direction direction : Direction.values() )
        {
            map.put( direction, new ArrayList<>() );
        }
        return map;
    }

    private static Map<Direction, Collection<RelationshipType>> temporaryTypeMap()
    {
        Map<Direction, Collection<RelationshipType>> map = new EnumMap<Direction,
                Collection<RelationshipType>>( Direction.class );
        for ( Direction direction : Direction.values() )
        {
            map.put( direction, new ArrayList<>() );
        }
        return map;
    }

Replace Generic With Diamond EnumMap<Direction,Collection<RelationshipType>> with EnumMap<> in method private temporaryTypeMap() : Map<Direction,Collection<RelationshipType>> from class org.neo4j.graphdb.impl.StandardExpander


    @Test
    public void testHardCoreRecovery() throws Exception
    {
        String path = testDirectory.graphDbDir().getPath();

        Process process = Runtime.getRuntime().exec( new String[]{
                ProcessUtil.getJavaExecutable().toString(), "-cp", ProcessUtil.getClassPath(),
                Inserter.class.getName(), path
        } );

        // Let it run for a while and then kill it, and wait for it to die
        awaitFile( new File( path, "started" ) );
        Thread.sleep( 5000 );
        process.destroy();
        process.waitFor();

        final GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabase( testDirectory.graphDbDir() );
        try ( Transaction transaction = db.beginTx() )
        {
            assertTrue( db.index().existsForNodes( "myIndex" ) );
            Index<Node> index = db.index().forNodes( "myIndex" );
            for ( Node node : db.getAllNodes() )
            {
                for ( String key : node.getPropertyKeys() )
                {
                    String value = (String) node.getProperty( key );
                    boolean found = false;
                    try ( IndexHits<Node> indexHits = index.get( key, value ) )
                    {
                        for ( Node indexedNode : indexHits )
                        {
                            if ( indexedNode.equals( node ) )
                            {
                                found = true;
                                break;
                            }
                        }
                    }
                    if ( !found )
                    {
                        throw new IllegalStateException( node + " has property '" + key + "'='" +
                                value + "', but not in index" );
                    }
                }
            }
        }
        catch ( Throwable e )
        {
            if ( Exceptions.contains( e, CorruptIndexException.class ) ||
                    exceptionContainsStackTraceElementFromPackage( e, "org.apache.lucene" ) )
            {
                // On some machines and during some circumstances a lucene index may become
                // corrupted during a crash. This is out of our control and since this test
                // is about a legacy (a.k.a. manual index) the db cannot just re-populate the
                // index automatically. We have to consider this an OK scenario and we cannot
                // verify the index any further if it happens.
                System.err.println( "Lucene exception happened during recovery after a real crash. " +
                        "It may be that the index is corrupt somehow and this is out of control and not " +
                        "something this test can really improve on right now. Printing the exception for reference" );
                e.printStackTrace();
                return;
            }

            // This was another unknown exception, throw it so that the test fails with it
            throw e;
        }

        // Added due to a recovery issue where the lucene data source write wasn't released properly after recovery.
        Thread t = new Thread( () ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                Index<Node> index = db.index().forNodes( "myIndex" );
                index.add( db.createNode(), "one", "two" );
                tx.success();
            }
        } );
        t.start();
        t.join();

        db.shutdown();
    }

    @Test
    public void testHardCoreRecovery() throws Exception
    {
        String path = "target/hcdb";
        File hcdb = new File( path );
        FileUtils.deleteRecursively( hcdb );

        Process process = Runtime.getRuntime().exec( new String[]{
                ProcessUtil.getJavaExecutable().toString(), "-cp", ProcessUtil.getClassPath(),
                Inserter.class.getName(), path
        } );

        // Let it run for a while and then kill it, and wait for it to die
        awaitFile( new File( path, "started" ) );
        Thread.sleep( 5000 );
        process.destroy();
        process.waitFor();

        final GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabase( hcdb );
        try ( Transaction transaction = db.beginTx() )
        {
            assertTrue( db.index().existsForNodes( "myIndex" ) );
            Index<Node> index = db.index().forNodes( "myIndex" );
            for ( Node node : db.getAllNodes() )
            {
                for ( String key : node.getPropertyKeys() )
                {
                    String value = (String) node.getProperty( key );
                    boolean found = false;
                    for ( Node indexedNode : index.get( key, value ) )
                    {
                        if ( indexedNode.equals( node ) )
                        {
                            found = true;
                            break;
                        }
                    }
                    if ( !found )
                    {
                        throw new IllegalStateException( node + " has property '" + key + "'='" +
                                value + "', but not in index" );
                    }
                }
            }
        }
        catch ( Throwable e )
        {
            if ( Exceptions.contains( e, CorruptIndexException.class ) ||
                    exceptionContainsStackTraceElementFromPackage( e, "org.apache.lucene" ) )
            {
                // On some machines and during some circumstances a lucene index may become
                // corrupted during a crash. This is out of our control and since this test
                // is about a legacy (a.k.a. manual index) the db cannot just re-populate the
                // index automatically. We have to consider this an OK scenario and we cannot
                // verify the index any further if it happens.
                System.err.println( "Lucene exception happened during recovery after a real crash. " +
                        "It may be that the index is corrupt somehow and this is out of control and not " +
                        "something this test can reall improve on right now. Printing the exception for reference" );
                e.printStackTrace();
                return;
            }

            // This was another unknown exception, throw it so that the test fails with it
            throw e;
        }

        // Added due to a recovery issue where the lucene data source write wasn't released properly after recovery.
        Thread t = new Thread()
        {
            @Override
            public void run()
            {
                try ( Transaction tx = db.beginTx() )
                {
                    Index<Node> index = db.index().forNodes( "myIndex" );
                    index.add( db.createNode(), "one", "two" );
                    tx.success();
                }
            }
        };
        t.start();
        t.join();

        db.shutdown();
    }

Replace Anonymous With Lambda org.neo4j.index.impl.lucene.legacy.LuceneRecoveryIT.testHardCoreRecovery.t.new Thread with () -> {try(Transaction tx=db.beginTx())Index<Node> index=db.index().forNodes("myIndex"); in method public testHardCoreRecovery() : void from class org.neo4j.index.impl.lucene.legacy.LuceneRecoveryIT


    private Map<K, V> copy()
    {
        return new HashMap<>( actual );
    }

    private Map<K, V> copy()
    {
        return new HashMap<K, V>( actual );
    }

Replace Generic With Diamond HashMap<K,V> with HashMap<> in method private copy() : Map<K,V> from class org.neo4j.kernel.impl.util.CopyOnWriteHashMap


    @Override
    public synchronized void clear()
    {
        actual = new HashMap<>();
    }

    @Override
    public synchronized void clear()
    {
        actual = new HashMap<K, V>();
    }

Replace Generic With Diamond HashMap<K,V> with HashMap<> in method public clear() : void from class org.neo4j.kernel.impl.util.CopyOnWriteHashMap


    private static Map<String,String> config( String desiredId )
    {
        HashMap<String,String> config = new HashMap<>();
        if ( desiredId != null )
        {
            config.put( KernelData.forced_id.name(), desiredId );
        }
        return config;
    }

    private static Map<String,String> config( String desiredId )
    {
        HashMap<String,String> config = new HashMap<String,String>();
        if ( desiredId != null )
        {
            config.put( KernelData.forced_id.name(), desiredId );
        }
        return config;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method private config(desiredId String) : Map<String,String> from class org.neo4j.kernel.internal.KernelDataTest


    @Override
    public void get( long index, byte[] into )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            do
            {
                for ( int i = 0; i < into.length; i++ )
                {
                    into[i] = cursor.getByte( offset + i );
                }
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void get( long index, byte[] into )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            do
            {
                for ( int i = 0; i < into.length; i++ )
                {
                    into[i] = cursor.getByte( offset + i );
                }
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public get(index long, into byte[]) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public byte getByte( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            byte result;
            do
            {
                result = cursor.getByte( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public byte getByte( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            byte result;
            do
            {
                result = cursor.getByte( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public getByte(index long, offset int) : byte from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public short getShort( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            short result;
            do
            {
                result = cursor.getShort( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public short getShort( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            short result;
            do
            {
                result = cursor.getShort( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public getShort(index long, offset int) : short from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public int getInt( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            int result;
            do
            {
                result = cursor.getInt( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public int getInt( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            int result;
            do
            {
                result = cursor.getInt( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public getInt(index long, offset int) : int from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public long get6ByteLong( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            long result;
            do
            {
                long low4b = cursor.getInt( offset ) & 0xFFFFFFFFL;
                long high2b = cursor.getShort( offset + Integer.BYTES );
                result = low4b | (high2b << 32);
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public long get6ByteLong( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            long result;
            do
            {
                long low4b = cursor.getInt( offset ) & 0xFFFFFFFFL;
                long high2b = cursor.getShort( offset + Integer.BYTES );
                result = low4b | (high2b << 32);
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public get6ByteLong(index long, offset int) : long from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public long getLong( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            long result;
            do
            {
                result = cursor.getLong( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public long getLong( long index, int offset )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            long result;
            do
            {
                result = cursor.getLong( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public getLong(index long, offset int) : long from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public void set( long index, byte[] value )
    {
        assert value.length == entrySize;
        long pageId = pageId( index );
        int offset = offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ); )
        {
            cursor.next();
            for ( int i = 0; i < value.length; i++ )
            {
                cursor.putByte( offset + i, value[i] );
            }
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void set( long index, byte[] value )
    {
        assert value.length == entrySize;
        long pageId = pageId( index );
        int offset = offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            for ( int i = 0; i < value.length; i++ )
            {
                cursor.putByte( offset + i, value[i] );
            }
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public set(index long, value byte[]) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public void setByte( long index, int offset, byte value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ); )
        {
            cursor.next();
            cursor.putByte( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void setByte( long index, int offset, byte value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            cursor.putByte( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public setByte(index long, offset int, value byte) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public void setShort( long index, int offset, short value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ); )
        {
            cursor.next();
            cursor.putShort( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void setShort( long index, int offset, short value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            cursor.putShort( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public setShort(index long, offset int, value short) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public void setInt( long index, int offset, int value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ); )
        {
            cursor.next();
            cursor.putInt( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void setInt( long index, int offset, int value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            cursor.putInt( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public setInt(index long, offset int, value int) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public void set6ByteLong( long index, int offset, long value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ); )
        {
            cursor.next();
            cursor.putInt( offset, (int) value );
            cursor.putShort( offset + Integer.BYTES, (short) (value >>> 32) );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void set6ByteLong( long index, int offset, long value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            cursor.putInt( offset, (int) value );
            cursor.putShort( offset + Integer.BYTES, (short) (value >>> 32) );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public set6ByteLong(index long, offset int, value long) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public void setLong( long index, int offset, long value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ); )
        {
            cursor.next();
            cursor.putLong( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void setLong( long index, int offset, long value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            cursor.putLong( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public setLong(index long, offset int, value long) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public int get3ByteInt( long index, int offset )
    {

        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            int result;
            do
            {
                int lowWord = cursor.getShort( offset ) & 0xFFFF;
                byte highByte = cursor.getByte( offset + Short.BYTES );
                result = lowWord | (highByte << Short.SIZE);
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public int get3ByteInt( long index, int offset )
    {

        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            int result;
            do
            {
                int lowWord = cursor.getShort( offset ) & 0xFFFF;
                byte highByte = cursor.getByte( offset + Short.BYTES );
                result = lowWord | (highByte << Short.SIZE);
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public get3ByteInt(index long, offset int) : int from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public void set3ByteInt( long index, int offset, int value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ); )
        {
            cursor.next();
            cursor.putShort( offset, (short) value );
            cursor.putByte( offset + Short.BYTES, (byte) (value >>> Short.SIZE) );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void set3ByteInt( long index, int offset, int value )
    {
        long pageId = pageId( index );
        offset += offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            cursor.putShort( offset, (short) value );
            cursor.putByte( offset + Short.BYTES, (byte) (value >>> Short.SIZE) );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public set3ByteInt(index long, offset int, value int) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheByteArray


    @Override
    public int get( long index )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            int result;
            do
            {
                result = cursor.getInt( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public int get( long index )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            int result;
            do
            {
                result = cursor.getInt( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public get(index long) : int from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheIntArray


    @Override
    public void set( long index, int value )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ); )
        {
            cursor.next();
            cursor.putInt( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void set( long index, int value )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            cursor.putInt( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public set(index long, value int) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheIntArray


    @Override
    public long get( long index )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_READ_LOCK ) )
        {
            cursor.next();
            long result;
            do
            {
                result = cursor.getLong( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public long get( long index )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try
        {
            PageCursor cursor = readCursor( pageId );
            long result;
            do
            {
                result = cursor.getLong( offset );
            }
            while ( cursor.shouldRetry() );
            checkBounds( cursor );
            return result;
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_READ_LOCK)) in method public get(index long) : long from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheLongArray


    @Override
    public void set( long index, long value )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try ( PageCursor cursor = pagedFile.io( pageId, PF_SHARED_WRITE_LOCK | PF_NO_GROW ) )
        {
            cursor.next();
            cursor.putLong( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

    @Override
    public void set( long index, long value )
    {
        long pageId = pageId( index );
        int offset = offset( index );
        try
        {
            PageCursor cursor = writeCursor( pageId );
            cursor.putLong( offset, value );
            checkBounds( cursor );
        }
        catch ( IOException e )
        {
            throw new UncheckedIOException( e );
        }
    }

Try With Resources try(PageCursor cursor=pagedFile.io(pageId,PF_SHARED_WRITE_LOCK | PF_NO_GROW)) in method public set(index long, value long) : void from class org.neo4j.unsafe.impl.batchimport.cache.PageCacheLongArray


    public synchronized int reserveNextPort( String trace )
    {
        // if we do not find one after trying 100 times, bail out
        for ( int i = 0; i < 100; i++ )
        {
            // have OS pick a free port
            try ( ServerSocket serverSocket = new ServerSocket( 0 ) )
            {
                int port = serverSocket.getLocalPort();

                Path portFilePath = directory.resolve( "port" + port );

                Files.createFile( portFilePath );

                try ( FileOutputStream fileOutputStream = new FileOutputStream( portFilePath.toFile(), true ) )
                {
                    fileOutputStream.write( trace.getBytes() );
                    fileOutputStream.flush();
                }

                return port;
            }
            catch ( FileAlreadyExistsException e )
            {
                // try again
            }
            catch ( IOException e )
            {
                throw new IllegalStateException( "This will never happen - LWN", e );
            }
        }

        throw new IllegalStateException( "There are no more ephemeral/ dynamic ports available" );
    }

    public synchronized int reserveNextPort( String trace )
    {
        // if we do not find one after trying 100 times, bail out
        for ( int i = 0; i < 100; i++ )
        {
            int port = lowestPort + RANDOM.nextInt( PortConstants.EphemeralPortMaximum - lowestPort );

            Path portFilePath = directory.resolve( "port" + port );

            try
            {
                Files.createFile( portFilePath );

                try ( FileOutputStream fileOutputStream = new FileOutputStream( portFilePath.toFile(), true ) )
                {
                    fileOutputStream.write( trace.getBytes() );
                    fileOutputStream.flush();
                }

                return port;
            }
            catch ( FileAlreadyExistsException e )
            {
                // try again
            }
            catch ( IOException e )
            {
                throw new IllegalStateException( "This will never happen - LWN", e );
            }
        }

        throw new IllegalStateException( "There are no more ephemeral/ dynamic ports available" );
    }

Try With Resources try(ServerSocket serverSocket=new ServerSocket(0)) in method public reserveNextPort(trace String) : int from class org.neo4j.causalclustering.PortRepository


    NativeSchemaNumberIndexUpdater( KEY treeKey, VALUE treeValue )
    {
        this.treeKey = treeKey;
        this.treeValue = treeValue;
        this.conflictDetectingValueMerger = new ConflictDetectingValueMerger<>();
    }

    NativeSchemaNumberIndexUpdater( KEY treeKey, VALUE treeValue )
    {
        this.treeKey = treeKey;
        this.treeValue = treeValue;
        this.conflictDetectingValueMerger = new ConflictDetectingValueMerger<VALUE>();
    }

Replace Generic With Diamond ConflictDetectingValueMerger<VALUE> with ConflictDetectingValueMerger<> in method package NativeSchemaNumberIndexUpdater(treeKey KEY, treeValue VALUE) from class org.neo4j.kernel.impl.index.schema.NativeSchemaNumberIndexUpdater


    public static byte[] chunk( int maxChunkSize, byte[][] messages ) throws IOException
    {
        final ByteBuffer outputBuffer = ByteBuffer.allocate( 1024 * 8 );

        Channel ch = mock( Channel.class );
        when( ch.alloc() ).thenReturn( UnpooledByteBufAllocator.DEFAULT );
        when( ch.writeAndFlush( any(), any( ChannelPromise.class ) ) ).then( inv ->
        {
            ByteBuf buf = (ByteBuf) inv.getArguments()[0];
            outputBuffer.limit( outputBuffer.position() + buf.readableBytes() );
            buf.readBytes( outputBuffer );
            buf.release();
            return null;
        } );

        ChunkedOutput out = new ChunkedOutput( ch, maxChunkSize + 2 /* for chunk header */ );

        for ( byte[] message : messages )
        {
            out.writeBytes( message, 0, message.length );
            out.onMessageComplete();
        }
        out.flush();
        out.close();

        byte[] bytes = new byte[outputBuffer.limit()];
        outputBuffer.position( 0 );
        outputBuffer.get( bytes );
        return bytes;
    }

    public static byte[] chunk( int maxChunkSize, byte[][] messages ) throws IOException
    {
        final ByteBuffer outputBuffer = ByteBuffer.allocate( 1024 * 8 );

        Channel ch = mock( Channel.class );
        when( ch.alloc() ).thenReturn( UnpooledByteBufAllocator.DEFAULT );
        when( ch.writeAndFlush( any(), any( ChannelPromise.class ) ) ).then( new Answer<Object>()
        {
            @Override
            public Object answer( InvocationOnMock inv ) throws Throwable
            {
                ByteBuf buf = (ByteBuf) inv.getArguments()[0];
                outputBuffer.limit( outputBuffer.position() + buf.readableBytes() );
                buf.readBytes( outputBuffer );
                buf.release();
                return null;
            }
        } );

        ChunkedOutput out = new ChunkedOutput( ch, maxChunkSize + 2 /* for chunk header */ );

        for ( byte[] message : messages )
        {
            out.writeBytes( message, 0, message.length );
            out.onMessageComplete();
        }
        out.flush();
        out.close();

        byte[] bytes = new byte[outputBuffer.limit()];
        outputBuffer.position( 0 );
        outputBuffer.get( bytes );
        return bytes;
    }

Replace Anonymous With Lambda org.neo4j.bolt.v1.transport.socket.Chunker.chunk.then.new Answer<Object> with inv -> {ByteBuf buf=(ByteBuf)inv.getArguments()[0]; in method public chunk(maxChunkSize int, messages byte[][]) : byte[] from class org.neo4j.bolt.v1.transport.socket.Chunker


    @Test( expected = IllegalStateException.class )
    public void testHandleExceptionOnIteratorCreation()
    {
        Iterables.count( new ExceptionHandlingIterable( () ->
        {
            throw new RuntimeException( "exception on iterator" );
        } )
        {
            protected Iterator exceptionOnIterator( Throwable t )
            {
                rethrow( new IllegalStateException() );
                return super.exceptionOnIterator( t );
            }
        } );
    }

    @Test( expected = IllegalStateException.class )
    public void testHandleExceptionOnIteratorCreation()
    {
        Iterables.count( new ExceptionHandlingIterable( new Iterable()
        {
            public Iterator iterator()
            {
                throw new RuntimeException( "exception on iterator" );
            }
        } )
        {
            protected Iterator exceptionOnIterator( Throwable t )
            {
                rethrow( new IllegalStateException() );
                return super.exceptionOnIterator( t );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.helpers.collection.ExceptionHandlingIterableTest.testHandleExceptionOnIteratorCreation.count.new ExceptionHandlingIterable.new Iterable with () -> {throw new RuntimeException("exception on iterator"); in method public testHandleExceptionOnIteratorCreation() : void from class org.neo4j.helpers.collection.ExceptionHandlingIterableTest


    @Test( expected = IllegalStateException.class )
    public void testHandleExceptionOnNext()
    {
        Iterables.count( new ExceptionHandlingIterable( () -> new Iterator()
        {
            public boolean hasNext()
            {
                return true;
            }

            public Object next()
            {
                throw new RuntimeException( "exception on next" );
            }

            public void remove()
            {
            }
        } )
        {
            @Override
            protected Object exceptionOnNext( Throwable t )
            {
                rethrow( new IllegalStateException() );
                return super.exceptionOnNext( t );
            }
        } );
    }

    @Test( expected = IllegalStateException.class )
    public void testHandleExceptionOnNext()
    {
        Iterables.count( new ExceptionHandlingIterable( new Iterable()
        {
            public Iterator iterator()
            {
                return new Iterator()
                {
                    public boolean hasNext()
                    {
                        return true;
                    }

                    public Object next()
                    {
                        throw new RuntimeException( "exception on next" );
                    }

                    public void remove()
                    {
                    }
                };
            }
        } )
        {
            @Override
            protected Object exceptionOnNext( Throwable t )
            {
                rethrow( new IllegalStateException() );
                return super.exceptionOnNext( t );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.helpers.collection.ExceptionHandlingIterableTest.testHandleExceptionOnNext.count.new ExceptionHandlingIterable.new Iterable with () -> new Iterator(){ in method public testHandleExceptionOnNext() : void from class org.neo4j.helpers.collection.ExceptionHandlingIterableTest


    @Test( expected = IllegalStateException.class )
    public void testHandleExceptionOnHasNext()
    {
        Iterables.count( new ExceptionHandlingIterable( () -> new Iterator()
        {
            public boolean hasNext()
            {
                throw new RuntimeException( "exception on next" );
            }

            public Object next()
            {
                return null;
            }

            public void remove()
            {
            }
        } )
        {
            @Override
            protected boolean exceptionOnHasNext( Throwable t )
            {
                rethrow( new IllegalStateException() );
                return super.exceptionOnHasNext( t );
            }
        } );
    }

    @Test( expected = IllegalStateException.class )
    public void testHandleExceptionOnHasNext()
    {
        Iterables.count( new ExceptionHandlingIterable( new Iterable()
        {
            public Iterator iterator()
            {
                return new Iterator()
                {
                    public boolean hasNext()
                    {
                        throw new RuntimeException( "exception on next" );
                    }

                    public Object next()
                    {
                        return null;
                    }

                    public void remove()
                    {
                    }
                };
            }
        } )
        {
            @Override
            protected boolean exceptionOnHasNext( Throwable t )
            {
                rethrow( new IllegalStateException() );
                return super.exceptionOnHasNext( t );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.helpers.collection.ExceptionHandlingIterableTest.testHandleExceptionOnHasNext.count.new ExceptionHandlingIterable.new Iterable with () -> new Iterator(){ in method public testHandleExceptionOnHasNext() : void from class org.neo4j.helpers.collection.ExceptionHandlingIterableTest