            @Override
            public List<T> apply( String value )
            {
                List<T> list = new ArrayList<>();
                if ( value.length() > 0 )
                {
                    String[] parts = value.split( separator );
                    for ( String part : parts )
                    {
                        list.add( itemParser.apply( part ) );
                    }
                }
                return list;
            }

            @Override
            public List<T> apply( String value )
            {
                List<T> list = new ArrayList<T>();
                if ( value.length() > 0 )
                {
                    String[] parts = value.split( separator );
                    for ( String part : parts )
                    {
                        list.add( itemParser.apply( part ) );
                    }
                }
                return list;
            }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method public apply(value String) : List<T> from class org.neo4j.kernel.configuration.Settings.list.new Function<String,List<T>>


    public static <T> Function<String, List<T>> list( final String separator, final Function<String, T> itemParser )
    {
        return new Function<String, List<T>>()
        {
            @Override
            public List<T> apply( String value )
            {
                List<T> list = new ArrayList<>();
                if ( value.length() > 0 )
                {
                    String[] parts = value.split( separator );
                    for ( String part : parts )
                    {
                        list.add( itemParser.apply( part ) );
                    }
                }
                return list;
            }

            @Override
            public String toString()
            {
                return "a list separated by \"" + separator + "\" where items are " + itemParser.toString();
            }
        };
    }

    public static <T> Function<String, List<T>> list( final String separator, final Function<String, T> itemParser )
    {
        return new Function<String, List<T>>()
        {
            @Override
            public List<T> apply( String value )
            {
                List<T> list = new ArrayList<T>();
                if ( value.length() > 0 )
                {
                    String[] parts = value.split( separator );
                    for ( String part : parts )
                    {
                        list.add( itemParser.apply( part ) );
                    }
                }
                return list;
            }

            @Override
            public String toString()
            {
                return "a list separated by \"" + separator + "\" where items are " + itemParser.toString();
            }
        };
    }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method public list(separator String, itemParser Function<String,T>) : Function<String,List<T>> from class org.neo4j.kernel.configuration.Settings


    private void deadlockDetectionBetween( HighlyAvailableGraphDatabase slave1, final HighlyAvailableGraphDatabase slave2 ) throws Exception
    {
        // GIVEN
        // -- two members acquiring a read lock on the same entity
        final Node commonNode;
        try ( Transaction tx = slave1.beginTx() )
        {
            commonNode = slave1.createNode();
            tx.success();
        }

        OtherThreadExecutor<HighlyAvailableGraphDatabase> thread2 = new OtherThreadExecutor<>( "T2", slave2 );
        Transaction tx1 = slave1.beginTx();
        Transaction tx2 = thread2.execute( new BeginTx() );
        tx1.acquireReadLock( commonNode );
        thread2.execute( new AcquireReadLockOnReferenceNode( tx2, commonNode ) );
        // -- and one of them wanting (and awaiting) to upgrade its read lock to a write lock
        Future<Lock> writeLockFuture = thread2.executeDontWait( state -> {
            try( Transaction ignored = tx2 ) // Close transaction no matter what happens
            {
                return tx2.acquireWriteLock( commonNode );
            }
        } );

        for ( int i = 0; i < 10; i++ )
        {
            thread2.waitUntilThreadState( Thread.State.TIMED_WAITING, Thread.State.WAITING );
            Thread.sleep(2);
        }

        try( Transaction ignored = tx1 ) // Close transaction no matter what happens
        {
            // WHEN
            tx1.acquireWriteLock( commonNode );

            // -- Deadlock detection is non-deterministic, so either the slave or the master will detect it
            writeLockFuture.get();
            fail( "Deadlock exception should have been thrown" );
        }
        catch ( DeadlockDetectedException e )
        {
            // THEN -- deadlock should be avoided with this exception
        }
        catch( ExecutionException e )
        {
            // OR -- the tx2 thread fails with executionexception, caused by deadlock on its end
            assertThat( e.getCause(), instanceOf( DeadlockDetectedException.class ) );
        }

        thread2.close();
    }

    private void deadlockDetectionBetween( HighlyAvailableGraphDatabase slave1, final HighlyAvailableGraphDatabase slave2 ) throws Exception
    {
        // GIVEN
        // -- two members acquiring a read lock on the same entity
        final Node commonNode;
        try ( Transaction tx = slave1.beginTx() )
        {
            commonNode = slave1.createNode();
            tx.success();
        }

        OtherThreadExecutor<HighlyAvailableGraphDatabase> thread2 = new OtherThreadExecutor<>( "T2", slave2 );
        Transaction tx1 = slave1.beginTx();
        Transaction tx2 = thread2.execute( new BeginTx() );
        tx1.acquireReadLock( commonNode );
        thread2.execute( new AcquireReadLockOnReferenceNode( tx2, commonNode ) );
        // -- and one of them wanting (and awaiting) to upgrade its read lock to a write lock
        Future<Lock> writeLockFuture = thread2.executeDontWait( new AcquireWriteLock( tx2, new Callable<Node>(){
            @Override
            public Node call() throws Exception
            {
                return commonNode;
            }
        } ) );

        for ( int i = 0; i < 10; i++ )
        {
            thread2.waitUntilThreadState( Thread.State.TIMED_WAITING, Thread.State.WAITING );
            Thread.sleep(2);
        }

        try
        {
            // WHEN
            tx1.acquireWriteLock( commonNode );

            // -- Deadlock detection is non-deterministic, so either the slave or the master will detect it
            writeLockFuture.get();
            fail( "Deadlock exception should have been thrown" );
        }
        catch ( DeadlockDetectedException e )
        {
            // THEN -- deadlock should be avoided with this exception
        }
        finally
        {
            tx1.close();
        }

        thread2.execute( new FinishTx( tx2, true ) );
        thread2.close();
    }

Try With Resources try(Transaction ignored=tx1) in method private deadlockDetectionBetween(slave1 HighlyAvailableGraphDatabase, slave2 HighlyAvailableGraphDatabase) : void from class org.neo4j.ha.TransactionConstraintsIT


    @Test
    public void shouldStartWithInvalidTokenId() throws Exception
    {
        // given
        LockTokenManager stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new ReplicatedLockTokenState<>() ) );

        // when
        int initialTokenId = stateMachine.currentToken().id();

        // then
        assertEquals( initialTokenId, LockToken.INVALID_LOCK_TOKEN_ID );
    }

    @Test
    public void shouldStartWithInvalidTokenId() throws Exception
    {
        // given
        LockTokenManager stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new InMemoryReplicatedLockTokenState<RaftTestMember>() ) );

        // when
        int initialTokenId = stateMachine.currentToken().id();

        // then
        assertEquals( initialTokenId, LockToken.INVALID_LOCK_TOKEN_ID );
    }

Replace Generic With Diamond ReplicatedLockTokenStateMachine<> with ReplicatedLockTokenStateMachine<> in method public shouldStartWithInvalidTokenId() : void from class org.neo4j.coreedge.server.core.locks.ReplicatedLockTokenStateMachineTest


    @Test
    public void shouldIssueNextLockTokenCandidateId() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine<Object> stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new ReplicatedLockTokenState<>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 0 );

        // then
        assertEquals( firstCandidateId + 1, stateMachine.nextCandidateId() );
    }

    @Test
    public void shouldIssueNextLockTokenCandidateId() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new InMemoryReplicatedLockTokenState<RaftTestMember>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 0 );

        // then
        assertEquals( firstCandidateId + 1, stateMachine.nextCandidateId() );
    }

Replace Generic With Diamond ReplicatedLockTokenStateMachine<> with ReplicatedLockTokenStateMachine<> in method public shouldIssueNextLockTokenCandidateId() : void from class org.neo4j.coreedge.server.core.locks.ReplicatedLockTokenStateMachineTest


    @Test
    public void shouldKeepTrackOfCurrentLockTokenId() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new ReplicatedLockTokenState<>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 1 );

        // then
        assertEquals( firstCandidateId, stateMachine.currentToken().id() );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 1 ), 2 );

        // then
        assertEquals( firstCandidateId + 1, stateMachine.currentToken().id() );
    }

    @Test
    public void shouldKeepTrackOfCurrentLockTokenId() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new InMemoryReplicatedLockTokenState<RaftTestMember>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 1 );

        // then
        assertEquals( firstCandidateId, stateMachine.currentToken().id() );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 1 ), 2 );

        // then
        assertEquals( firstCandidateId + 1, stateMachine.currentToken().id() );
    }

Replace Generic With Diamond ReplicatedLockTokenStateMachine<> with ReplicatedLockTokenStateMachine<> in method public shouldKeepTrackOfCurrentLockTokenId() : void from class org.neo4j.coreedge.server.core.locks.ReplicatedLockTokenStateMachineTest


    @Test
    public void shouldKeepTrackOfLockTokenOwner() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new ReplicatedLockTokenState<>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 1 );

        // then
        assertEquals( member( 0 ), stateMachine.currentToken().owner() );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 1 ), firstCandidateId + 1 ), 2 );

        // then
        assertEquals( member( 1 ), stateMachine.currentToken().owner() );
    }

    @Test
    public void shouldKeepTrackOfLockTokenOwner() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new InMemoryReplicatedLockTokenState<RaftTestMember>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 1 );

        // then
        assertEquals( member( 0 ), stateMachine.currentToken().owner() );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 1 ), firstCandidateId + 1 ), 2 );

        // then
        assertEquals( member( 1 ), stateMachine.currentToken().owner() );
    }

Replace Generic With Diamond ReplicatedLockTokenStateMachine<> with ReplicatedLockTokenStateMachine<> in method public shouldKeepTrackOfLockTokenOwner() : void from class org.neo4j.coreedge.server.core.locks.ReplicatedLockTokenStateMachineTest


    @Test
    public void shouldAcceptOnlyFirstRequestWithSameId() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new ReplicatedLockTokenState<>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 1 );
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 1 ), firstCandidateId ), 2 );

        // then
        assertEquals( 0, stateMachine.currentToken().id() );
        assertEquals( member( 0 ), stateMachine.currentToken().owner() );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 1 ), firstCandidateId + 1 ), 3 );
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 1 ), 4 );

        // then
        assertEquals( 1, stateMachine.currentToken().id() );
        assertEquals( member( 1 ), stateMachine.currentToken().owner() );
    }

    @Test
    public void shouldAcceptOnlyFirstRequestWithSameId() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new InMemoryReplicatedLockTokenState<RaftTestMember>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 1 );
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 1 ), firstCandidateId ), 2 );

        // then
        assertEquals( 0, stateMachine.currentToken().id() );
        assertEquals( member( 0 ), stateMachine.currentToken().owner() );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 1 ), firstCandidateId + 1 ), 3 );
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 1 ), 4 );

        // then
        assertEquals( 1, stateMachine.currentToken().id() );
        assertEquals( member( 1 ), stateMachine.currentToken().owner() );
    }

Replace Generic With Diamond ReplicatedLockTokenStateMachine<> with ReplicatedLockTokenStateMachine<> in method public shouldAcceptOnlyFirstRequestWithSameId() : void from class org.neo4j.coreedge.server.core.locks.ReplicatedLockTokenStateMachineTest


    @Test
    public void shouldOnlyAcceptNextImmediateId() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new ReplicatedLockTokenState<>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 1 ), 1 ); // not accepted

        // then
        assertEquals( stateMachine.currentToken().id(), LockToken.INVALID_LOCK_TOKEN_ID );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 2 ); // accepted

        // then
        assertEquals( stateMachine.currentToken().id(), firstCandidateId );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 1 ), 3 ); // accepted

        // then
        assertEquals( stateMachine.currentToken().id(), firstCandidateId + 1 );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 4 ); // not accepted

        // then
        assertEquals( stateMachine.currentToken().id(), firstCandidateId + 1 );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 3 ), 5 ); // not accepted

        // then
        assertEquals( stateMachine.currentToken().id(), firstCandidateId + 1 );
    }

    @Test
    public void shouldOnlyAcceptNextImmediateId() throws Exception
    {
        // given
        ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine<>(
                new StubStateStorage<>( new InMemoryReplicatedLockTokenState<RaftTestMember>() ) );
        int firstCandidateId = stateMachine.nextCandidateId();

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 1 ), 1 ); // not accepted

        // then
        assertEquals( stateMachine.currentToken().id(), LockToken.INVALID_LOCK_TOKEN_ID );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 2 ); // accepted

        // then
        assertEquals( stateMachine.currentToken().id(), firstCandidateId );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 1 ), 3 ); // accepted

        // then
        assertEquals( stateMachine.currentToken().id(), firstCandidateId + 1 );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId ), 4 ); // not accepted

        // then
        assertEquals( stateMachine.currentToken().id(), firstCandidateId + 1 );

        // when
        stateMachine.applyCommand( new ReplicatedLockTokenRequest<>( member( 0 ), firstCandidateId + 3 ), 5 ); // not accepted

        // then
        assertEquals( stateMachine.currentToken().id(), firstCandidateId + 1 );
    }

Replace Generic With Diamond ReplicatedLockTokenStateMachine<> with ReplicatedLockTokenStateMachine<> in method public shouldOnlyAcceptNextImmediateId() : void from class org.neo4j.coreedge.server.core.locks.ReplicatedLockTokenStateMachineTest


    @Override
    protected final void doRead( RECORD record, PageCursor primaryCursor, int recordSize, PagedFile storeFile,
            long headerByte, boolean inUse ) throws IOException
    {
        boolean recordUnit = has( headerByte, HEADER_BIT_RECORD_UNIT );
        if ( recordUnit )
        {
            boolean firstRecordUnit = has( headerByte, HEADER_BIT_FIRST_RECORD_UNIT );
            if ( !firstRecordUnit )
            {
                // This is a record unit and not even the first one, so you cannot go here directly and read it,
                // it may only be read as part of reading the primary unit.
                record.clear();
                return;
            }
        }

        if ( recordUnit )
        {
            int primaryEndOffset = primaryCursor.getOffset() + recordSize - 1 /*we've already read the header byte*/;

            // This is a record that is split into multiple record units. We need a bit more clever
            // data structures here. For the time being this means instantiating one object,
            // but the trade-off is a great reduction in complexity.
            long secondaryId = Reference.decode( primaryCursor, PAGE_CURSOR_ADAPTER );
            @SuppressWarnings( "resource" )
            SecondaryPageCursorReadDataAdapter readAdapter = new SecondaryPageCursorReadDataAdapter(
                    primaryCursor, storeFile,
                    pageIdForRecord( secondaryId, storeFile.pageSize(), recordSize ),
                    offsetForId( secondaryId, storeFile.pageSize(), recordSize ),
                    primaryEndOffset, PagedFile.PF_SHARED_READ_LOCK );

            try ( SecondaryPageCursorControl secondaryPageCursorControl = readAdapter )
            {
                do
                {
                    // (re)sets offsets for both cursors
                    secondaryPageCursorControl.reposition();
                    doReadInternal( record, primaryCursor, recordSize, headerByte, inUse, readAdapter );
                }
                while ( secondaryPageCursorControl.shouldRetry() );

                record.setSecondaryId( secondaryId );
            }
        }
        else
        {
            doReadInternal( record, primaryCursor, recordSize, headerByte, inUse, PAGE_CURSOR_ADAPTER );
        }
    }

    @Override
    protected final void doRead( RECORD record, PageCursor primaryCursor, int recordSize, PagedFile storeFile,
            long headerByte, boolean inUse ) throws IOException
    {
        boolean recordUnit = has( headerByte, HEADER_BIT_RECORD_UNIT );
        if ( recordUnit )
        {
            boolean firstRecordUnit = has( headerByte, HEADER_BIT_FIRST_RECORD_UNIT);
            if ( !firstRecordUnit )
            {
                // This is a record unit and not even the first one, so you cannot go here directly and read it,
                // it may only be read as part of reading the primary unit.
                record.clear();
                return;
            }
        }

        long secondaryId = -1;
        DataAdapter<PageCursor> dataAdapter = PAGE_CURSOR_ADAPTER;
        SecondaryPageCursorControl secondaryPageCursorControl = SecondaryPageCursorControl.NULL;
        if ( recordUnit )
        {
            int primaryEndOffset = primaryCursor.getOffset() + recordSize - 1 /*we've already read the header byte*/;

            // This is a record that is split into multiple record units. We need a bit more clever
            // data structures here. For the time being this means instantiating one object,
            // but the trade-off is a great reduction in complexity.
            secondaryId = Reference.decode( primaryCursor, dataAdapter );
            @SuppressWarnings( "resource" )
            SecondaryPageCursorReadDataAdapter readAdapter = new SecondaryPageCursorReadDataAdapter(
                    primaryCursor, storeFile,
                    pageIdForRecord( secondaryId, storeFile.pageSize(), recordSize ),
                    offsetForId( secondaryId, storeFile.pageSize(), recordSize ),
                    primaryEndOffset, PagedFile.PF_SHARED_READ_LOCK );
            dataAdapter = readAdapter;
            secondaryPageCursorControl = readAdapter;
        }

        try
        {
            do
            {
                // (re)sets offsets for both cursors
                secondaryPageCursorControl.reposition();
                doReadInternal( record, primaryCursor, recordSize, headerByte, inUse, dataAdapter );
            }
            while ( secondaryPageCursorControl.shouldRetry() );
            if ( recordUnit )
            {
                record.setSecondaryId( secondaryId );
            }
        }
        finally
        {
            secondaryPageCursorControl.close();
        }
    }

Try With Resources try(SecondaryPageCursorControl secondaryPageCursorControl=readAdapter) in method protected doRead(record RECORD, primaryCursor PageCursor, recordSize int, storeFile PagedFile, headerByte long, inUse boolean) : void from class org.neo4j.kernel.impl.store.format.busted.BaseBustedRecordFormat


    private void writeRows( final Iterable<String> columns, Result data, final ResultDataContentWriter writer )
            throws IOException
    {
        out.writeArrayFieldStart( "data" );
        try
        {
            data.accept( row -> {
                out.writeStartObject();
                try
                {
                    writer.write( out, columns, row, TransactionStateChecker.create( container ) );
                }
                finally
                {
                    out.writeEndObject();
                }
                return true;
            } );
        }
        finally
        {
            out.writeEndArray(); // </data>
        }
    }

    private void writeRows( final Iterable<String> columns, Result data, final ResultDataContentWriter writer )
            throws IOException
    {
        out.writeArrayFieldStart( "data" );
        try
        {
            data.accept( new Result.ResultVisitor<IOException>()
            {
                @Override
                public boolean visit( Result.ResultRow row ) throws IOException
                {
                    out.writeStartObject();
                    try
                    {
                        writer.write( out, columns, row );
                    }
                    finally
                    {
                        out.writeEndObject();
                    }
                    return true;
                }
            } );
        }
        finally
        {
            out.writeEndArray(); // </data>
        }
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.ExecutionResultSerializer.writeRows.accept.new Result.ResultVisitor<IOException> with row -> {out.writeStartObject(); in method private writeRows(columns Iterable<String>, data Result, writer ResultDataContentWriter) : void from class org.neo4j.server.rest.transactional.ExecutionResultSerializer


    @Override
    public void accept( final Visitor visitor ) throws Exception
    {
        delegate.accept( row -> {
            visitor.visit( currentRecord.reset( row ) );
            return true;
        } );

        QueryExecutionType qt = delegate.getQueryExecutionType();
        visitor.addMetadata( "type", queryTypeCode( qt.queryType() ) );

        if ( delegate.getQueryStatistics().containsUpdates() )
        {
            Object stats = queryStats( delegate.getQueryStatistics() );
            visitor.addMetadata( "stats", stats );
        }
        if ( qt.requestedExecutionPlanDescription() )
        {
            ExecutionPlanDescription rootPlanTreeNode = delegate.getExecutionPlanDescription();
            String metadataFieldName = rootPlanTreeNode.hasProfilerStatistics() ? "profile" : "plan";
            visitor.addMetadata( metadataFieldName, ExecutionPlanConverter.convert( rootPlanTreeNode ) );
        }

        Iterable<Notification> notifications = delegate.getNotifications();
        if ( notifications.iterator().hasNext() )
        {
            visitor.addMetadata( "notifications", NotificationConverter.convert( notifications ) );
        }
    }

    @Override
    public void accept( final Visitor visitor ) throws Exception
    {
        delegate.accept( new Result.ResultVisitor<Exception>()
        {
            @Override
            public boolean visit( Result.ResultRow row ) throws Exception
            {
                visitor.visit( currentRecord.reset( row ) );
                return true;
            }
        } );

        QueryExecutionType qt = delegate.getQueryExecutionType();
        visitor.addMetadata( "type", queryTypeCode( qt.queryType() ) );

        if ( delegate.getQueryStatistics().containsUpdates() )
        {
            Object stats = queryStats( delegate.getQueryStatistics() );
            visitor.addMetadata( "stats", stats );
        }
        if ( qt.requestedExecutionPlanDescription() )
        {
            ExecutionPlanDescription rootPlanTreeNode = delegate.getExecutionPlanDescription();
            String metadataFieldName = rootPlanTreeNode.hasProfilerStatistics() ? "profile" : "plan";
            visitor.addMetadata( metadataFieldName, ExecutionPlanConverter.convert( rootPlanTreeNode ) );
        }

        Iterable<Notification> notifications = delegate.getNotifications();
        if ( notifications.iterator().hasNext() )
        {
            visitor.addMetadata( "notifications", NotificationConverter.convert( notifications ) );
        }
    }

Replace Anonymous With Lambda org.neo4j.bolt.v1.runtime.internal.CypherAdapterStream.accept.accept.new Result.ResultVisitor<Exception> with row -> {visitor.visit(currentRecord.reset(row)); in method public accept(visitor Visitor) : void from class org.neo4j.bolt.v1.runtime.internal.CypherAdapterStream


        private RepairKit wrap( final RepairKit actual )
        {
            pendingRepairs.add( actual );
            return () -> {
                try
                {
                    return actual.repair();
                }
                finally
                {
                    pendingRepairs.remove( actual );
                }
            };
        }

        private RepairKit wrap( final RepairKit actual )
        {
            pendingRepairs.add( actual );
            return new RepairKit()
            {
                @Override
                public HighlyAvailableGraphDatabase repair() throws Throwable
                {
                    try
                    {
                        return actual.repair();
                    }
                    finally
                    {
                        pendingRepairs.remove( actual );
                    }
                }
            };
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.ManagedCluster.wrap.new RepairKit with () -> {tryreturn actual.repair(); in method private wrap(actual RepairKit) : RepairKit from class org.neo4j.kernel.impl.ha.ClusterManager.ManagedCluster


    private Process startStandaloneClusterClientProcess( File configFile, Map<String, String> config )
            throws Exception
    {
        List<String> args = new ArrayList<>( asList( "java", "-cp", getProperty( "java.class.path" ),
                "-Dorg.neo4j.cluster.logdirectory=" + directory.getAbsolutePath() ) );
        if ( configFile != null )
        {
            args.add( "-D" + ServerSettings.SERVER_CONFIG_FILE_KEY + "=" + configFile.getAbsolutePath() );
        }
        args.add( StandaloneClusterClientTestProxy.class.getName() );

        for ( Map.Entry<String, String> entry : config.entrySet() )
        {
            args.add( "-" + entry.getKey() + "=" + entry.getValue() );
        }
        return getRuntime().exec( args.toArray( new String[args.size()] ) );
    }

    private Process startStandaloneClusterClientProcess( File configFile, Map<String, String> config )
            throws Exception
    {
        List<String> args = new ArrayList<String>( asList( "java", "-cp", getProperty( "java.class.path" ),
                "-Dneo4j.home=" + directory.getAbsolutePath() ) );
        if ( configFile != null )
        {
            args.add( "-D" + ServerSettings.SERVER_CONFIG_FILE_KEY + "=" + configFile.getAbsolutePath() );
        }
        args.add( StandaloneClusterClientTestProxy.class.getName() );

        for ( Map.Entry<String, String> entry : config.entrySet() )
        {
            args.add( "-" + entry.getKey() + "=" + entry.getValue() );
        }
        return getRuntime().exec( args.toArray( new String[args.size()] ) );
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method private startStandaloneClusterClientProcess(configFile File, config Map<String,String>) : Process from class org.neo4j.server.enterprise.StandaloneClusterClientIT


    private JButton createCommandPromptButton()
    {
        return Components.createTextButton( ellipsis( "Command Prompt" ), e -> {
            try
            {
                model.launchCommandPrompt();
            }
            catch ( Exception exception )
            {
                exception.printStackTrace();
                alert( exception.getMessage() );
            }
        } );
    }

    private JButton createCommandPromptButton()
    {
        return Components.createTextButton( ellipsis( "Command Prompt" ), new ActionListener()
        {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                try
                {
                    model.launchCommandPrompt();
                }
                catch ( Exception exception )
                {
                    exception.printStackTrace();
                    alert( exception.getMessage() );
                }
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.desktop.ui.SettingsDialog.createCommandPromptButton.createTextButton.new ActionListener with e -> {trymodel.launchCommandPrompt(); in method private createCommandPromptButton() : JButton from class org.neo4j.desktop.ui.SettingsDialog


    @Override
    public File[] listFiles( File directory )
    {
        try ( Stream<Path> listing = Files.list( path( directory ) ) )
        {
            return listing.map( Path::toFile ).toArray( File[]::new );
        }
        catch ( IOException e )
        {
            return null;
        }
    }

    @Override
    public File[] listFiles( File directory )
    {
        List<File> files = new ArrayList<>();
        try
        {
            for ( Path path : Files.newDirectoryStream( path( directory ) ) )
            {
                files.add( path.toFile() );
            }
        }
        catch ( IOException e )
        {
            return null;
        }
        return files.toArray( new File[files.size()] );
    }

Try With Resources try(Stream<Path> listing=Files.list(path(directory))) in method public listFiles(directory File) : File[] from class org.neo4j.io.fs.DelegateFileSystemAbstraction


    @Override
    public File[] listFiles( File directory, final FilenameFilter filter )
    {
        try ( Stream<Path> listing = Files.list( path( directory ) ) )
        {
            return listing
                    .filter( entry -> filter.accept( entry.getParent().toFile(), entry.getFileName().toString() ) )
                    .map( Path::toFile )
                    .toArray( File[]::new );
        }
        catch ( IOException e )
        {
            return null;
        }
    }

    @Override
    public File[] listFiles( File directory, final FilenameFilter filter )
    {
        List<File> files = new ArrayList<>();
        try
        {
            DirectoryStream.Filter<Path> dirfilter = new DirectoryStream.Filter<Path>()
            {
                @Override
                public boolean accept( Path entry ) throws IOException
                {
                    return filter.accept( entry.getParent().toFile(), entry.getFileName().toString() );
                }
            };
            for ( Path path : Files.newDirectoryStream( path( directory ), dirfilter ) )
            {
                files.add( path.toFile() );
            }
        }
        catch ( IOException e )
        {
            return null;
        }
        return files.toArray( new File[files.size()] );
    }

Try With Resources try(Stream<Path> listing=Files.list(path(directory))) in method public listFiles(directory File, filter FilenameFilter) : File[] from class org.neo4j.io.fs.DelegateFileSystemAbstraction


    public static void copyFile( File srcFile, File dstFile ) throws IOException
    {
        //noinspection ResultOfMethodCallIgnored
        dstFile.getParentFile().mkdirs();
        try ( FileInputStream input = new FileInputStream( srcFile );
              FileOutputStream output = new FileOutputStream( dstFile ); )
        {
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int bytesRead;
            while ( (bytesRead = input.read( buffer )) != -1 )
            {
                output.write( buffer, 0, bytesRead );
            }
        }
        catch ( IOException e )
        {
            // Because the message from this cause may not mention which file it's about
            throw new IOException( "Could not copy '" + srcFile + "' to '" + dstFile + "'", e );
        }
    }

    public static void copyFile( File srcFile, File dstFile ) throws IOException
    {
        //noinspection ResultOfMethodCallIgnored
        dstFile.getParentFile().mkdirs();
        FileInputStream input = null;
        FileOutputStream output = null;
        try
        {
            input = new FileInputStream( srcFile );
            output = new FileOutputStream( dstFile );
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int bytesRead;
            while ( (bytesRead = input.read( buffer )) != -1 )
            {
                output.write( buffer, 0, bytesRead );
            }
        }
        catch ( IOException e )
        {
            // Because the message from this cause may not mention which file it's about
            throw new IOException( "Could not copy '" + srcFile + "' to '" + dstFile + "'", e );
        }
        finally
        {
            if ( input != null )
            {
                input.close();
            }
            if ( output != null )
            {
                output.close();
            }
        }
    }

Try With Resources try(FileInputStream input=new FileInputStream(srcFile); FileOutputStream output=new FileOutputStream(dstFile)) in method public copyFile(srcFile File, dstFile File) : void from class org.neo4j.io.fs.FileUtils


    private void copyFile( File from, FileSystemAbstraction fromFs, File to, ByteBuffer buffer ) throws IOException
    {
        try ( StoreChannel source = fromFs.open( from, "r" );
              StoreChannel sink = this.open( to, "rw" ) )
        {
            for ( int available; (available = (int) (source.size() - source.position())) > 0; )
            {
                buffer.clear();
                buffer.limit( min( available, buffer.capacity() ) );
                source.read( buffer );
                buffer.flip();
                sink.write( buffer );
            }
        }
    }

    private void copyFile( File from, FileSystemAbstraction fromFs, File to, ByteBuffer buffer ) throws IOException
    {
        StoreChannel source = fromFs.open( from, "r" );
        StoreChannel sink = this.open( to, "rw" );
        try
        {
            for ( int available; (available = (int) (source.size() - source.position())) > 0; )
            {
                buffer.clear();
                buffer.limit( min( available, buffer.capacity() ) );
                source.read( buffer );
                buffer.flip();
                sink.write( buffer );
            }
        }
        finally
        {
            if ( source != null )
            {
                source.close();
            }
            if ( sink != null )
            {
                sink.close();
            }
        }
    }

Try With Resources try(StoreChannel source=fromFs.open(from,"r"); StoreChannel sink=this.open(to,"rw")) in method private copyFile(from File, fromFs FileSystemAbstraction, to File, buffer ByteBuffer) : void from class org.neo4j.graphdb.mockfs.EphemeralFileSystemAbstraction


    private static boolean available( int port )
    {
        if ( port < 1111 || port > 9999 )
        {
            throw new IllegalArgumentException( "Invalid start port: " + port );
        }

        try ( ServerSocket ss = new ServerSocket( port );
              DatagramSocket ds = new DatagramSocket( port ) )
        {
            ss.setReuseAddress( true );
            ds.setReuseAddress( true );
            return true;
        }
        catch ( IOException e )
        {
        }

        return false;
    }

    private static boolean available( int port )
    {
        if ( port < 1111 || port > 9999 )
        {
            throw new IllegalArgumentException( "Invalid start port: " + port );
        }

        ServerSocket ss = null;
        DatagramSocket ds = null;
        try
        {
            ss = new ServerSocket( port );
            ss.setReuseAddress( true );
            ds = new DatagramSocket( port );
            ds.setReuseAddress( true );
            return true;
        }
        catch ( IOException e )
        {
        }
        finally
        {
            if ( ds != null )
            {
                ds.close();
            }

            if ( ss != null )
            {
                try
                {
                    ss.close();
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        }

        return false;
    }

Try With Resources try(ServerSocket ss=new ServerSocket(port); DatagramSocket ds=new DatagramSocket(port)) in method private available(port int) : boolean from class org.neo4j.server.WebTestUtils


    private void readAndThrowFailureResponse()
    {
        Throwable cause;
        try
        {
            try ( ObjectInputStream input = new ObjectInputStream( asInputStream() ) )
            {
                cause = (Throwable) input.readObject();
            }
        }
        catch ( Throwable e )
        {
            // Note: this is due to a problem with the streaming of exceptions, the ChunkingChannelBuffer will almost
            // always sends exceptions back as two chunks, the first one empty and the second with the exception.
            // We hit this when we try to read the exception of the first one, and in reading it hit the second
            // chunk with the "real" exception. This should be revisited to 1) clear up the chunking and 2) handle
            // serialized exceptions spanning multiple chunks.
            if ( e instanceof RuntimeException ) throw (RuntimeException) e;
            if ( e instanceof Error ) throw (Error) e;

            throw new ComException( e );
        }

        if ( cause instanceof RuntimeException ) throw (RuntimeException) cause;
        if ( cause instanceof Error ) throw (Error) cause;
        throw new ComException( cause );
    }

    private void readAndThrowFailureResponse()
    {
        Throwable cause;
        try
        {
            ObjectInputStream input = new ObjectInputStream( asInputStream() );
            cause = (Throwable) input.readObject();
        }
        catch ( Throwable e )
        {
            // Note: this is due to a problem with the streaming of exceptions, the ChunkingChannelBuffer will almost
            // always sends exceptions back as two chunks, the first one empty and the second with the exception.
            // We hit this when we try to read the exception of the first one, and in reading it hit the second
            // chunk with the "real" exception. This should be revisited to 1) clear up the chunking and 2) handle
            // serialized exceptions spanning multiple chunks.
            if ( e instanceof RuntimeException ) throw (RuntimeException) e;
            if ( e instanceof Error ) throw (Error) e;

            throw new ComException( e );
        }

        if ( cause instanceof RuntimeException ) throw (RuntimeException) cause;
        if ( cause instanceof Error ) throw (Error) cause;
        throw new ComException( cause );
    }

Try With Resources try(ObjectInputStream input=new ObjectInputStream(asInputStream())) in method private readAndThrowFailureResponse() : void from class org.neo4j.com.DechunkingChannelBuffer


    public long getLastCommittedIndex()
    {
        long lastCommittedIndex;
        long lastTxId = transactionIdStore.getLastCommittedTransactionId();

        if ( lastTxId == 1 )
        {
            lastCommittedIndex = -1;
        }
        else
        {
            byte[] lastHeaderFound = null;
            try ( IOCursor<CommittedTransactionRepresentation> transactions =
                          transactionStore.getTransactions( lastTxId ) )
            {
                while ( transactions.next() )
                {
                    CommittedTransactionRepresentation committedTransactionRepresentation = transactions.get();
                    lastHeaderFound = committedTransactionRepresentation.getStartEntry().getAdditionalHeader();
                }
            }
            catch ( Exception e )
            {
                throw new RuntimeException( e );
            }
            lastCommittedIndex = decodeLogIndexFromTxHeader( lastHeaderFound );
        }

        log.info( "Last committed index %d", lastCommittedIndex );
        return lastCommittedIndex;
    }

    public long getLastCommittedIndex()
    {
        long lastCommittedIndex;
        long lastTxId = transactionIdStore.getLastCommittedTransactionId();

        if ( lastTxId == 1 )
        {
            lastCommittedIndex = -1;
        }
        else
        {
            IOCursor<CommittedTransactionRepresentation> transactions;
            byte[] lastHeaderFound;
            try
            {
                transactions = transactionStore.getTransactions( lastTxId );
                lastHeaderFound = null;
                while ( transactions.next() )
                {
                    CommittedTransactionRepresentation committedTransactionRepresentation = transactions.get();
                    lastHeaderFound = committedTransactionRepresentation.getStartEntry().getAdditionalHeader();
                }
            }
            catch ( Exception e )
            {
                throw new RuntimeException( e );
            }
            lastCommittedIndex = decodeLogIndexFromTxHeader( lastHeaderFound );
        }

        log.info( "Last committed index %d", lastCommittedIndex );
        return lastCommittedIndex;
    }

Try With Resources try(IOCursor<CommittedTransactionRepresentation> transactions=transactionStore.getTransactions(lastTxId)) in method public getLastCommittedIndex() : long from class org.neo4j.coreedge.raft.replication.tx.LastCommittedIndexFinder


    public DarwinInstallation()
    {
        String filename = "openNeoTerminal.sh";
        try
        {
            String[] scriptCommands = {
                    "#!/bin/bash",
                    "export PATH=$PATH:'" + this.getInstallationBinDirectory().getAbsolutePath().toString() + "':'" +
                    this.getInstallationJreBinDirectory().getAbsolutePath().toString() + "'",
                    "echo Neo4j Command Prompt",
                    "echo",
                    "echo This window is configured with Neo4j on the path.",
                    "echo",
                    "echo Available commands:",
                    "echo neo4j-shell",
                    "echo neo4j-import",
                    "bash"};

            try ( FileWriter fileWriter = new FileWriter( new File( filename ), false ) )
            {
                for ( String scriptCommand : scriptCommands )
                {
                    fileWriter.write( scriptCommand + "\n" );
                }
            }

            String commands[] = { "bash", "-c", "chmod a+x " + filename };

            Runtime.getRuntime().exec( commands );
        }
        catch( IOException ioe )
        {
            System.out.println( "Error writing openNeoTerminal.sh" );
        }
        catch( URISyntaxException urise )
        {
            System.out.println( "Error getting bin locations for openNeoTerminal.sh" );
        }
    }

    public DarwinInstallation()
    {
        String filename = "openNeoTerminal.sh";
        try
        {
            String[] scriptCommands = {
                    "#!/bin/bash",
                    "export PATH=$PATH:'" + this.getInstallationBinDirectory().getAbsolutePath().toString() + "':'" +
                    this.getInstallationJreBinDirectory().getAbsolutePath().toString() + "'",
                    "echo Neo4j Command Prompt",
                    "echo",
                    "echo This window is configured with Neo4j on the path.",
                    "echo",
                    "echo Available commands:",
                    "echo neo4j-shell",
                    "echo neo4j-import",
                    "bash"};

            FileWriter fileWriter = new FileWriter( new File( filename ), false );

            for( String scriptCommand : scriptCommands )
            {
                fileWriter.write( scriptCommand + "\n");
            }

            fileWriter.flush();
            fileWriter.close();

            String commands[] = { "bash", "-c", "chmod a+x " + filename };

            Runtime.getRuntime().exec( commands );
        }
        catch( IOException ioe )
        {
            System.out.println( "Error writing openNeoTerminal.sh" );
        }
        catch( URISyntaxException urise )
        {
            System.out.println( "Error getting bin locations for openNeoTerminal.sh" );
        }
    }

Try With Resources try(FileWriter fileWriter=new FileWriter(new File(filename),false)) in method public DarwinInstallation() from class org.neo4j.desktop.config.osx.DarwinInstallation


    @Override
    public void actionPerformed( ActionEvent e )
    {
        File selectedFile = null;
        boolean cancelled = false;
        boolean validLocation = false;

        while ( !validLocation && !cancelled )
        {
            if ( SystemUtils.IS_OS_MAC )
            {
                selectedFile = macFileSelection();
            }
            else
            {
                selectedFile = fileSelection();
            }

            try
            {
                model.setDatabaseDirectory( selectedFile );
                directoryDisplay.setText( selectedFile.getAbsolutePath() );

                validLocation = true;

                try ( FileWriter fileWriter = new FileWriter( new File( ".dblocation" ) ) )
                {
                    fileWriter.write( selectedFile.getAbsolutePath() );
                }
            }
            catch ( UnsuitableDirectoryException ude )
            {
                int choice = showWrappedConfirmDialog(
                        frame,
                        ude.getMessage() + "\n" + "Please choose a different folder.",
                        "Invalid folder selected", OK_CANCEL_OPTION, ERROR_MESSAGE );

                if ( choice == CANCEL_OPTION )
                {
                    cancelled = true;
                }
            }
            catch ( IOException ioe )
            {
                System.out.println( "Error saving DB location" );
                System.out.println( ioe );
            }
        }
    }

    @Override
    public void actionPerformed( ActionEvent e )
    {
        File selectedFile = null;
        boolean cancelled = false;
        boolean validLocation = false;

        while ( !validLocation && !cancelled )
        {
            if ( SystemUtils.IS_OS_MAC )
            {
                selectedFile = macFileSelection();
            }
            else
            {
                selectedFile = fileSelection();
            }

            try
            {
                model.setDatabaseDirectory( selectedFile );
                directoryDisplay.setText( selectedFile.getAbsolutePath() );

                validLocation = true;

                FileWriter fileWriter = new FileWriter( new File( ".dblocation" ) );
                fileWriter.write( selectedFile.getAbsolutePath() );
                fileWriter.flush();
                fileWriter.close();
            }
            catch ( UnsuitableDirectoryException ude )
            {
                int choice = showWrappedConfirmDialog(
                        frame,
                        ude.getMessage() + "\n" + "Please choose a different folder.",
                        "Invalid folder selected", OK_CANCEL_OPTION, ERROR_MESSAGE );

                if ( choice == CANCEL_OPTION )
                {
                    cancelled = true;
                }
            }
            catch ( IOException ioe )
            {
                System.out.println( "Error saving DB location" );
                System.out.println( ioe );
            }
        }
    }

Try With Resources try(FileWriter fileWriter=new FileWriter(new File(".dblocation"))) in method public actionPerformed(e ActionEvent) : void from class org.neo4j.desktop.ui.BrowseForDatabaseActionListener


    public MainWindow( DatabaseActions databaseActions, DesktopModel model )
    {
        this.model = model;
        this.debugWindow = new SystemOutDebugWindow();
        this.databaseActions = databaseActions;

        this.frame = new JFrame( "Neo4j Community Edition" );
        this.frame.setIconImages( Graphics.loadIcons() );
        this.sysTray = SysTray.install( new SysTrayActions(), frame );

        String location = model.getDatabaseDirectory().getAbsolutePath();
        File file = new File( ".dblocation" );

        if ( file.exists() && file.canRead() )
        {
            try
            {
                try ( Scanner scanner = new Scanner( file ) )
                {
                    if ( scanner.hasNextLine() )
                    {
                        location = scanner.nextLine();
                    }
                }
            }
            catch ( FileNotFoundException e )
            {
                e.printStackTrace();
            }
        }

        this.directoryDisplay = createUnmodifiableTextField( location, 35 );
        this.browseButton = createBrowseButton();
        this.statusPanelLayout = new CardLayout();
        this.statusPanel = createStatusPanel( statusPanelLayout );
        this.startButton = createStartButton();
        this.stopButton = createStopButton();

        JButton optionsButton = createOptionsButton();
        JPanel root =
                createRootPanel( directoryDisplay, browseButton, statusPanel, startButton, stopButton, optionsButton );

        frame.add( root );
        frame.pack();
        frame.setResizable( false );

        updateStatus( STOPPED );
    }

    public MainWindow( DatabaseActions databaseActions, DesktopModel model )
    {
        this.model = model;
        this.debugWindow = new SystemOutDebugWindow();
        this.databaseActions = databaseActions;

        this.frame = new JFrame( "Neo4j Community Edition" );
        this.frame.setIconImages( Graphics.loadIcons() );
        this.sysTray = SysTray.install( new SysTrayActions(), frame );

        String location = model.getDatabaseDirectory().getAbsolutePath();
        File file = new File( ".dblocation" );

        if( file.exists() && file.canRead() )
        {
            try
            {
                Scanner scanner = new Scanner( file );
                if ( scanner.hasNextLine() )
                {
                    location = scanner.nextLine();
                }
            }
            catch ( FileNotFoundException e )
            {
                e.printStackTrace();
            }
        }

        this.directoryDisplay = createUnmodifiableTextField( location, 35 );
        this.browseButton = createBrowseButton();
        this.statusPanelLayout = new CardLayout();
        this.statusPanel = createStatusPanel( statusPanelLayout );
        this.startButton = createStartButton();
        this.stopButton = createStopButton();

        JButton optionsButton = createOptionsButton();
        JPanel root =
                createRootPanel( directoryDisplay, browseButton, statusPanel, startButton, stopButton, optionsButton );

        frame.add( root );
        frame.pack();
        frame.setResizable( false );

        updateStatus( STOPPED );
    }

Try With Resources try(Scanner scanner=new Scanner(file)) in method public MainWindow(databaseActions DatabaseActions, model DesktopModel) from class org.neo4j.desktop.ui.MainWindow


    @Test
    public void restartWhileDoingTransactions() throws Exception
    {
        // given
        File dbDir = dir.directory();
        cluster = Cluster.start( dbDir, 3, 0 );

        // when
        final GraphDatabaseService coreDB = cluster.getCoreServerById( 0 );

        ExecutorService executor = Executors.newCachedThreadPool();

        final AtomicBoolean done = new AtomicBoolean( false );
        executor.execute( () -> {
            while ( !done.get() )
            {
                try ( Transaction tx = coreDB.beginTx() )
                {
                    Node node = coreDB.createNode( label( "boo" ) );
                    node.setProperty( "foobar", "baz_bat" );
                    tx.success();
                }
            }
        } );
        Thread.sleep( 500 );

        cluster.removeCoreServerWithServerId( 1 );
        cluster.addCoreServerWithServerId( 1, 3 );
        Thread.sleep( 500 );

        // then
        done.set( true );
        executor.shutdown();
        cluster.shutdown();
    }

    @Test
    public void restartWhileDoingTransactions() throws Exception
    {
        // given
        File dbDir = dir.directory();
        cluster = Cluster.start( dbDir, 3, 0);

        // when
        final GraphDatabaseService coreDB = cluster.getCoreServerById( 0 );

        ExecutorService executor = Executors.newCachedThreadPool();

        final AtomicBoolean done = new AtomicBoolean( false );
        executor.execute( new Runnable()
        {
            @Override
            public void run()
            {
                while ( !done.get() )
                {
                    try ( Transaction tx = coreDB.beginTx() )
                    {
                        Node node = coreDB.createNode( label( "boo" ) );
                        node.setProperty( "foobar", "baz_bat" );
                        tx.success();
                    }
                }
            }
        } );
        Thread.sleep( 500 );

        cluster.removeCoreServerWithServerId( 1 );
        cluster.addCoreServerWithServerId( 1, 3 );
        Thread.sleep( 500 );

        // then
        done.set( true );
        executor.shutdown();
        cluster.shutdown();
    }

Replace Anonymous With Lambda org.neo4j.coreedge.scenarios.RestartIT.restartWhileDoingTransactions.execute.new Runnable with () -> {while(!done.get()){try(Transaction tx=coreDB.beginTx())Node node=coreDB.createNode(label("boo")); in method public restartWhileDoingTransactions() : void from class org.neo4j.coreedge.scenarios.RestartIT


    @Test
    public void testMultipleCreate() throws InterruptedException
    {
        final int numThreads = 25;
        final String uuid = UUID.randomUUID().toString();

        final Node commonNode;
        try(Transaction tx = graphDb.beginTx())
        {
            commonNode = graphDb.createNode();
            tx.success();
        }

        ExecutorCompletionService<Node> ecs = new ExecutorCompletionService<>(
                Executors.newFixedThreadPool( numThreads ) );
        for ( int i = 0; i < numThreads; i++ )
        {
            ecs.submit( () -> {
                try ( Transaction tx = graphDb.beginTx() )
                {
                    final Node node = graphDb.createNode();
                    // Acquire lock
                    tx.acquireWriteLock( commonNode );
                    Index<Node> index = graphDb.index().forNodes( "uuids" );
                    final Node existing = index.get( "uuid", uuid ).getSingle();
                    if ( existing != null )
                    {
                        throw new RuntimeException( "Node already exists" );
                    }
                    node.setProperty( "uuid", uuid );
                    index.add( node, "uuid", uuid );
                    tx.success();
                    return node;
                }
            } );
        }
        int numSucceeded = 0;
        for ( int i = 0; i < numThreads; i++ )
        {
            try
            {
                ecs.take().get();
                ++numSucceeded;
            }
            catch ( ExecutionException e )
            {
            }
        }
        assertEquals( 1, numSucceeded );
    }

    @Test
    public void testMultipleCreate() throws InterruptedException
    {
        final int numThreads = 25;
        final String uuid = UUID.randomUUID().toString();

        final Node commonNode;
        try(Transaction tx = graphDb.beginTx())
        {
            commonNode = graphDb.createNode();
            tx.success();
        }

        ExecutorCompletionService<Node> ecs = new ExecutorCompletionService<>(
                Executors.newFixedThreadPool( numThreads ) );
        for ( int i = 0; i < numThreads; i++ )
        {
            ecs.submit( new Callable<Node>()
            {
                public Node call() throws Exception
                {
                    try ( Transaction tx = graphDb.beginTx() )
                    {
                        final Node node = graphDb.createNode();
                        // Acquire lock
                        tx.acquireWriteLock( commonNode );
                        Index<Node> index = graphDb.index().forNodes( "uuids" );
                        final Node existing = index.get( "uuid", uuid ).getSingle();
                        if ( existing != null )
                        {
                            throw new RuntimeException( "Node already exists" );
                        }
                        node.setProperty( "uuid", uuid );
                        index.add( node, "uuid", uuid );
                        tx.success();
                        return node;
                    }
                }
            } );
        }
        int numSucceeded = 0;
        for ( int i = 0; i < numThreads; i++ )
        {
            try
            {
                ecs.take().get();
                ++numSucceeded;
            }
            catch ( ExecutionException e )
            {
            }
        }
        assertEquals( 1, numSucceeded );
    }

Replace Anonymous With Lambda org.neo4j.index.IndexConstraintsTest.testMultipleCreate.submit.new Callable<Node> with () -> {try(Transaction tx=graphDb.beginTx())final Node node=graphDb.createNode(); in method public testMultipleCreate() : void from class org.neo4j.index.IndexConstraintsTest


    @Parameterized.Parameters( name = "{0}" )
    public static Collection<IOFunction<DirectoryFactory,LuceneIndexAccessor>[]> implementations()
    {
        final File dir = new File( "dir" );
        return Arrays.asList(
                arg( dirFactory1 -> {
                    LuceneSchemaIndex index = LuceneSchemaIndexBuilder.create()
                            .withFileSystem( new EphemeralFileSystemAbstraction() )
                            .withDirectoryFactory( dirFactory1 )
                            .withIndexRootFolder( dir )
                            .withIndexIdentifier( "1" )
                            .build();

                    index.create();
                    index.open();
                    return new LuceneIndexAccessor( index );
                } ),
                arg( dirFactory1 -> {
                    LuceneSchemaIndex index = LuceneSchemaIndexBuilder.create()
                            .uniqueIndex()
                            .withFileSystem( new EphemeralFileSystemAbstraction() )
                            .withDirectoryFactory( dirFactory1 )
                            .withIndexRootFolder( dir )
                            .withIndexIdentifier( "testIndex" )
                            .build();

                    index.create();
                    index.open();
                    return new LuceneIndexAccessor( index );
                } )
        );
    }

    @Parameterized.Parameters( name = "{0}" )
    public static Collection<IOFunction<DirectoryFactory,LuceneIndexAccessor>[]> implementations()
    {
        final File dir = new File( "dir" );
        return Arrays.asList(
                arg( new IOFunction<DirectoryFactory,LuceneIndexAccessor>()
                {
                    @Override
                    public LuceneIndexAccessor apply( DirectoryFactory dirFactory )
                            throws IOException
                    {
                        LuceneSchemaIndex index = LuceneSchemaIndexBuilder.create()
                                .withFileSystem( new EphemeralFileSystemAbstraction() )
                                .withDirectoryFactory( dirFactory )
                                .withIndexRootFolder( dir )
                                .withIndexIdentifier( "1" )
                                .build();

                        index.create();
                        index.open();
                        return new LuceneIndexAccessor( index );
                    }
                } ),
                arg( new IOFunction<DirectoryFactory,LuceneIndexAccessor>()
                {
                    @Override
                    public LuceneIndexAccessor apply( DirectoryFactory dirFactory )
                            throws IOException
                    {
                        LuceneSchemaIndex index = LuceneSchemaIndexBuilder.create()
                                .uniqueIndex()
                                .withFileSystem( new EphemeralFileSystemAbstraction() )
                                .withDirectoryFactory( dirFactory )
                                .withIndexRootFolder( dir )
                                .withIndexIdentifier( "testIndex" )
                                .build();

                        index.create();
                        index.open();
                        return new LuceneIndexAccessor( index );
                    }
                } )
        );
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.index.LuceneIndexAccessorTest.implementations.asList.arg.new IOFunction<DirectoryFactory,LuceneIndexAccessor> with dirFactory1 -> {LuceneSchemaIndex index=LuceneSchemaIndexBuilder.create().withFileSystem(new EphemeralFileSystemAbstraction()).withDirectoryFactory(dirFactory1).withIndexRootFolder(dir).withIndexIdentifier("1").build(); in method public implementations() : Collection<IOFunction<DirectoryFactory,LuceneIndexAccessor>[]> from class org.neo4j.kernel.api.impl.index.LuceneIndexAccessorTest


    @Test
    public void shouldReadPagesOfDocumentsFromSearcher() throws Exception
    {
        final int labelId = 7;
        final int pageSize = 2;
        // given
        Query query = mock( Query.class );
        IndexSearcher searcher = mock( IndexSearcher.class );

        NumericDocValues rangeNDV = mock( NumericDocValues.class );
        when( rangeNDV.get( 11 ) ).thenReturn( 0x1L );
        when( rangeNDV.get( 16 ) ).thenReturn( 0x2L );
        when( rangeNDV.get( 37 ) ).thenReturn( 0x3L );

        NumericDocValues labelNDV = mock( NumericDocValues.class );
        when( labelNDV.get( 11 ) ).thenReturn( 0x01L );
        when( labelNDV.get( 16 ) ).thenReturn( 0x03L );
        when( labelNDV.get( 37 ) ).thenReturn( 0x30L );

        Map<String,NumericDocValues> docValues = MapUtil.genericMap( "range", rangeNDV, "7", labelNDV );
        IndexReaderStub reader = new IndexReaderStub( docValues );
        reader.setElements( new String[]{"11", "16", "37"} );
        final LeafReaderContext context = reader.getContext();

        doAnswer( invocation -> {
            DocValuesCollector collector = (DocValuesCollector) invocation.getArguments()[1];
            collector.doSetNextReader( context );
            collector.collect( 11 );
            collector.collect( 16 );
            collector.collect( 37 );
            return null;
        } ).when( searcher ).search( same( query ), any( DocValuesCollector.class ) );

        PrimitiveLongIterator iterator = concat(
                new PageOfRangesIterator( format, searcher, pageSize, query, labelId ) );

        // when
        List<Long> longs = primitivesList( iterator );

        // then
        assertEquals( asList(
        /*doc1:*/(1L << format.bitmapFormat().shift),
        /*doc2:*/(2L << format.bitmapFormat().shift), (2L << format.bitmapFormat().shift) + 1,
        /*doc3:*/(3L << format.bitmapFormat().shift) + 4, (3L << format.bitmapFormat().shift) + 5 ),
                longs );

        verify( searcher, times( 1 ) ).search( same( query ), any( DocValuesCollector.class ) );
        verify( rangeNDV, times( 3 ) ).get( anyInt() );
        verify( labelNDV, times( 3 ) ).get( anyInt() );

        verifyNoMoreInteractions( searcher );
        verifyNoMoreInteractions( labelNDV );
        verifyNoMoreInteractions( rangeNDV );
    }

    @Test
    public void shouldReadPagesOfDocumentsFromSearcher() throws Exception
    {
        final int labelId = 7;
        final int pageSize = 2;
        // given
        Query query = mock( Query.class );
        IndexSearcher searcher = mock( IndexSearcher.class );

        NumericDocValues rangeNDV = mock( NumericDocValues.class );
        when( rangeNDV.get( 11 ) ).thenReturn( 0x1L );
        when( rangeNDV.get( 16 ) ).thenReturn( 0x2L );
        when( rangeNDV.get( 37 ) ).thenReturn( 0x3L );

        NumericDocValues labelNDV = mock( NumericDocValues.class );
        when( labelNDV.get( 11 ) ).thenReturn( 0x01L );
        when( labelNDV.get( 16 ) ).thenReturn( 0x03L );
        when( labelNDV.get( 37 ) ).thenReturn( 0x30L );

        Map<String,NumericDocValues> docValues =
                MapUtil.genericMap( "range", rangeNDV, "7", labelNDV );
        IndexReaderStub reader = new IndexReaderStub( docValues );
        reader.setElements( new String[]{"11", "16", "37"} );
        final LeafReaderContext context = reader.getContext();

        doAnswer( new Answer<Void>()
        {
            @Override
            public Void answer( InvocationOnMock invocation ) throws Throwable
            {
                DocValuesCollector collector = (DocValuesCollector) invocation.getArguments()[1];
                collector.doSetNextReader( context );
                collector.collect( 11 );
                collector.collect( 16 );
                collector.collect( 37 );
                return null;
            }
        } ).when( searcher ).search( same( query ), any( DocValuesCollector.class ) );

        PrimitiveLongIterator iterator = concat(
                new PageOfRangesIterator( format, searcher, pageSize, query, labelId ) );

        // when
        List<Long> longs = primitivesList( iterator );

        // then
        assertEquals( asList(
        /*doc1:*/(1L << format.bitmapFormat().shift),
        /*doc2:*/(2L << format.bitmapFormat().shift), (2L << format.bitmapFormat().shift) + 1,
        /*doc3:*/(3L << format.bitmapFormat().shift) + 4, (3L << format.bitmapFormat().shift) + 5 ),
                      longs );

        verify( searcher, times( 1 ) ).search( same( query ), any( DocValuesCollector.class ) );
        verify( rangeNDV, times( 3 ) ).get( anyInt() );
        verify( labelNDV, times( 3 ) ).get( anyInt() );

        verifyNoMoreInteractions( searcher );
        verifyNoMoreInteractions( labelNDV );
        verifyNoMoreInteractions( rangeNDV );
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.index.PageOfRangesIteratorTest.shouldReadPagesOfDocumentsFromSearcher.search.when.doAnswer.new Answer<Void> with invocation -> {DocValuesCollector collector=(DocValuesCollector)invocation.getArguments()[1]; in method public shouldReadPagesOfDocumentsFromSearcher() : void from class org.neo4j.kernel.api.impl.index.PageOfRangesIteratorTest


    private Answer<Long> answerWith( final long indexUniqueValues, final long indexSize )
    {
        return invocationOnMock -> {
            DoubleLong.Out result = (DoubleLong.Out) invocationOnMock.getArguments()[0];
            result.write( indexUniqueValues, indexSize );
            return indexSize;
        };
    }

    private Answer<Long> answerWith( final long indexUniqueValues, final long indexSize )
    {
        return new Answer<Long>()
        {
            @Override
            public Long answer( InvocationOnMock invocationOnMock ) throws Throwable
            {
                final DoubleLong.Out result = (DoubleLong.Out) invocationOnMock.getArguments()[0];
                result.write( indexUniqueValues, indexSize );
                return indexSize;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.sampling.OnlineIndexSamplingJobTest.answerWith.new Answer<Long> with invocationOnMock -> {DoubleLong.Out result=(DoubleLong.Out)invocationOnMock.getArguments()[0]; in method private answerWith(indexUniqueValues long, indexSize long) : Answer<Long> from class org.neo4j.kernel.impl.api.index.sampling.OnlineIndexSamplingJobTest


    @Override
    public long sampleIndex( final DoubleLong.Out result ) throws IndexNotFoundKernelException
    {
        if ( data == null )
        {
            throw new IndexNotFoundKernelException( "Index dropped while sampling." );
        }
        final long[] uniqueAndSize = {0, 0};
        try
        {
            iterateAll( ( value, nodeIds ) -> {
                int ids = nodeIds.size();
                if ( ids > 0 )
                {
                    uniqueAndSize[0] += 1;
                    uniqueAndSize[1] += ids;
                }
            } );
        }
        catch ( Exception ex )
        {
            throw new RuntimeException( ex );
        }

        result.write( uniqueAndSize[0], uniqueAndSize[1] );
        return uniqueAndSize[1];
    }

    @Override
    public long sampleIndex( final DoubleLong.Out result ) throws IndexNotFoundKernelException
    {
        if ( data == null )
        {
            throw new IndexNotFoundKernelException( "Index dropped while sampling." );
        }
        final long[] uniqueAndSize = {0, 0};
        try
        {
            iterateAll( new IndexEntryIterator()
            {
                @Override
                public void visitEntry( Object value, Set<Long> nodeIds )
                {
                    int ids = nodeIds.size();
                    if ( ids > 0 )
                    {
                        uniqueAndSize[0] += 1;
                        uniqueAndSize[1] += ids;
                    }
                }
            });
        }
        catch ( Exception ex )
        {
            throw new RuntimeException( ex );
        }

        result.write( uniqueAndSize[0], uniqueAndSize[1] );
        return uniqueAndSize[1];
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.inmemory.HashBasedIndex.sampleIndex.iterateAll.new IndexEntryIterator with (value, nodeIds) -> {int ids=nodeIds.size(); in method public sampleIndex(result DoubleLong.Out) : long from class org.neo4j.kernel.impl.api.index.inmemory.HashBasedIndex


    @Override
    public Map<String, String> fillInDefaults( Map<String, String> source )
    {
        Map<String, String> result = source != null ?
                new HashMap<>( source ) : new HashMap<>();
        String analyzer = result.get( KEY_ANALYZER );
        if ( analyzer == null )
        {
            // Type is only considered if "analyzer" isn't supplied
            String type = result.get( KEY_TYPE );
            if ( type == null )
            {
                type = "exact";
                result.put( KEY_TYPE, type );
            }
            if ( type.equals( "fulltext" ) &&
                 !result.containsKey( LuceneIndexImplementation.KEY_TO_LOWER_CASE ) )
            {
                result.put( KEY_TO_LOWER_CASE, "true" );
            }
        }

        // Try it on for size. Calling this will reveal configuration problems.
        IndexType.getIndexType( result );

        return result;
    }

    @Override
    public Map<String, String> fillInDefaults( Map<String, String> source )
    {
        Map<String, String> result = source != null ?
                new HashMap<>( source ) : new HashMap<String, String>();
        String analyzer = result.get( KEY_ANALYZER );
        if ( analyzer == null )
        {
            // Type is only considered if "analyzer" isn't supplied
            String type = result.get( KEY_TYPE );
            if ( type == null )
            {
                type = "exact";
                result.put( KEY_TYPE, type );
            }
            if ( type.equals( "fulltext" ) &&
                 !result.containsKey( LuceneIndexImplementation.KEY_TO_LOWER_CASE ) )
            {
                result.put( KEY_TO_LOWER_CASE, "true" );
            }
        }

        // Try it on for size. Calling this will reveal configuration problems.
        IndexType.getIndexType( result );

        return result;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public fillInDefaults(source Map<String,String>) : Map<String,String> from class org.neo4j.index.impl.lucene.legacy.LuceneIndexImplementation


    private static Unsafe getUnsafe()
    {
        try
        {
            PrivilegedExceptionAction<Unsafe> getUnsafe = () -> {
                try
                {
                    return Unsafe.getUnsafe();
                }
                catch ( Exception e )
                {
                    Class<Unsafe> type = Unsafe.class;
                    Field[] fields = type.getDeclaredFields();
                    for ( Field field : fields )
                    {
                        if ( Modifier.isStatic( field.getModifiers() )
                             && type.isAssignableFrom( field.getType() ) )
                        {
                            field.setAccessible( true );
                            return type.cast( field.get( null ) );
                        }
                    }
                    LinkageError error = new LinkageError( "No static field of type sun.misc.Unsafe" );
                    error.addSuppressed( e );
                    throw error;
                }
            };
            return AccessController.doPrivileged( getUnsafe );
        }
        catch ( Exception e )
        {
            throw new LinkageError( "Cannot access sun.misc.Unsafe", e );
        }
    }

    private static Unsafe getUnsafe()
    {
        try
        {
            return AccessController.doPrivileged( new PrivilegedExceptionAction<Unsafe>()
            {
                @Override
                public Unsafe run() throws Exception
                {
                    try
                    {
                        return Unsafe.getUnsafe();
                    }
                    catch ( Exception e )
                    {
                        Class<Unsafe> type = Unsafe.class;
                        Field[] fields = type.getDeclaredFields();
                        for ( Field field : fields )
                        {
                            if ( Modifier.isStatic( field.getModifiers() )
                                    && type.isAssignableFrom( field.getType() ) )
                            {
                                field.setAccessible( true );
                                return type.cast( field.get( null ) );
                            }
                        }
                        LinkageError error = new LinkageError( "No static field of type sun.misc.Unsafe" );
                        error.addSuppressed( e );
                        throw error;
                    }
                }
            } );
        }
        catch ( Exception e )
        {
            throw new LinkageError( "Cannot access sun.misc.Unsafe", e );
        }
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.internal.dragons.UnsafeUtil.getUnsafe.doPrivileged.new PrivilegedExceptionAction<Unsafe> with () -> {tryreturn Unsafe.getUnsafe(); in method private getUnsafe() : Unsafe from class org.neo4j.unsafe.impl.internal.dragons.UnsafeUtil


    @Test
    public void shouldVisitLogFile() throws Exception
    {
        // GIVEN
        String name = "log";
        StoreFlusher storeFlusher = mock( StoreFlusher.class );
        LifeSupport life = new LifeSupport();
        PhysicalLogFiles logFiles = new PhysicalLogFiles( directory.directory(), name, fs );
        LogFile logFile = life.add( new PhysicalLogFile( fs, logFiles, 50,
                transactionIdStore, logVersionRepository, mock( Monitor.class ),
                new TransactionMetadataCache( 10, 100 )) );
        life.start();
        FlushablePositionAwareChannel writer = logFile.getWriter();
        LogPositionMarker mark = new LogPositionMarker();
        writer.getCurrentPosition( mark );
        for ( int i = 0; i < 5; i++ )
        {
            writer.put( (byte)i );
        }
        writer.prepareForFlush();

        // WHEN/THEN
        final AtomicBoolean called = new AtomicBoolean();
        logFile.accept( ( position, channel ) -> {
            for ( int i = 0; i < 5; i++ )
            {
                assertEquals( (byte)i, channel.get() );
            }
            called.set( true );
            return true;
        }, mark.newPosition() );
        assertTrue( called.get() );
        life.shutdown();
    }

    @Test
    public void shouldVisitLogFile() throws Exception
    {
        // GIVEN
        String name = "log";
        StoreFlusher storeFlusher = mock( StoreFlusher.class );
        LifeSupport life = new LifeSupport();
        PhysicalLogFiles logFiles = new PhysicalLogFiles( directory.directory(), name, fs );
        LogFile logFile = life.add( new PhysicalLogFile( fs, logFiles, 50,
                transactionIdStore, logVersionRepository, mock( Monitor.class ),
                new TransactionMetadataCache( 10, 100 )) );
        life.start();
        FlushablePositionAwareChannel writer = logFile.getWriter();
        LogPositionMarker mark = new LogPositionMarker();
        writer.getCurrentPosition( mark );
        for ( int i = 0; i < 5; i++ )
        {
            writer.put( (byte)i );
        }
        writer.prepareForFlush();

        // WHEN/THEN
        final AtomicBoolean called = new AtomicBoolean();
        logFile.accept( new LogFileVisitor()
        {
            @Override
            public boolean visit( LogPosition position, ReadableLogChannel channel ) throws IOException
            {
                for ( int i = 0; i < 5; i++ )
                {
                    assertEquals( (byte)i, channel.get() );
                }
                called.set( true );
                return true;
            }
        }, mark.newPosition() );
        assertTrue( called.get() );
        life.shutdown();
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.PhysicalLogFileTest.shouldVisitLogFile.accept.new LogFileVisitor with (position, channel) -> {for(int i=0; i < 5; i++){assertEquals((byte)i,channel.get()); in method public shouldVisitLogFile() : void from class org.neo4j.kernel.impl.transaction.log.PhysicalLogFileTest


    @Before
    public void setup() throws IOException
    {
        for ( int i = 0; i <= logVersion; i++ )
        {
            File file = mock( File.class );
            when( logFiles.getLogFileForVersion( i ) ).thenReturn( file );
            StoreChannel channel = mock( StoreChannel.class );
            when( fs.open( file, "rw" ) ).thenReturn( channel );
            final int version = i;
            when( channel.read( any( ByteBuffer.class ) ) ).thenAnswer( invocationOnMock -> {
                ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
                buffer.putLong( encodeLogVersion( version ) );
                buffer.putLong( 33 );
                return LOG_HEADER_SIZE;
            } );
        }
        when( fs.fileExists( any( File.class ) ) ).thenReturn( true );
    }

    @Before
    public void setup() throws IOException
    {
        for ( int i = 0; i <= logVersion; i++ )
        {
            File file = mock( File.class );
            when( logFiles.getLogFileForVersion( i ) ).thenReturn( file );
            StoreChannel channel = mock( StoreChannel.class );
            when( fs.open( file, "rw" ) ).thenReturn( channel );
            final int version = i;
            when( channel.read( any( ByteBuffer.class ) ) ).thenAnswer( new Answer<Integer>()
            {
                @Override
                public Integer answer( InvocationOnMock invocationOnMock ) throws Throwable
                {
                    ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
                    buffer.putLong( encodeLogVersion( version ) );
                    buffer.putLong( 33 );
                    return LOG_HEADER_SIZE;
                }
            } );
        }
        when( fs.fileExists( any( File.class ) ) ).thenReturn( true );
    }

Replace Anonymous With Lambda org.neo4j.kernel.recovery.LatestCheckPointFinderTest.setup.thenAnswer.new Answer<Integer> with invocationOnMock -> {ByteBuffer buffer=(ByteBuffer)invocationOnMock.getArguments()[0]; in method public setup() : void from class org.neo4j.kernel.recovery.LatestCheckPointFinderTest


    @Test
    public void shouldValidateConstraintIndexAsPartOfExtraction() throws Throwable
    {
        // GIVEN
        NeoStores neoStores = neoStoresRule.open();
        TransactionRecordState recordState = new TransactionRecordState( neoStores, integrityValidator,
                newContext( neoStores ) );

        final long indexId = neoStores.getSchemaStore().nextId();
        final long constraintId = neoStores.getSchemaStore().nextId();

        recordState.createSchemaRule( uniquenessConstraintRule( constraintId, 1, 1, indexId ) );

        // WHEN
        recordState.extractCommands( new ArrayList<>() );

        // THEN
        verify( integrityValidator ).validateSchemaRule( any() );
    }

    @Test
    public void shouldValidateConstraintIndexAsPartOfExtraction() throws Throwable
    {
        // GIVEN
        NeoStores neoStores = neoStoresRule.open();
        TransactionRecordState recordState = new TransactionRecordState( neoStores, integrityValidator,
                newContext( neoStores ) );

        final long indexId = neoStores.getSchemaStore().nextId();
        final long constraintId = neoStores.getSchemaStore().nextId();

        recordState.createSchemaRule( uniquenessConstraintRule( constraintId, 1, 1, indexId ) );

        // WHEN
        recordState.extractCommands( new ArrayList<StorageCommand>() );

        // THEN
        verify( integrityValidator ).validateSchemaRule( any() );
    }

Replace Generic With Diamond ArrayList<StorageCommand> with ArrayList<> in method public shouldValidateConstraintIndexAsPartOfExtraction() : void from class org.neo4j.kernel.impl.transaction.state.TransactionRecordStateTest


    @Test
    public void shouldContainTransactionsThatHappenDuringBackupProcess() throws Throwable
    {
        // given
        defaultBackupPortHostParams();
        Config defaultConfig = dbRule.getConfigCopy();
        dbRule.setConfig( OnlineBackupSettings.online_backup_enabled, "false" );
        Config withOnlineBackupEnabled = dbRule.getConfigCopy();

        final Barrier.Control barrier = new Barrier.Control();
        final GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();

        createAndIndexNode( db, 1 ); // create some data

        final DependencyResolver resolver = db.getDependencyResolver();
        NeoStoreDataSource ds = resolver.resolveDependency( DataSourceManager.class ).getDataSource();
        long expectedLastTxId = ds.getLastCommittedTransactionId();

        // This monitor is added server-side...
        monitors.addMonitorListener( new StoreSnoopingMonitor( barrier ) );

        Dependencies dependencies = new Dependencies( resolver );
        dependencies.satisfyDependencies( defaultConfig, monitors, NullLogProvider.getInstance() );

        OnlineBackupKernelExtension backup = (OnlineBackupKernelExtension)
                new OnlineBackupExtensionFactory().newInstance( new SimpleKernelContext( fileSystem, storeDir ),
                DependenciesProxy.dependencies(dependencies, OnlineBackupExtensionFactory.Dependencies.class));
        backup.start();

        // when
        BackupService backupService = backupService();
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute( () -> {
            barrier.awaitUninterruptibly();

            createAndIndexNode( db, 1 );
            resolver.resolveDependency( NeoStoresSupplier.class ).get().flush();

            barrier.release();
        } );

        BackupService.BackupOutcome backupOutcome = backupService.doFullBackup( BACKUP_HOST, backupPort,
                backupDir.getAbsoluteFile(), ConsistencyCheck.DEFAULT, withOnlineBackupEnabled,
                BackupClient.BIG_READ_TIMEOUT, false );

        backup.stop();
        executor.shutdown();
        executor.awaitTermination( 30, TimeUnit.SECONDS );

        // then
        checkPreviousCommittedTxIdFromLog( 0, expectedLastTxId );
        File neoStore = new File( storeDir, MetaDataStore.DEFAULT_NAME );
        long txIdFromOrigin = MetaDataStore
                .getRecord( resolver.resolveDependency( PageCache.class ), neoStore, Position.LAST_TRANSACTION_ID );
        checkLastCommittedTxIdInLogAndNeoStore( expectedLastTxId+1, txIdFromOrigin );
        assertEquals( DbRepresentation.of( db ), DbRepresentation.of( backupDir ) );
        assertTrue( backupOutcome.isConsistent() );
    }

    @Test
    public void shouldContainTransactionsThatHappenDuringBackupProcess() throws Throwable
    {
        // given
        defaultBackupPortHostParams();
        Config defaultConfig = dbRule.getConfigCopy();
        dbRule.setConfig( OnlineBackupSettings.online_backup_enabled, "false" );
        Config withOnlineBackupEnabled = dbRule.getConfigCopy();

        final Barrier.Control barrier = new Barrier.Control();
        final GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();

        createAndIndexNode( db, 1 ); // create some data

        final DependencyResolver resolver = db.getDependencyResolver();
        NeoStoreDataSource ds = resolver.resolveDependency( DataSourceManager.class ).getDataSource();
        long expectedLastTxId = ds.getLastCommittedTransactionId();

        // This monitor is added server-side...
        monitors.addMonitorListener( new StoreSnoopingMonitor( barrier ) );

        Dependencies dependencies = new Dependencies( resolver );
        dependencies.satisfyDependencies( defaultConfig, monitors, NullLogProvider.getInstance() );

        OnlineBackupKernelExtension backup = (OnlineBackupKernelExtension) new OnlineBackupExtensionFactory().newKernelExtension(
                DependenciesProxy.dependencies(dependencies, OnlineBackupExtensionFactory.Dependencies.class));
        backup.start();

        // when
        BackupService backupService = backupService();
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute( new Runnable()
        {
            @Override
            public void run()
            {
                barrier.awaitUninterruptibly();

                createAndIndexNode( db, 1 );
                resolver.resolveDependency( NeoStoresSupplier.class ).get().flush();

                barrier.release();
            }
        } );

        BackupService.BackupOutcome backupOutcome = backupService.doFullBackup( BACKUP_HOST, backupPort,
                backupDir.getAbsoluteFile(), ConsistencyCheck.DEFAULT, withOnlineBackupEnabled,
                BackupClient.BIG_READ_TIMEOUT, false );

        backup.stop();
        executor.shutdown();
        executor.awaitTermination( 30, TimeUnit.SECONDS );

        // then
        checkPreviousCommittedTxIdFromLog( 0, expectedLastTxId );
        File neoStore = new File( storeDir, MetaDataStore.DEFAULT_NAME );
        long txIdFromOrigin = MetaDataStore
                .getRecord( resolver.resolveDependency( PageCache.class ), neoStore, Position.LAST_TRANSACTION_ID );
        checkLastCommittedTxIdInLogAndNeoStore( expectedLastTxId+1, txIdFromOrigin );
        assertEquals( DbRepresentation.of( db ), DbRepresentation.of( backupDir ) );
        assertTrue( backupOutcome.isConsistent() );
    }

Replace Anonymous With Lambda org.neo4j.backup.BackupServiceIT.shouldContainTransactionsThatHappenDuringBackupProcess.execute.new Runnable with () -> {barrier.awaitUninterruptibly(); in method public shouldContainTransactionsThatHappenDuringBackupProcess() : void from class org.neo4j.backup.BackupServiceIT


    @Test
    public void messageNodesAreOnlyReturnedOnce()
    {
        Map<Node,Integer> counts = new HashMap<>();
        for ( Node message : new VisibleMessagesByFollowedUsers( user ) )
        {
            Integer seen = counts.get( message );
            counts.put( message, seen == null ? 1 : (seen + 1) );
            count++;
        }
        StringBuilder duplicates = null;
        for ( Map.Entry<Node,Integer> seen : counts.entrySet() )
        {
            if ( seen.getValue() > 1 )
            {
                if ( duplicates == null )
                {
                    duplicates = new StringBuilder(
                            "These nodes occured multiple times (expected once): " );
                }
                else
                {
                    duplicates.append( ", " );
                }
                duplicates.append( seen.getKey() );
                duplicates.append( " (" );
                duplicates.append( seen.getValue() );
                duplicates.append( " times)" );
            }
        }
        if ( duplicates != null )
        {
            fail( duplicates.toString() );
        }
        tx.success();
    }

    @Test
    public void messageNodesAreOnlyReturnedOnce()
    {
        Map<Node,Integer> counts = new HashMap<Node,Integer>();
        for ( Node message : new VisibleMessagesByFollowedUsers( user ) )
        {
            Integer seen = counts.get( message );
            counts.put( message, seen == null ? 1 : (seen + 1) );
            count++;
        }
        StringBuilder duplicates = null;
        for ( Map.Entry<Node,Integer> seen : counts.entrySet() )
        {
            if ( seen.getValue() > 1 )
            {
                if ( duplicates == null )
                {
                    duplicates = new StringBuilder(
                            "These nodes occured multiple times (expected once): " );
                }
                else
                {
                    duplicates.append( ", " );
                }
                duplicates.append( seen.getKey() );
                duplicates.append( " (" );
                duplicates.append( seen.getValue() );
                duplicates.append( " times)" );
            }
        }
        if ( duplicates != null )
        {
            fail( duplicates.toString() );
        }
        tx.success();
    }

Replace Generic With Diamond HashMap<Node,Integer> with HashMap<> in method public messageNodesAreOnlyReturnedOnce() : void from class matching.TestMatchingOfCircularPattern


    private Iterator<TraversalBranch> gatherSourceIterator( TraversalContext metadata )
    {
        LinkedList<TraversalBranch> queue = new LinkedList<>();
        queue.add( current.next( expander, metadata ) );
        while ( true )
        {
            List<TraversalBranch> level = gatherOneLevel( queue, metadata );
            if ( level.isEmpty() )
            {
                break;
            }
            queue.addAll( 0, level );
        }
        return queue.iterator();
    }

    private Iterator<TraversalBranch> gatherSourceIterator( TraversalContext metadata )
    {
        LinkedList<TraversalBranch> queue = new LinkedList<TraversalBranch>();
        queue.add( current.next( expander, metadata ) );
        while ( true )
        {
            List<TraversalBranch> level = gatherOneLevel( queue, metadata );
            if ( level.isEmpty() )
            {
                break;
            }
            queue.addAll( 0, level );
        }
        return queue.iterator();
    }

Replace Generic With Diamond LinkedList<TraversalBranch> with LinkedList<> in method private gatherSourceIterator(metadata TraversalContext) : Iterator<TraversalBranch> from class org.neo4j.graphdb.traversal.PostorderBreadthFirstSelector


    private List<TraversalBranch> gatherOneLevel(
            List<TraversalBranch> queue, TraversalContext metadata )
    {
        List<TraversalBranch> level = new LinkedList<>();
        Integer depth = null;
        for ( TraversalBranch source : queue )
        {
            if ( depth == null )
            {
                depth = source.length();
            }
            else if ( source.length() != depth )
            {
                break;
            }

            while ( true )
            {
                TraversalBranch next = source.next( expander, metadata );
                if ( next == null )
                {
                    break;
                }
                level.add( next );
            }
        }
        return level;
    }

    private List<TraversalBranch> gatherOneLevel(
            List<TraversalBranch> queue, TraversalContext metadata )
    {
        List<TraversalBranch> level = new LinkedList<TraversalBranch>();
        Integer depth = null;
        for ( TraversalBranch source : queue )
        {
            if ( depth == null )
            {
                depth = source.length();
            }
            else if ( source.length() != depth )
            {
                break;
            }

            while ( true )
            {
                TraversalBranch next = source.next( expander, metadata );
                if ( next == null )
                {
                    break;
                }
                level.add( next );
            }
        }
        return level;
    }

Replace Generic With Diamond LinkedList<TraversalBranch> with LinkedList<> in method private gatherOneLevel(queue List<TraversalBranch>, metadata TraversalContext) : List<TraversalBranch> from class org.neo4j.graphdb.traversal.PostorderBreadthFirstSelector


    RecentlyUnique( PrimitiveTypeFetcher type, Object parameter )
    {
        super( type );
        parameter = parameter != null ? parameter : DEFAULT_RECENT_SIZE;
        recentlyVisited = new LruCache<>( "Recently visited",
                ((Number) parameter).intValue() );
    }

    RecentlyUnique( PrimitiveTypeFetcher type, Object parameter )
    {
        super( type );
        parameter = parameter != null ? parameter : DEFAULT_RECENT_SIZE;
        recentlyVisited = new LruCache<Long, Object>( "Recently visited",
                ((Number) parameter).intValue() );
    }

Replace Generic With Diamond LruCache<Long,Object> with LruCache<> in method package RecentlyUnique(type PrimitiveTypeFetcher, parameter Object) from class org.neo4j.graphdb.traversal.RecentlyUnique