    @Test( expected = /* THEN */ IllegalStateException.class )
    public void shouldNotCloseWhileUpdating() throws IOException
    {
        // GIVEN
        final DoubleLatch latch = new DoubleLatch();
        final IndexProxy inner = new IndexProxyAdapter()
        {
            @Override
            public IndexUpdater newUpdater( IndexUpdateMode mode )
            {
                return super.newUpdater( mode );
            }
        };
        final IndexProxy outer = newContractCheckingIndexProxy( inner );
        outer.start();

        // WHEN
        runInSeparateThread( () ->
        {
            try (IndexUpdater updater = outer.newUpdater( IndexUpdateMode.ONLINE ))
            {
                updater.process( null );
                latch.startAndWaitForAllToStartAndFinish();
            }
            catch ( IndexEntryConflictException e )
            {
                throw new RuntimeException( e );
            }
        } );

        try
        {
            latch.waitForAllToStart();
            outer.close();
        }
        finally
        {
            latch.finish();
        }
    }

    @Test( expected = /* THEN */ IllegalStateException.class )
    public void shouldNotCloseWhileUpdating() throws IOException
    {
        // GIVEN
        final DoubleLatch latch = new DoubleLatch();
        final IndexProxy inner = new IndexProxyAdapter()
        {
            @Override
            public IndexUpdater newUpdater( IndexUpdateMode mode )
            {
                return super.newUpdater( mode );
            }
        };
        final IndexProxy outer = newContractCheckingIndexProxy( inner );
        outer.start();

        // WHEN
        runInSeparateThread( new ThrowingRunnable()
        {
            @Override
            public void run() throws IOException
            {
                try (IndexUpdater updater = outer.newUpdater( IndexUpdateMode.ONLINE ))
                {
                    updater.process( null );
                    latch.startAndAwaitFinish();
                }
                catch ( IndexEntryConflictException e )
                {
                    throw new RuntimeException( e );
                }
            }
        } );

        try
        {
            latch.awaitStart();
            outer.close();
        }
        finally
        {
            latch.finish();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.ContractCheckingIndexProxyTest.shouldNotCloseWhileUpdating.runInSeparateThread.new ThrowingRunnable with () -> {try(IndexUpdater updater=outer.newUpdater(IndexUpdateMode.ONLINE))updater.process(null); in method public shouldNotCloseWhileUpdating() : void from class org.neo4j.kernel.impl.api.index.ContractCheckingIndexProxyTest


    private void runInSeparateThread( final ThrowingRunnable action )
    {
        new Thread( () ->
        {
            try
            {
                action.run();
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
        } ).start();
    }

    private void runInSeparateThread( final ThrowingRunnable action )
    {
        new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    action.run();
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        } ).start();
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.ContractCheckingIndexProxyTest.runInSeparateThread.start.new Thread.new Runnable with () -> {tryaction.run(); in method private runInSeparateThread(action ThrowingRunnable) : void from class org.neo4j.kernel.impl.api.index.ContractCheckingIndexProxyTest


    @Test( timeout = 5_000 )
    public void shouldAcceptNewJobWhenRunningJobFinishes() throws Throwable
    {
        // Given
        when( config.jobLimit() ).thenReturn( 1 );

        JobScheduler jobScheduler = new Neo4jJobScheduler();
        jobScheduler.init();

        final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker( config, jobScheduler );

        final DoubleLatch latch = new DoubleLatch();
        final AtomicBoolean lastJobExecuted = new AtomicBoolean();

        jobTracker.scheduleSamplingJob( new IndexSamplingJob()
        {
            @Override
            public IndexDescriptor descriptor()
            {
                return new IndexDescriptor( 1, 1 );
            }

            @Override
            public void run()
            {
                latch.waitForAllToStart();
            }
        } );

        // When
        Executors.newSingleThreadExecutor().execute( () ->
        {
            jobTracker.waitUntilCanExecuteMoreSamplingJobs();
            jobTracker.scheduleSamplingJob( new IndexSamplingJob()
            {
                @Override
                public IndexDescriptor descriptor()
                {
                    return new IndexDescriptor( 2, 2 );
                }

                @Override
                public void run()
                {
                    lastJobExecuted.set( true );
                    latch.finish();
                }
            } );
        } );

        assertFalse( jobTracker.canExecuteMoreSamplingJobs() );
        latch.startAndWaitForAllToStart();
        latch.waitForAllToFinish();

        // Then
        assertTrue( lastJobExecuted.get() );
    }

    @Test( timeout = 5_000 )
    public void shouldAcceptNewJobWhenRunningJobFinishes() throws Throwable
    {
        // Given
        when( config.jobLimit() ).thenReturn( 1 );

        JobScheduler jobScheduler = new Neo4jJobScheduler();
        jobScheduler.init();

        final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker( config, jobScheduler );

        final DoubleLatch latch = new DoubleLatch();
        final AtomicBoolean lastJobExecuted = new AtomicBoolean();

        jobTracker.scheduleSamplingJob( new IndexSamplingJob()
        {
            @Override
            public IndexDescriptor descriptor()
            {
                return new IndexDescriptor( 1, 1 );
            }

            @Override
            public void run()
            {
                latch.awaitStart();
            }
        } );

        // When
        Executors.newSingleThreadExecutor().execute( new Runnable()
        {
            @Override
            public void run()
            {
                jobTracker.waitUntilCanExecuteMoreSamplingJobs();
                jobTracker.scheduleSamplingJob( new IndexSamplingJob()
                {
                    @Override
                    public IndexDescriptor descriptor()
                    {
                        return new IndexDescriptor( 2, 2 );
                    }

                    @Override
                    public void run()
                    {
                        lastJobExecuted.set( true );
                        latch.finish();
                    }
                } );
            }
        } );

        assertFalse( jobTracker.canExecuteMoreSamplingJobs() );
        latch.start();
        latch.awaitFinish();

        // Then
        assertTrue( lastJobExecuted.get() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.sampling.IndexSamplingJobTrackerTest.shouldAcceptNewJobWhenRunningJobFinishes.execute.new Runnable with () -> {jobTracker.waitUntilCanExecuteMoreSamplingJobs(); in method public shouldAcceptNewJobWhenRunningJobFinishes() : void from class org.neo4j.kernel.impl.api.index.sampling.IndexSamplingJobTrackerTest


    @Test( timeout = 5_000 )
    public void shouldStopAndWaitForAllJobsToFinish() throws Throwable
    {
        // Given
        when( config.jobLimit() ).thenReturn( 2 );

        JobScheduler jobScheduler = new Neo4jJobScheduler();
        jobScheduler.init();

        final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker( config, jobScheduler );
        final CountDownLatch latch1 = new CountDownLatch( 1 );
        final CountDownLatch latch2 = new CountDownLatch( 1 );

        WaitingIndexSamplingJob job1 = new WaitingIndexSamplingJob( new IndexDescriptor( 1, 1 ), latch1 );
        WaitingIndexSamplingJob job2 = new WaitingIndexSamplingJob( new IndexDescriptor( 2, 2 ), latch1 );

        jobTracker.scheduleSamplingJob( job1 );
        jobTracker.scheduleSamplingJob( job2 );

        Future<?> stopping = Executors.newSingleThreadExecutor().submit( () ->
        {
            latch2.countDown();
            jobTracker.stopAndAwaitAllJobs();
        } );

        // When
        latch2.await();
        assertFalse( stopping.isDone() );
        latch1.countDown();
        stopping.get( 10, SECONDS );

        // Then
        assertTrue( stopping.isDone() );
        assertNull( stopping.get() );
        assertTrue( job1.executed );
        assertTrue( job2.executed );
    }

    @Test( timeout = 5_000 )
    public void shouldStopAndWaitForAllJobsToFinish() throws Throwable
    {
        // Given
        when( config.jobLimit() ).thenReturn( 2 );

        JobScheduler jobScheduler = new Neo4jJobScheduler();
        jobScheduler.init();

        final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker( config, jobScheduler );
        final CountDownLatch latch1 = new CountDownLatch( 1 );
        final CountDownLatch latch2 = new CountDownLatch( 1 );

        WaitingIndexSamplingJob job1 = new WaitingIndexSamplingJob( new IndexDescriptor( 1, 1 ), latch1 );
        WaitingIndexSamplingJob job2 = new WaitingIndexSamplingJob( new IndexDescriptor( 2, 2 ), latch1 );

        jobTracker.scheduleSamplingJob( job1 );
        jobTracker.scheduleSamplingJob( job2 );

        Future<?> stopping = Executors.newSingleThreadExecutor().submit( new Runnable()
        {
            @Override
            public void run()
            {
                latch2.countDown();
                jobTracker.stopAndAwaitAllJobs();
            }
        } );

        // When
        latch2.await();
        assertFalse( stopping.isDone() );
        latch1.countDown();
        stopping.get( 10, SECONDS );

        // Then
        assertTrue( stopping.isDone() );
        assertNull( stopping.get() );
        assertTrue( job1.executed );
        assertTrue( job2.executed );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.sampling.IndexSamplingJobTrackerTest.shouldStopAndWaitForAllJobsToFinish.stopping.submit.new Runnable with () -> {latch2.countDown(); in method public shouldStopAndWaitForAllJobsToFinish() : void from class org.neo4j.kernel.impl.api.index.sampling.IndexSamplingJobTrackerTest


    @Test( timeout = 5_000 )
    public void shouldWaitForAllJobsToFinish() throws Throwable
    {
        // Given
        when( config.jobLimit() ).thenReturn( 2 );

        JobScheduler jobScheduler = new Neo4jJobScheduler();
        jobScheduler.init();

        final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker( config, jobScheduler );
        final CountDownLatch latch1 = new CountDownLatch( 1 );
        final CountDownLatch latch2 = new CountDownLatch( 1 );

        WaitingIndexSamplingJob job1 = new WaitingIndexSamplingJob( new IndexDescriptor( 1, 1 ), latch1 );
        WaitingIndexSamplingJob job2 = new WaitingIndexSamplingJob( new IndexDescriptor( 2, 2 ), latch1 );

        jobTracker.scheduleSamplingJob( job1 );
        jobTracker.scheduleSamplingJob( job2 );

        Future<?> stopping = Executors.newSingleThreadExecutor().submit( () ->
        {
            latch2.countDown();
            try {
                jobTracker.awaitAllJobs( 10, TimeUnit.SECONDS );
            } catch (InterruptedException e)
            {
                throw new RuntimeException( e );
            }
        } );

        // When
        latch2.await();
        assertFalse( stopping.isDone() );
        latch1.countDown();
        stopping.get( 10, SECONDS );

        // Then
        assertTrue( stopping.isDone() );
        assertNull( stopping.get() );
        assertTrue( job1.executed );
        assertTrue( job2.executed );
    }

    @Test( timeout = 5_000 )
    public void shouldWaitForAllJobsToFinish() throws Throwable
    {
        // Given
        when( config.jobLimit() ).thenReturn( 2 );

        JobScheduler jobScheduler = new Neo4jJobScheduler();
        jobScheduler.init();

        final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker( config, jobScheduler );
        final CountDownLatch latch1 = new CountDownLatch( 1 );
        final CountDownLatch latch2 = new CountDownLatch( 1 );

        WaitingIndexSamplingJob job1 = new WaitingIndexSamplingJob( new IndexDescriptor( 1, 1 ), latch1 );
        WaitingIndexSamplingJob job2 = new WaitingIndexSamplingJob( new IndexDescriptor( 2, 2 ), latch1 );

        jobTracker.scheduleSamplingJob( job1 );
        jobTracker.scheduleSamplingJob( job2 );

        Future<?> stopping = Executors.newSingleThreadExecutor().submit( new Runnable()
        {
            @Override
            public void run()
            {
                latch2.countDown();
                try {
                    jobTracker.awaitAllJobs( 10, TimeUnit.SECONDS );
                } catch (InterruptedException e)
                {
                    throw new RuntimeException( e );
                }
            }
        } );

        // When
        latch2.await();
        assertFalse( stopping.isDone() );
        latch1.countDown();
        stopping.get( 10, SECONDS );

        // Then
        assertTrue( stopping.isDone() );
        assertNull( stopping.get() );
        assertTrue( job1.executed );
        assertTrue( job2.executed );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.sampling.IndexSamplingJobTrackerTest.shouldWaitForAllJobsToFinish.stopping.submit.new Runnable with () -> {latch2.countDown(); in method public shouldWaitForAllJobsToFinish() : void from class org.neo4j.kernel.impl.api.index.sampling.IndexSamplingJobTrackerTest


    @Test(timeout = 1000)
    public void shouldBlockUniqueIndexSeekFromCompetingTransaction() throws Exception
    {
        // This is the interleaving that we are trying to verify works correctly:
        // ----------------------------------------------------------------------
        // Thread1 (main)        : Thread2
        // create unique node    :
        // lookup(node)          :
        // open start latch ----->
        //    |                  : lookup(node)
        // wait for T2 to block  :      |
        //                       :    *block*
        // commit --------------->   *unblock*
        // wait for T2 end latch :      |
        //                       : finish failed transaction
        //                       : open end latch
        // *unblock* <-------------‘
        // assert that we complete before timeout
        final DoubleLatch latch = new DoubleLatch();

        DependencyResolver resolver = db.getDependencyResolver();
        Locks manager = resolver.resolveDependency( Locks.class );

        final IndexDescriptor index = createUniquenessConstraint();
        final String value = "value";

        DataWriteOperations dataStatement = dataWriteOperationsInNewTransaction();
        long nodeId = dataStatement.nodeCreate();
        dataStatement.nodeAddLabel( nodeId, labelId );

        // This adds the node to the unique index and should take an index write lock
        dataStatement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, value ) );

        Runnable runnableForThread2 = () ->
        {
            latch.waitForAllToStart();
            try ( Transaction tx = db.beginTx() )
            {
                try ( Statement statement1 = statementContextSupplier.get() )
                {
                    statement1.readOperations().nodeGetFromUniqueIndexSeek( index, value );
                }
                tx.success();
            }
            catch ( IndexNotFoundKernelException | IndexBrokenKernelException e )
            {
                throw new RuntimeException( e );
            }
            finally
            {
                latch.finish();
            }
        };
        Thread thread2 = new Thread( runnableForThread2, "Transaction Thread 2" );
        thread2.start();
        latch.startAndWaitForAllToStart();

        //noinspection UnusedLabel
        spinUntilBlocking:
        for (; ; )
        {
            if(thread2.getState() == Thread.State.TIMED_WAITING || thread2.getState() == Thread.State.WAITING)
            {
                break;
            }
            Thread.yield();
        }

        commit();
        latch.waitForAllToFinish();
    }

    @Test(timeout = 1000)
    public void shouldBlockUniqueIndexSeekFromCompetingTransaction() throws Exception
    {
        // This is the interleaving that we are trying to verify works correctly:
        // ----------------------------------------------------------------------
        // Thread1 (main)        : Thread2
        // create unique node    :
        // lookup(node)          :
        // open start latch ----->
        //    |                  : lookup(node)
        // wait for T2 to block  :      |
        //                       :    *block*
        // commit --------------->   *unblock*
        // wait for T2 end latch :      |
        //                       : finish failed transaction
        //                       : open end latch
        // *unblock* <-------------‘
        // assert that we complete before timeout
        final DoubleLatch latch = new DoubleLatch();

        DependencyResolver resolver = db.getDependencyResolver();
        Locks manager = resolver.resolveDependency( Locks.class );

        final IndexDescriptor index = createUniquenessConstraint();
        final String value = "value";

        DataWriteOperations dataStatement = dataWriteOperationsInNewTransaction();
        long nodeId = dataStatement.nodeCreate();
        dataStatement.nodeAddLabel( nodeId, labelId );

        // This adds the node to the unique index and should take an index write lock
        dataStatement.nodeSetProperty( nodeId, Property.stringProperty( propertyKeyId, value ) );

        Runnable runnableForThread2 = new Runnable()
        {
            @Override
            public void run()
            {
                latch.awaitStart();
                try ( Transaction tx = db.beginTx() )
                {
                    try ( Statement statement = statementContextSupplier.get() )
                    {
                        statement.readOperations().nodeGetFromUniqueIndexSeek( index, value );
                    }
                    tx.success();
                }
                catch ( IndexNotFoundKernelException | IndexBrokenKernelException e )
                {
                    throw new RuntimeException( e );
                }
                finally
                {
                    latch.finish();
                }
            }
        };
        Thread thread2 = new Thread( runnableForThread2, "Transaction Thread 2" );
        thread2.start();
        latch.start();

        spinUntilBlocking:
        for (; ; )
        {
            if(thread2.getState() == Thread.State.TIMED_WAITING || thread2.getState() == Thread.State.WAITING)
            {
                break;
            }
            Thread.yield();
        }

        commit();
        latch.awaitFinish();
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.NodeGetUniqueFromIndexSeekIT.shouldBlockUniqueIndexSeekFromCompetingTransaction.runnableForThread2.new Runnable with () -> {latch.waitForAllToStart(); in method public shouldBlockUniqueIndexSeekFromCompetingTransaction() : void from class org.neo4j.kernel.impl.api.integrationtest.NodeGetUniqueFromIndexSeekIT


        int add( Hit hit, int atDepth )
        {
            Collection<Hit> depthHits = hits.get( atDepth );
            if ( depthHits == null )
            {
                depthHits = new HashSet<>();
                hits.put( atDepth, depthHits );
            }
            if ( depthHits.add( hit ) )
            {
                totalHitCount++;
            }
            if ( lowestDepth == 0 || atDepth < lowestDepth )
            {
                lowestDepth = atDepth;
            }
            return totalHitCount;
        }

        int add( Hit hit, int atDepth )
        {
            Collection<Hit> depthHits = hits.get( atDepth );
            if ( depthHits == null )
            {
                depthHits = new HashSet<Hit>();
                hits.put( atDepth, depthHits );
            }
            if ( depthHits.add( hit ) )
            {
                totalHitCount++;
            }
            if ( lowestDepth == 0 || atDepth < lowestDepth )
            {
                lowestDepth = atDepth;
            }
            return totalHitCount;
        }

Replace Generic With Diamond HashSet<Hit> with HashSet<> in method package add(hit Hit, atDepth int) : int from class org.neo4j.graphalgo.impl.path.ShortestPath.Hits


    private static Collection<Path> hitsToPaths( Collection<Hit> depthHits, Node start, Node end, boolean stopAsap )
    {
        LinkedHashMap<String,Path> paths = new LinkedHashMap<>();
        for ( Hit hit : depthHits )
        {
            for ( Path path : hitToPaths( hit, start, end, stopAsap ) )
            {
                paths.put( path.toString(), path );
            }
        }
        return paths.values();
    }

    private static Collection<Path> hitsToPaths( Collection<Hit> depthHits, Node start, Node end, boolean stopAsap )
    {
        LinkedHashMap<String,Path> paths = new LinkedHashMap<String,Path>();
        for ( Hit hit : depthHits )
        {
            for ( Path path : hitToPaths( hit, start, end, stopAsap ) )
            {
                paths.put( path.toString(), path );
            }
        }
        return paths.values();
    }

Replace Generic With Diamond LinkedHashMap<String,Path> with LinkedHashMap<> in method private hitsToPaths(depthHits Collection<Hit>, start Node, end Node, stopAsap boolean) : Collection<Path> from class org.neo4j.graphalgo.impl.path.ShortestPath


    private static Collection<Path> hitToPaths( Hit hit, Node start, Node end, boolean stopAsap )
    {
        Collection<Path> paths = new ArrayList<>();
        Iterable<LinkedList<Relationship>> startPaths = getPaths( hit.connectingNode, hit.start, stopAsap );
        Iterable<LinkedList<Relationship>> endPaths = getPaths( hit.connectingNode, hit.end, stopAsap );
        for ( LinkedList<Relationship> startPath : startPaths )
        {
            PathImpl.Builder startBuilder = toBuilder( start, startPath );
            for ( LinkedList<Relationship> endPath : endPaths )
            {
                PathImpl.Builder endBuilder = toBuilder( end, endPath );
                Path path = startBuilder.build( endBuilder );
                paths.add( path );
            }
        }
        return paths;
    }

    private static Collection<Path> hitToPaths( Hit hit, Node start, Node end, boolean stopAsap )
    {
        Collection<Path> paths = new ArrayList<Path>();
        Iterable<LinkedList<Relationship>> startPaths = getPaths( hit.connectingNode, hit.start, stopAsap );
        Iterable<LinkedList<Relationship>> endPaths = getPaths( hit.connectingNode, hit.end, stopAsap );
        for ( LinkedList<Relationship> startPath : startPaths )
        {
            PathImpl.Builder startBuilder = toBuilder( start, startPath );
            for ( LinkedList<Relationship> endPath : endPaths )
            {
                PathImpl.Builder endBuilder = toBuilder( end, endPath );
                Path path = startBuilder.build( endBuilder );
                paths.add( path );
            }
        }
        return paths;
    }

Replace Generic With Diamond ArrayList<Path> with ArrayList<> in method private hitToPaths(hit Hit, start Node, end Node, stopAsap boolean) : Collection<Path> from class org.neo4j.graphalgo.impl.path.ShortestPath


    private void rollbackSuspended( Predicate<TransactionMarker> predicate )
    {
        Set<Long> candidateTransactionIdsToRollback = new HashSet<>();

        for ( Map.Entry<Long, TransactionMarker> entry : registry.entrySet() )
        {
            TransactionMarker marker = entry.getValue();
            if (marker.isSuspended() && predicate.test(marker))
            {
                candidateTransactionIdsToRollback.add( entry.getKey() );
            }
        }

        for ( long id : candidateTransactionIdsToRollback )
        {
            TransactionHandle handle;
            try
            {
                handle = acquire( id );
            }
            catch ( TransactionLifecycleException invalidTransactionId )
            {
                // Allow this - someone snatched the transaction from under our feet,
                continue;
            }
            try
            {
                handle.forceRollback();
                log.info( format( "Transaction with id %d has been automatically rolled back.", id ) );
            }
            catch ( Throwable e )
            {
                log.error( format( "Transaction with id %d failed to roll back.", id ), e );
            }
            finally
            {
                forget( id );
            }
        }
    }

    private void rollbackSuspended( Predicate<TransactionMarker> predicate )
    {
        Set<Long> candidateTransactionIdsToRollback = new HashSet<Long>();

        for ( Map.Entry<Long, TransactionMarker> entry : registry.entrySet() )
        {
            TransactionMarker marker = entry.getValue();
            if (marker.isSuspended() && predicate.test(marker))
            {
                candidateTransactionIdsToRollback.add( entry.getKey() );
            }
        }

        for ( long id : candidateTransactionIdsToRollback )
        {
            TransactionHandle handle;
            try
            {
                handle = acquire( id );
            }
            catch ( TransactionLifecycleException invalidTransactionId )
            {
                // Allow this - someone snatched the transaction from under our feet,
                continue;
            }
            try
            {
                handle.forceRollback();
                log.info( format( "Transaction with id %d has been automatically rolled back.", id ) );
            }
            catch ( Throwable e )
            {
                log.error( format( "Transaction with id %d failed to roll back.", id ), e );
            }
            finally
            {
                forget( id );
            }
        }
    }

Replace Generic With Diamond HashSet<Long> with HashSet<> in method private rollbackSuspended(predicate Predicate<TransactionMarker>) : void from class org.neo4j.server.rest.transactional.TransactionHandleRegistry


    @Test
    public void shouldBeAbleToStorePropertiesInAnExistingNode() throws
            PropertyValueException, NodeNotFoundException
    {
        long nodeId = graphdbHelper.createNode();
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "baz", 17 );
        actions.setAllNodeProperties( nodeId, properties );

        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node node = database.getGraph().getNodeById( nodeId );
            assertHasProperties( node, properties );
        }
    }

    @Test
    public void shouldBeAbleToStorePropertiesInAnExistingNode() throws
            PropertyValueException, NodeNotFoundException
    {
        long nodeId = graphdbHelper.createNode();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "baz", 17 );
        actions.setAllNodeProperties( nodeId, properties );

        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node node = database.getGraph().getNodeById( nodeId );
            assertHasProperties( node, properties );
        }
    }

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


    @Test(expected = PropertyValueException.class)
    public void shouldFailOnTryingToStoreMixedArraysAsAProperty() throws Exception
    {
        long nodeId = graphdbHelper.createNode();
        Map<String, Object> properties = new HashMap<>();
        Object[] dodgyArray = new Object[3];
        dodgyArray[0] = 0;
        dodgyArray[1] = 1;
        dodgyArray[2] = "two";
        properties.put( "foo", dodgyArray );

        actions.setAllNodeProperties( nodeId, properties );
    }

    @Test(expected = PropertyValueException.class)
    public void shouldFailOnTryingToStoreMixedArraysAsAProperty() throws Exception
    {
        long nodeId = graphdbHelper.createNode();
        Map<String, Object> properties = new HashMap<String, Object>();
        Object[] dodgyArray = new Object[3];
        dodgyArray[0] = 0;
        dodgyArray[1] = 1;
        dodgyArray[2] = "two";
        properties.put( "foo", dodgyArray );

        actions.setAllNodeProperties( nodeId, properties );
    }

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


    @Test
    public void shouldOverwriteExistingProperties() throws PropertyValueException,
            NodeNotFoundException
    {

        long nodeId;
        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node node = database.getGraph().createNode();
            node.setProperty( "remove me", "trash" );
            nodeId = node.getId();
            tx.success();
        }

        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "baz", 17 );
        actions.setAllNodeProperties( nodeId, properties );
        try (Transaction tx = database.getGraph().beginTx())
        {
            Node node = database.getGraph().getNodeById( nodeId );
            assertHasProperties( node, properties );
            assertNull( node.getProperty( "remove me", null ) );
        }
    }

    @Test
    public void shouldOverwriteExistingProperties() throws PropertyValueException,
            NodeNotFoundException
    {

        long nodeId;
        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node node = database.getGraph().createNode();
            node.setProperty( "remove me", "trash" );
            nodeId = node.getId();
            tx.success();
        }

        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "baz", 17 );
        actions.setAllNodeProperties( nodeId, properties );
        try (Transaction tx = database.getGraph().beginTx())
        {
            Node node = database.getGraph().getNodeById( nodeId );
            assertHasProperties( node, properties );
            assertNull( node.getProperty( "remove me", null ) );
        }
    }

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


    @Test
    public void shouldBeAbleToGetPropertiesOnNode() throws NodeNotFoundException
    {

        long nodeId;
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "neo", "Thomas A. Anderson" );
        properties.put( "number", 15L );
        Node node;
        try ( Transaction tx = database.getGraph().beginTx() )
        {
            node = database.getGraph().createNode();
            for ( Map.Entry<String, Object> entry : properties.entrySet() )
            {
                node.setProperty( entry.getKey(), entry.getValue() );
            }
            nodeId = node.getId();
            tx.success();
        }

        try ( Transaction transaction = graph.beginTx() )
        {
            assertEquals( properties, serialize( actions.getAllNodeProperties( nodeId ) ) );
        }
    }

    @Test
    public void shouldBeAbleToGetPropertiesOnNode() throws NodeNotFoundException
    {

        long nodeId;
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "neo", "Thomas A. Anderson" );
        properties.put( "number", 15L );
        Node node;
        try ( Transaction tx = database.getGraph().beginTx() )
        {
            node = database.getGraph().createNode();
            for ( Map.Entry<String, Object> entry : properties.entrySet() )
            {
                node.setProperty( entry.getKey(), entry.getValue() );
            }
            nodeId = node.getId();
            tx.success();
        }

        try ( Transaction transaction = graph.beginTx() )
        {
            assertEquals( properties, serialize( actions.getAllNodeProperties( nodeId ) ) );
        }
    }

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


    @Test
    public void shouldBeAbleToRemoveNodeProperties() throws Exception
    {
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        long nodeId = createNode( properties );
        actions.removeAllNodeProperties( nodeId );

        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node node = database.getGraph().getNodeById( nodeId );
            assertEquals( false, node.getPropertyKeys()
                    .iterator()
                    .hasNext() );
            tx.success();
        }
    }

    @Test
    public void shouldBeAbleToRemoveNodeProperties() throws Exception
    {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        long nodeId = createNode( properties );
        actions.removeAllNodeProperties( nodeId );

        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node node = database.getGraph().getNodeById( nodeId );
            assertEquals( false, node.getPropertyKeys()
                    .iterator()
                    .hasNext() );
            tx.success();
        }
    }

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


    @Test
    public void shouldStoreSuppliedPropertiesWhenCreatingRelationship() throws Exception
    {
        Map<String, Object> properties = new HashMap<>();
        properties.put( "string", "value" );
        properties.put( "integer", 17 );
        long relId = actions.createRelationship( graphdbHelper.createNode(), graphdbHelper.createNode(), "LOVES",
                properties )
                .getId();

        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Relationship rel = database.getGraph().getRelationshipById( relId );
            for ( String key : rel.getPropertyKeys() )
            {
                assertTrue( "extra property stored", properties.containsKey( key ) );
            }
            for ( Map.Entry<String, Object> entry : properties.entrySet() )
            {
                assertEquals( entry.getValue(), rel.getProperty( entry.getKey() ) );
            }
        }
    }

    @Test
    public void shouldStoreSuppliedPropertiesWhenCreatingRelationship() throws Exception
    {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "string", "value" );
        properties.put( "integer", 17 );
        long relId = actions.createRelationship( graphdbHelper.createNode(), graphdbHelper.createNode(), "LOVES",
                properties )
                .getId();

        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Relationship rel = database.getGraph().getRelationshipById( relId );
            for ( String key : rel.getPropertyKeys() )
            {
                assertTrue( "extra property stored", properties.containsKey( key ) );
            }
            for ( Map.Entry<String, Object> entry : properties.entrySet() )
            {
                assertEquals( entry.getValue(), rel.getProperty( entry.getKey() ) );
            }
        }
    }

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


    @Test
    public void shouldBeAbleToRemoveNodeProperty() throws Exception
    {
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        long nodeId = createNode( properties );
        actions.removeNodeProperty( nodeId, "foo" );

        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node node = database.getGraph().getNodeById( nodeId );
            assertEquals( 15, node.getProperty( "number" ) );
            assertEquals( false, node.hasProperty( "foo" ) );
            tx.success();
        }
    }

    @Test
    public void shouldBeAbleToRemoveNodeProperty() throws Exception
    {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        long nodeId = createNode( properties );
        actions.removeNodeProperty( nodeId, "foo" );

        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node node = database.getGraph().getNodeById( nodeId );
            assertEquals( 15, node.getProperty( "number" ) );
            assertEquals( false, node.hasProperty( "foo" ) );
            tx.success();
        }
    }

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


    @Test
    public void shouldReturnTrueIfNodePropertyRemoved() throws Exception
    {
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        long nodeId = createNode( properties );
        actions.removeNodeProperty( nodeId, "foo" );
    }

    @Test
    public void shouldReturnTrueIfNodePropertyRemoved() throws Exception
    {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        long nodeId = createNode( properties );
        actions.removeNodeProperty( nodeId, "foo" );
    }

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


    @Test(expected = NoSuchPropertyException.class)
    public void shouldReturnFalseIfNodePropertyNotRemoved() throws Exception
    {
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        long nodeId = createNode( properties );
        actions.removeNodeProperty( nodeId, "baz" );
    }

    @Test(expected = NoSuchPropertyException.class)
    public void shouldReturnFalseIfNodePropertyNotRemoved() throws Exception
    {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        long nodeId = createNode( properties );
        actions.removeNodeProperty( nodeId, "baz" );
    }

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


    @Test
    public void shouldBeAbleToGetPropertiesOnRelationship() throws Exception
    {

        long relationshipId;
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "neo", "Thomas A. Anderson" );
        properties.put( "number", 15L );
        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node startNode = database.getGraph().createNode();
            Node endNode = database.getGraph().createNode();
            Relationship relationship = startNode.createRelationshipTo( endNode,
                    RelationshipType.withName( "knows" ) );
            for ( Map.Entry<String, Object> entry : properties.entrySet() )
            {
                relationship.setProperty( entry.getKey(), entry.getValue() );
            }
            relationshipId = relationship.getId();
            tx.success();
        }

        try ( Transaction transaction = graph.beginTx() )
        {
            assertEquals( properties, serialize( actions.getAllRelationshipProperties( relationshipId ) ) );
        }
    }

    @Test
    public void shouldBeAbleToGetPropertiesOnRelationship() throws Exception
    {

        long relationshipId;
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "neo", "Thomas A. Anderson" );
        properties.put( "number", 15L );
        try ( Transaction tx = database.getGraph().beginTx() )
        {
            Node startNode = database.getGraph().createNode();
            Node endNode = database.getGraph().createNode();
            Relationship relationship = startNode.createRelationshipTo( endNode,
                    RelationshipType.withName( "knows" ) );
            for ( Map.Entry<String, Object> entry : properties.entrySet() )
            {
                relationship.setProperty( entry.getKey(), entry.getValue() );
            }
            relationshipId = relationship.getId();
            tx.success();
        }

        try ( Transaction transaction = graph.beginTx() )
        {
            assertEquals( properties, serialize( actions.getAllRelationshipProperties( relationshipId ) ) );
        }
    }

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


    @Test
    public void shouldBeAbleToRetrieveASinglePropertyFromARelationship() throws Exception
    {
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "neo", "Thomas A. Anderson" );
        properties.put( "number", 15L );

        long relationshipId = graphdbHelper.createRelationship( "LOVES" );
        graphdbHelper.setRelationshipProperties( relationshipId, properties );

        Object relationshipProperty;
        try ( Transaction transaction = graph.beginTx() )
        {
            relationshipProperty = serialize( actions.getRelationshipProperty( relationshipId, "foo" ) );
        }
        assertEquals( "bar", relationshipProperty );
    }

    @Test
    public void shouldBeAbleToRetrieveASinglePropertyFromARelationship() throws Exception
    {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "neo", "Thomas A. Anderson" );
        properties.put( "number", 15L );

        long relationshipId = graphdbHelper.createRelationship( "LOVES" );
        graphdbHelper.setRelationshipProperties( relationshipId, properties );

        Object relationshipProperty;
        try ( Transaction transaction = graph.beginTx() )
        {
            relationshipProperty = serialize( actions.getRelationshipProperty( relationshipId, "foo" ) );
        }
        assertEquals( "bar", relationshipProperty );
    }

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


    @Test
    public void testCluster()
            throws ExecutionException, InterruptedException, URISyntaxException, TimeoutException
    {
        final long start = System.currentTimeMillis();
        timer.scheduleAtFixedRate( new TimerTask()
        {
            int i = 0;

            @Override
            public void run()
            {
                long now = System.currentTimeMillis() - start;
                logger.getLogger().fine( "Round " + i + ", time:" + now );

                script.tick( now );

                if ( ++i == 1000 )
                {
                    timer.cancel();
                }
            }
        }, 0, 10 );

        // Let messages settle
        Thread.sleep( script.getLength() + 1000 );

        logger.getLogger().fine( "All nodes leave" );

        // All leave
        for ( Cluster cluster : new ArrayList<>( in ) )
        {
            logger.getLogger().fine( "Leaving:" + cluster );
            cluster.leave();
            Thread.sleep( 100 );
        }
    }

    @Test
    public void testCluster()
            throws ExecutionException, InterruptedException, URISyntaxException, TimeoutException
    {
        final long start = System.currentTimeMillis();
        timer.scheduleAtFixedRate( new TimerTask()
        {
            int i = 0;

            @Override
            public void run()
            {
                long now = System.currentTimeMillis() - start;
                logger.getLogger().fine( "Round " + i + ", time:" + now );

                script.tick( now );

                if ( ++i == 1000 )
                {
                    timer.cancel();
                }
            }
        }, 0, 10 );

        // Let messages settle
        Thread.sleep( script.getLength() + 1000 );

        logger.getLogger().fine( "All nodes leave" );

        // All leave
        for ( Cluster cluster : new ArrayList<Cluster>( in ) )
        {
            logger.getLogger().fine( "Leaving:" + cluster );
            cluster.leave();
            Thread.sleep( 100 );
        }
    }

Replace Generic With Diamond ArrayList<Cluster> with ArrayList<> in method public testCluster() : void from class org.neo4j.cluster.protocol.cluster.ClusterNetworkTest


    private AtomicReference<ClusterConfiguration> clusterStateListener( final URI uri, final Cluster cluster )
    {
        final AtomicReference<ClusterConfiguration> config = new AtomicReference<>();
        cluster.addClusterListener( new ClusterListener()
        {
            @Override
            public void enteredCluster( ClusterConfiguration clusterConfiguration )
            {
                logger.getLogger().fine( uri + " entered cluster:" + clusterConfiguration.getMemberURIs() );
                config.set( new ClusterConfiguration( clusterConfiguration ) );
                in.add( cluster );
            }

            @Override
            public void joinedCluster( InstanceId instanceId, URI member )
            {
                logger.getLogger().fine( uri + " sees a join from " + instanceId + " at URI " + member.toString() );
                config.get().joined( instanceId, member );
            }

            @Override
            public void leftCluster( InstanceId instanceId, URI member )
            {
                logger.getLogger().fine( uri + " sees a leave:" + instanceId );
                config.get().left( instanceId );
            }

            @Override
            public void leftCluster()
            {
                out.add( cluster );
                config.set( null );
            }

            @Override
            public void elected( String role, InstanceId instanceId, URI electedMember )
            {
                logger.getLogger().fine( uri + " sees an election:" + instanceId +
                        "was elected as " + role + " on URI " + electedMember );
            }

            @Override
            public void unelected( String role, InstanceId instanceId, URI electedMember )
            {
                logger.getLogger().fine( uri + " sees an unelection:" + instanceId +
                        "was removed from " + role + " on URI " + electedMember );
            }
        } );
        return config;
    }

    private AtomicReference<ClusterConfiguration> clusterStateListener( final URI uri, final Cluster cluster )
    {
        final AtomicReference<ClusterConfiguration> config = new AtomicReference<ClusterConfiguration>();
        cluster.addClusterListener( new ClusterListener()
        {
            @Override
            public void enteredCluster( ClusterConfiguration clusterConfiguration )
            {
                logger.getLogger().fine( uri + " entered cluster:" + clusterConfiguration.getMemberURIs() );
                config.set( new ClusterConfiguration( clusterConfiguration ) );
                in.add( cluster );
            }

            @Override
            public void joinedCluster( InstanceId instanceId, URI member )
            {
                logger.getLogger().fine( uri + " sees a join from " + instanceId + " at URI " + member.toString() );
                config.get().joined( instanceId, member );
            }

            @Override
            public void leftCluster( InstanceId instanceId, URI member )
            {
                logger.getLogger().fine( uri + " sees a leave:" + instanceId );
                config.get().left( instanceId );
            }

            @Override
            public void leftCluster()
            {
                out.add( cluster );
                config.set( null );
            }

            @Override
            public void elected( String role, InstanceId instanceId, URI electedMember )
            {
                logger.getLogger().fine( uri + " sees an election:" + instanceId +
                        "was elected as " + role + " on URI " + electedMember );
            }

            @Override
            public void unelected( String role, InstanceId instanceId, URI electedMember )
            {
                logger.getLogger().fine( uri + " sees an unelection:" + instanceId +
                        "was removed from " + role + " on URI " + electedMember );
            }
        } );
        return config;
    }

Replace Generic With Diamond AtomicReference<ClusterConfiguration> with AtomicReference<> in method private clusterStateListener(uri URI, cluster Cluster) : AtomicReference<ClusterConfiguration> from class org.neo4j.cluster.protocol.cluster.ClusterNetworkTest


    public static ClusterManager.ManagedCluster buildClusterWithMasterDirIn( FileSystemAbstraction fs,
            final File legacyStoreDir, LifeSupport life,
            final Map<String,String> sharedConfig ) throws Throwable
    {
        File haRootDir = new File( legacyStoreDir.getParentFile(), "ha-migration" );
        fs.deleteRecursively( haRootDir );

        ClusterManager clusterManager = new ClusterManager.Builder( haRootDir )
                .withStoreDirInitializer( ( serverId, storeDir ) ->
                {
                    if ( serverId == 1 ) // Initialize dir only for master, others will copy store from it
                    {
                        FileUtils.copyRecursively( legacyStoreDir, storeDir );
                    }
                } )
                .withCluster( clusterOfSize( 3 ) )
                .withSharedConfig( sharedConfig )
                .build();

        life.add( clusterManager );
        life.start();

        return clusterManager.getCluster();
    }

    public static ClusterManager.ManagedCluster buildClusterWithMasterDirIn( FileSystemAbstraction fs,
            final File legacyStoreDir, LifeSupport life,
            final Map<String,String> sharedConfig ) throws Throwable
    {
        File haRootDir = new File( legacyStoreDir.getParentFile(), "ha-migration" );
        fs.deleteRecursively( haRootDir );

        ClusterManager clusterManager = new ClusterManager.Builder( haRootDir )
                .withStoreDirInitializer( new ClusterManager.StoreDirInitializer()
                {
                    @Override
                    public void initializeStoreDir( int serverId, File storeDir ) throws IOException
                    {
                        if ( serverId == 1 ) // Initialize dir only for master, others will copy store from it
                        {
                            FileUtils.copyRecursively( legacyStoreDir, storeDir );
                        }
                    }
                } )
                .withCluster( clusterOfSize( 3 ) )
                .withSharedConfig( sharedConfig )
                .build();

        life.add( clusterManager );
        life.start();

        return clusterManager.getCluster();
    }

Replace Anonymous With Lambda upgrade.StoreMigratorTestUtil.buildClusterWithMasterDirIn.clusterManager.build.withSharedConfig.withCluster.withStoreDirInitializer.new ClusterManager.StoreDirInitializer with (serverId, storeDir) -> {if(serverId == 1){FileUtils.copyRecursively(legacyStoreDir,storeDir); in method public buildClusterWithMasterDirIn(fs FileSystemAbstraction, legacyStoreDir File, life LifeSupport, sharedConfig Map<String,String>) : ClusterManager.ManagedCluster from class org.neo4j.upgrade.StoreMigratorTestUtil


    @Test
    public void testReplaceLocations() throws Exception {
        Map<Integer,String> map=new HashMap<>();
        map.put(100,"bar");
        assertEquals("foo", ops.replaceLocationPlaceholders("foo", map));
        assertEquals("foo bar", ops.replaceLocationPlaceholders("foo {100}", map));
        assertEquals("bar foo bar", ops.replaceLocationPlaceholders("{100} foo {100}", map));
        assertEquals("bar bar foo bar bar", ops.replaceLocationPlaceholders("bar {100} foo {100} bar", map));
    }

    @Test
    public void testReplaceLocations() throws Exception {
        Map<Integer,String> map=new HashMap<Integer, String>();
        map.put(100,"bar");
        assertEquals("foo", ops.replaceLocationPlaceholders("foo", map));
        assertEquals("foo bar", ops.replaceLocationPlaceholders("foo {100}", map));
        assertEquals("bar foo bar", ops.replaceLocationPlaceholders("{100} foo {100}", map));
        assertEquals("bar bar foo bar bar", ops.replaceLocationPlaceholders("bar {100} foo {100} bar", map));
    }

Replace Generic With Diamond HashMap<Integer,String> with HashMap<> in method public testReplaceLocations() : void from class org.neo4j.server.rest.batch.BatchOperationsTest


            @Override
            public InputIterator<InputNode> iterator()
            {
                return new InputGroupsDeserializer<>( nodeDataFactory.iterator(),
                        nodeHeaderFactory, config, idType, maxProcessors, (dataStream, dataHeader, decorator) ->
                        new InputEntityDeserializer<>( dataHeader, dataStream, config.delimiter(),
                                new InputNodeDeserialization( dataStream, dataHeader, groups, idType.idsAreExternal() ),
                                decorator, Validators.<InputNode>emptyValidator(), badCollector ), InputNode.class );
            }

            @Override
            public InputIterator<InputNode> iterator()
            {
                return new InputGroupsDeserializer<InputNode>( nodeDataFactory.iterator(),
                        nodeHeaderFactory, config, idType )
                {
                    @Override
                    protected InputEntityDeserializer<InputNode> entityDeserializer( CharSeeker dataStream,
                            Header dataHeader, Function<InputNode,InputNode> decorator )
                    {
                        return new InputEntityDeserializer<>( dataHeader, dataStream, config.delimiter(),
                                new InputNodeDeserialization( dataStream, dataHeader, groups, idType.idsAreExternal() ),
                                decorator, Validators.<InputNode>emptyValidator(), badCollector );
                    }
                };
            }

Replace Generic With Diamond InputGroupsDeserializer<InputNode> with InputGroupsDeserializer<> in method public iterator() : InputIterator<InputNode> from class org.neo4j.unsafe.impl.batchimport.input.csv.CsvInput.nodes.new InputIterable<InputNode>


    @Override
    public InputIterable<InputNode> nodes()
    {
        return new InputIterable<InputNode>()
        {
            @Override
            public InputIterator<InputNode> iterator()
            {
                return new InputGroupsDeserializer<>( nodeDataFactory.iterator(),
                        nodeHeaderFactory, config, idType, maxProcessors, (dataStream, dataHeader, decorator) ->
                        new InputEntityDeserializer<>( dataHeader, dataStream, config.delimiter(),
                                new InputNodeDeserialization( dataStream, dataHeader, groups, idType.idsAreExternal() ),
                                decorator, Validators.<InputNode>emptyValidator(), badCollector ), InputNode.class );
            }

            @Override
            public boolean supportsMultiplePasses()
            {
                return true;
            }
        };
    }

    @Override
    public InputIterable<InputNode> nodes()
    {
        return new InputIterable<InputNode>()
        {
            @Override
            public InputIterator<InputNode> iterator()
            {
                return new InputGroupsDeserializer<InputNode>( nodeDataFactory.iterator(),
                        nodeHeaderFactory, config, idType )
                {
                    @Override
                    protected InputEntityDeserializer<InputNode> entityDeserializer( CharSeeker dataStream,
                            Header dataHeader, Function<InputNode,InputNode> decorator )
                    {
                        return new InputEntityDeserializer<>( dataHeader, dataStream, config.delimiter(),
                                new InputNodeDeserialization( dataStream, dataHeader, groups, idType.idsAreExternal() ),
                                decorator, Validators.<InputNode>emptyValidator(), badCollector );
                    }
                };
            }

            @Override
            public boolean supportsMultiplePasses()
            {
                return true;
            }
        };
    }

Replace Generic With Diamond InputGroupsDeserializer<InputNode> with InputGroupsDeserializer<> in method public nodes() : InputIterable<InputNode> from class org.neo4j.unsafe.impl.batchimport.input.csv.CsvInput


            @Override
            public InputIterator<InputRelationship> iterator()
            {
                return new InputGroupsDeserializer<>( relationshipDataFactory.iterator(),
                        relationshipHeaderFactory, config, idType, maxProcessors, (dataStream, dataHeader, decorator) ->
                        new InputEntityDeserializer<>( dataHeader, dataStream, config.delimiter(),
                                new InputRelationshipDeserialization( dataStream, dataHeader, groups ),
                                decorator, new InputRelationshipValidator(), badCollector ), InputRelationship.class );
            }

            @Override
            public InputIterator<InputRelationship> iterator()
            {
                return new InputGroupsDeserializer<InputRelationship>( relationshipDataFactory.iterator(),
                        relationshipHeaderFactory, config, idType )
                {
                    @Override
                    protected InputEntityDeserializer<InputRelationship> entityDeserializer( CharSeeker dataStream,
                              Header dataHeader, Function<InputRelationship,InputRelationship> decorator )
                    {
                        return new InputEntityDeserializer<>( dataHeader, dataStream, config.delimiter(),
                                new InputRelationshipDeserialization( dataStream, dataHeader, groups ),
                                decorator, new InputRelationshipValidator(), badCollector );
                    }
                };
            }

Replace Generic With Diamond InputGroupsDeserializer<InputRelationship> with InputGroupsDeserializer<> in method public iterator() : InputIterator<InputRelationship> from class org.neo4j.unsafe.impl.batchimport.input.csv.CsvInput.relationships.new InputIterable<InputRelationship>


    @Override
    public InputIterable<InputRelationship> relationships()
    {
        return new InputIterable<InputRelationship>()
        {
            @Override
            public InputIterator<InputRelationship> iterator()
            {
                return new InputGroupsDeserializer<>( relationshipDataFactory.iterator(),
                        relationshipHeaderFactory, config, idType, maxProcessors, (dataStream, dataHeader, decorator) ->
                        new InputEntityDeserializer<>( dataHeader, dataStream, config.delimiter(),
                                new InputRelationshipDeserialization( dataStream, dataHeader, groups ),
                                decorator, new InputRelationshipValidator(), badCollector ), InputRelationship.class );
            }

            @Override
            public boolean supportsMultiplePasses()
            {
                return true;
            }
        };
    }

    @Override
    public InputIterable<InputRelationship> relationships()
    {
        return new InputIterable<InputRelationship>()
        {
            @Override
            public InputIterator<InputRelationship> iterator()
            {
                return new InputGroupsDeserializer<InputRelationship>( relationshipDataFactory.iterator(),
                        relationshipHeaderFactory, config, idType )
                {
                    @Override
                    protected InputEntityDeserializer<InputRelationship> entityDeserializer( CharSeeker dataStream,
                              Header dataHeader, Function<InputRelationship,InputRelationship> decorator )
                    {
                        return new InputEntityDeserializer<>( dataHeader, dataStream, config.delimiter(),
                                new InputRelationshipDeserialization( dataStream, dataHeader, groups ),
                                decorator, new InputRelationshipValidator(), badCollector );
                    }
                };
            }

            @Override
            public boolean supportsMultiplePasses()
            {
                return true;
            }
        };
    }

Replace Generic With Diamond InputGroupsDeserializer<InputRelationship> with InputGroupsDeserializer<> in method public relationships() : InputIterable<InputRelationship> from class org.neo4j.unsafe.impl.batchimport.input.csv.CsvInput


    @Test
    public void shouldBeAbleToAskForSourceInformationEvenBetweenTwoSources() throws Exception
    {
        // GIVEN
        List<DataFactory<InputNode>> data = asList( data( ":ID\n1" ), data( "2" ) );
        final AtomicInteger flips = new AtomicInteger();
        final AtomicReference<InputGroupsDeserializer<InputNode>> deserializerTestHack = new AtomicReference<>( null );
        InputGroupsDeserializer<InputNode> deserializer = new InputGroupsDeserializer<>(
                data.iterator(), defaultFormatNodeFileHeader(), lowBufferSize( COMMAS ), INTEGER,
                Runtime.getRuntime().availableProcessors(), (stream,header,decorator) ->
                {
                    // This is the point where the currentInput field in InputGroupsDeserializer was null
                    // so ensure that's no longer the case, just by poking those source methods right here and now.
                    if ( flips.get() == 0 )
                    {
                        assertNotNull( deserializerTestHack.get().sourceDescription() );
                    }
                    else
                    {
                        assertEquals( "" + flips.get(), deserializerTestHack.get().sourceDescription() );
                    }

                    flips.incrementAndGet();
                    @SuppressWarnings( "unchecked" )
                    InputEntityDeserializer<InputNode> result = mock( InputEntityDeserializer.class );
                    when( result.sourceDescription() ).thenReturn( String.valueOf( flips.get() ) );
                    return result;
                }, InputNode.class );
        deserializerTestHack.set( deserializer );

        // WHEN running through the iterator
        count( deserializer );

        // THEN there should have been two data source flips
        assertEquals( 2, flips.get() );
    }

    @Test
    public void shouldBeAbleToAskForSourceInformationEvenBetweenTwoSources() throws Exception
    {
        // GIVEN
        List<DataFactory<InputNode>> data = asList( data( ":ID\n1" ), data( "2" ) );
        final AtomicInteger flips = new AtomicInteger();
        InputGroupsDeserializer<InputNode> deserializer = new InputGroupsDeserializer<InputNode>(
                data.iterator(), defaultFormatNodeFileHeader(), lowBufferSize( COMMAS ), INTEGER )
        {
            @Override
            protected InputEntityDeserializer<InputNode> entityDeserializer( CharSeeker dataStream, Header dataHeader,
                    Function<InputNode,InputNode> decorator )
            {
                // This is the point where the currentInput field in InputGroupsDeserializer was null
                // so ensure that's no longer the case, just by poking those source methods right here and now.
                if ( flips.get() == 0 )
                {
                    assertNotNull( sourceDescription() );
                }
                else
                {
                    assertEquals( "" + flips.get(), sourceDescription() );
                }

                flips.incrementAndGet();
                @SuppressWarnings( "unchecked" )
                InputEntityDeserializer<InputNode> result = mock( InputEntityDeserializer.class );
                when( result.sourceDescription() ).thenReturn( String.valueOf( flips.get() ) );
                return result;
            }
        };

        // WHEN running through the iterator
        count( deserializer );

        // THEN there should have been two data source flips
        assertEquals( 2, flips.get() );
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.input.csv.InputGroupsDeserializerTest.shouldBeAbleToAskForSourceInformationEvenBetweenTwoSources.deserializer.new InputGroupsDeserializer<InputNode> with (stream, header, decorator) -> {if(flips.get() == 0){assertNotNull(deserializerTestHack.get().sourceDescription()); in method public shouldBeAbleToAskForSourceInformationEvenBetweenTwoSources() : void from class org.neo4j.unsafe.impl.batchimport.input.csv.InputGroupsDeserializerTest


    @Test
    public void shouldRecoverAfterCrashUnderLoad() throws Exception
    {
        EphemeralFileSystemAbstraction delegate = new EphemeralFileSystemAbstraction();
        AdversarialFileSystemAbstraction fsa = new AdversarialFileSystemAbstraction(
                new MethodGuardedAdversary( new CountingAdversary( 100, true ),
                        StoreChannel.class.getMethod( "writeAll", ByteBuffer.class ) ),
                delegate );

        long lastValue = 0;
        try ( LongState persistedState = new LongState( fsa, testDir.directory(), 14 ) )
        {
            while ( true ) // it will break from the Exception that AFS will throw
            {
                long tempValue = lastValue + 1;
                persistedState.setTheState( tempValue );
                lastValue = tempValue;
            }
        }
        catch ( Exception expected )
        {
            ensureStackTraceContainsExpectedMethod( expected.getStackTrace(), "writeAll" );
        }

        try( LongState restoredState = new LongState( delegate, testDir.directory(), 4 ) )
        {
            assertEquals( lastValue, restoredState.getTheState() );
        }
    }

    @Test
    public void shouldRecoverAfterCrashUnderLoad() throws Exception
    {
        EphemeralFileSystemAbstraction delegate = new EphemeralFileSystemAbstraction();
        AdversarialFileSystemAbstraction fsa = new AdversarialFileSystemAbstraction(
                new MethodGuardedAdversary( new CountingAdversary( 100, true ),
                        StoreChannel.class.getMethod( "writeAll", ByteBuffer.class ) ),
                delegate );

        LongState persistedState = new LongState( fsa, testDir.directory(), 14 );
        long lastValue = 0;

        try
        {
            while ( true ) // it will break from the Exception that AFS will throw
            {
                long tempValue = lastValue + 1;
                persistedState.setTheState( tempValue );
                lastValue = tempValue;
            }
        }
        catch ( Exception expected )
        {
            ensureStackTraceContainsExpectedMethod( expected.getStackTrace(), "writeAll" );
        }

        LongState restoredState = new LongState( delegate, testDir.directory(), 4 );
        assertEquals( lastValue, restoredState.getTheState() );
    }

Try With Resources try(LongState persistedState=new LongState(fsa,testDir.directory(),14)) in method public shouldRecoverAfterCrashUnderLoad() : void from class org.neo4j.coreedge.core.state.storage.DurableStateStorageIT


    @Test
    public void shouldProperlyRecoveryAfterCrashOnFileCreationDuringRotation() throws Exception
    {
        EphemeralFileSystemAbstraction normalFSA = new EphemeralFileSystemAbstraction();
        /*
         * Magic number warning. For a rotation threshold of 14, 998 operations on file A falls on truncation of the
         * file during rotation. This has been discovered via experimentation. The end result is that there is a
         * failure to create the file to rotate to. This should be recoverable.
         */
        AdversarialFileSystemAbstraction breakingFSA = new AdversarialFileSystemAbstraction(
                new MethodGuardedAdversary(
                        new CountingAdversary( 20, true ),
                        FileSystemAbstraction.class.getMethod( "truncate", File.class, long.class ) ),
                normalFSA );
        SelectiveFileSystemAbstraction combinedFSA = new SelectiveFileSystemAbstraction(
                new File( new File( testDir.directory(), "long-state" ), "long.a" ), breakingFSA, normalFSA );

        long lastValue = 0;
        try ( LongState persistedState = new LongState( combinedFSA, testDir.directory(), 14 ) )
        {
            while ( true ) // it will break from the Exception that AFS will throw
            {
                long tempValue = lastValue + 1;
                persistedState.setTheState( tempValue );
                lastValue = tempValue;
            }
        }
        catch ( Exception expected )
        {
            // this stack trace should contain FSA.truncate()
            ensureStackTraceContainsExpectedMethod( expected.getStackTrace(), "truncate" );
        }

        try( LongState restoredState = new LongState( normalFSA, testDir.directory(), 14 ) )
        {
            assertEquals( lastValue, restoredState.getTheState() );
        }
    }

    @Test
    public void shouldProperlyRecoveryAfterCrashOnFileCreationDuringRotation() throws Exception
    {
        EphemeralFileSystemAbstraction normalFSA = new EphemeralFileSystemAbstraction();
        /*
         * Magic number warning. For a rotation threshold of 14, 998 operations on file A falls on truncation of the
         * file during rotation. This has been discovered via experimentation. The end result is that there is a
         * failure to create the file to rotate to. This should be recoverable.
         */
        AdversarialFileSystemAbstraction breakingFSA = new AdversarialFileSystemAbstraction(
                new MethodGuardedAdversary(
                        new CountingAdversary( 20, true ),
                        FileSystemAbstraction.class.getMethod( "truncate", File.class, long.class ) ),
                normalFSA );
        SelectiveFileSystemAbstraction combinedFSA = new SelectiveFileSystemAbstraction(
                new File( new File( testDir.directory(), "long-state" ), "long.a" ), breakingFSA, normalFSA );

        LongState persistedState = new LongState( combinedFSA, testDir.directory(), 14 );
        long lastValue = 0;

        try
        {
            while ( true ) // it will break from the Exception that AFS will throw
            {
                long tempValue = lastValue + 1;
                persistedState.setTheState( tempValue );
                lastValue = tempValue;
            }
        }
        catch ( Exception expected )
        {
            // this stack trace should contain FSA.truncate()
            ensureStackTraceContainsExpectedMethod( expected.getStackTrace(), "truncate" );
        }

        LongState restoredState = new LongState( normalFSA, testDir.directory(), 14 );
        assertEquals( lastValue, restoredState.getTheState() );
    }

Try With Resources try(LongState persistedState=new LongState(combinedFSA,testDir.directory(),14)) in method public shouldProperlyRecoveryAfterCrashOnFileCreationDuringRotation() : void from class org.neo4j.coreedge.core.state.storage.DurableStateStorageIT


    @Test
    public void shouldProperlyRecoveryAfterCrashOnFileForceDuringWrite() throws Exception
    {
        EphemeralFileSystemAbstraction normalFSA = new EphemeralFileSystemAbstraction();
        /*
         * Magic number warning. For a rotation threshold of 14, 990 operations on file A falls on a force() of the
         * current active file. This has been discovered via experimentation. The end result is that there is a
         * flush (but not write) a value. This should be recoverable. Interestingly, the failure semantics are a bit
         * unclear on what should happen to that value. We assume that exception during persistence requires recovery
         * to discover if the last argument made it to disk or not. Since we use an EFSA, force is not necessary and
         * the value that caused the failure is actually "persisted" and recovered.
         */
        AdversarialFileSystemAbstraction breakingFSA = new AdversarialFileSystemAbstraction(
                new MethodGuardedAdversary(
                        new CountingAdversary( 40, true ),
                        StoreChannel.class.getMethod( "force", boolean.class ) ),
                normalFSA );
        SelectiveFileSystemAbstraction combinedFSA = new SelectiveFileSystemAbstraction(
                new File( new File( testDir.directory(), "long-state" ), "long.a" ), breakingFSA, normalFSA );

        long lastValue = 0;

        try ( LongState persistedState = new LongState( combinedFSA, testDir.directory(), 14 ) )
        {
            while ( true ) // it will break from the Exception that AFS will throw
            {
                long tempValue = lastValue + 1;
                persistedState.setTheState( tempValue );
                lastValue = tempValue;
            }
        }
        catch ( Exception expected )
        {
            // this stack trace should contain force()
            ensureStackTraceContainsExpectedMethod( expected.getStackTrace(), "force" );
        }

        try( LongState restoredState = new LongState( normalFSA, testDir.directory(), 14 ) )
        {
            assertThat( restoredState.getTheState(), greaterThanOrEqualTo( lastValue ) );
        }
    }

    @Test
    public void shouldProperlyRecoveryAfterCrashOnFileForceDuringWrite() throws Exception
    {
        EphemeralFileSystemAbstraction normalFSA = new EphemeralFileSystemAbstraction();
        /*
         * Magic number warning. For a rotation threshold of 14, 990 operations on file A falls on a force() of the
         * current active file. This has been discovered via experimentation. The end result is that there is a
         * flush (but not write) a value. This should be recoverable. Interestingly, the failure semantics are a bit
         * unclear on what should happen to that value. We assume that exception during persistence requires recovery
         * to discover if the last argument made it to disk or not. Since we use an EFSA, force is not necessary and
         * the value that caused the failure is actually "persisted" and recovered.
         */
        AdversarialFileSystemAbstraction breakingFSA = new AdversarialFileSystemAbstraction(
                new MethodGuardedAdversary(
                        new CountingAdversary( 40, true ),
                        StoreChannel.class.getMethod( "force", boolean.class ) ),
                normalFSA );
        SelectiveFileSystemAbstraction combinedFSA = new SelectiveFileSystemAbstraction(
                new File( new File( testDir.directory(), "long-state" ), "long.a" ), breakingFSA, normalFSA );

        LongState persistedState = new LongState( combinedFSA, testDir.directory(), 14 );
        long lastValue = 0;

        try
        {
            while ( true ) // it will break from the Exception that AFS will throw
            {
                long tempValue = lastValue + 1;
                persistedState.setTheState( tempValue );
                lastValue = tempValue;
            }
        }
        catch ( Exception expected )
        {
            // this stack trace should contain force()
            ensureStackTraceContainsExpectedMethod( expected.getStackTrace(), "force" );
        }

        LongState restoredState = new LongState( normalFSA, testDir.directory(), 14 );
        assertThat( restoredState.getTheState(), greaterThanOrEqualTo( lastValue ) );
    }

Try With Resources try(LongState persistedState=new LongState(combinedFSA,testDir.directory(),14)) in method public shouldProperlyRecoveryAfterCrashOnFileForceDuringWrite() : void from class org.neo4j.coreedge.core.state.storage.DurableStateStorageIT


    @Test
    public void shouldProperlyRecoveryAfterCloseOnActiveFileDuringRotation() throws Exception
    {
        EphemeralFileSystemAbstraction normalFSA = new EphemeralFileSystemAbstraction();
        AdversarialFileSystemAbstraction breakingFSA = new AdversarialFileSystemAbstraction(
                new MethodGuardedAdversary(
                        new CountingAdversary( 5, true ),
                        StoreChannel.class.getMethod( "close" ) ),
                normalFSA );
        SelectiveFileSystemAbstraction combinedFSA = new SelectiveFileSystemAbstraction(
                new File( new File( testDir.directory(), "long-state" ), "long.a" ), breakingFSA, normalFSA );

        long lastValue = 0;
        try ( LongState persistedState = new LongState( combinedFSA, testDir.directory(), 14 ) )
        {
            while ( true ) // it will break from the Exception that AFS will throw
            {
                long tempValue = lastValue + 1;
                persistedState.setTheState( tempValue );
                lastValue = tempValue;
            }
        }
        catch ( Exception expected )
        {
            // this stack trace should contain close()
            ensureStackTraceContainsExpectedMethod( expected.getStackTrace(), "close" );
        }

        try( LongState restoredState = new LongState( normalFSA, testDir.directory(), 14 ) )
        {
            assertThat( restoredState.getTheState(), greaterThanOrEqualTo( lastValue ) );
        }
    }

    @Test
    public void shouldProperlyRecoveryAfterCloseOnActiveFileDuringRotation() throws Exception
    {
        EphemeralFileSystemAbstraction normalFSA = new EphemeralFileSystemAbstraction();
        AdversarialFileSystemAbstraction breakingFSA = new AdversarialFileSystemAbstraction(
                new MethodGuardedAdversary(
                        new CountingAdversary( 5, true ),
                        StoreChannel.class.getMethod( "close" ) ),
                normalFSA );
        SelectiveFileSystemAbstraction combinedFSA = new SelectiveFileSystemAbstraction(
                new File( new File( testDir.directory(), "long-state" ), "long.a" ), breakingFSA, normalFSA );

        LongState persistedState = new LongState( combinedFSA, testDir.directory(), 14 );
        long lastValue = 0;

        try
        {
            while ( true ) // it will break from the Exception that AFS will throw
            {
                long tempValue = lastValue + 1;
                persistedState.setTheState( tempValue );
                lastValue = tempValue;
            }
        }
        catch ( Exception expected )
        {
            // this stack trace should contain close()
            ensureStackTraceContainsExpectedMethod( expected.getStackTrace(), "close" );
        }

        LongState restoredState = new LongState( normalFSA, testDir.directory(), 14 );
        assertThat( restoredState.getTheState(), greaterThanOrEqualTo( lastValue ) );
    }

Try With Resources try(LongState persistedState=new LongState(combinedFSA,testDir.directory(),14)) in method public shouldProperlyRecoveryAfterCloseOnActiveFileDuringRotation() : void from class org.neo4j.coreedge.core.state.storage.DurableStateStorageIT


    private WorkerCommand<Void,Void> createNode( final Label label, final String propertyKey,
            final Object propertyValue )
    {
        return state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                Node node = db.createNode( label );
                node.setProperty( propertyKey, propertyValue );
                tx.success();
            }
            return null;
        };
    }

    private WorkerCommand<Void,Void> createNode( final Label label, final String propertyKey,
            final Object propertyValue )
    {
        return new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    Node node = db.createNode( label );
                    node.setProperty( propertyKey, propertyValue );
                    tx.success();
                }
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.DeferringLocksIT.createNode.new WorkerCommand<Void,Void> with state -> {try(Transaction tx=db.beginTx())Node node=db.createNode(label); in method private createNode(label Label, propertyKey String, propertyValue Object) : WorkerCommand<Void,Void> from class org.neo4j.kernel.impl.locking.DeferringLocksIT


    private WorkerCommand<Void,Void> createIndexOn( final Label label, final String propertyKey )
    {
        return state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                db.schema().indexFor( label ).on( propertyKey ).create();
                tx.success();
            }
            return null;
        };
    }

    private WorkerCommand<Void,Void> createIndexOn( final Label label, final String propertyKey )
    {
        return new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    db.schema().indexFor( label ).on( propertyKey ).create();
                    tx.success();
                }
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.DeferringLocksIT.createIndexOn.new WorkerCommand<Void,Void> with state -> {try(Transaction tx=db.beginTx())db.schema().indexFor(label).on(propertyKey).create(); in method private createIndexOn(label Label, propertyKey String) : WorkerCommand<Void,Void> from class org.neo4j.kernel.impl.locking.DeferringLocksIT


    private WorkerCommand<Void,Void> createUniquenessConstraintOn( final Label label, final String propertyKey )
    {
        return state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                db.schema().constraintFor( label ).assertPropertyIsUnique( propertyKey ).create();
                tx.success();
            }
            return null;
        };
    }

    private WorkerCommand<Void,Void> createUniquenessConstraintOn( final Label label, final String propertyKey )
    {
        return new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    db.schema().constraintFor( label ).assertPropertyIsUnique( propertyKey ).create();
                    tx.success();
                }
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.DeferringLocksIT.createUniquenessConstraintOn.new WorkerCommand<Void,Void> with state -> {try(Transaction tx=db.beginTx())db.schema().constraintFor(label).assertPropertyIsUnique(propertyKey).create(); in method private createUniquenessConstraintOn(label Label, propertyKey String) : WorkerCommand<Void,Void> from class org.neo4j.kernel.impl.locking.DeferringLocksIT


    private WorkerCommand<Void,Void> createAndAwaitIndex( final Label label, final String key )
    {
        return state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                db.schema().indexFor( label ).on( key ).create();
                tx.success();
            }
            try ( Transaction ignore = db.beginTx() )
            {
                db.schema().awaitIndexesOnline( 1, TimeUnit.MINUTES );
            }
            return null;
        };
    }

    private WorkerCommand<Void,Void> createAndAwaitIndex( final Label label, final String key )
    {
        return new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    db.schema().indexFor( label ).on( key ).create();
                    tx.success();
                }
                try ( Transaction tx = db.beginTx() )
                {
                    db.schema().awaitIndexesOnline( 1, TimeUnit.MINUTES );
                }
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.DeferringLocksIT.createAndAwaitIndex.new WorkerCommand<Void,Void> with state -> {try(Transaction tx=db.beginTx())db.schema().indexFor(label).on(key).create(); in method private createAndAwaitIndex(label Label, key String) : WorkerCommand<Void,Void> from class org.neo4j.kernel.impl.locking.DeferringLocksIT


    private FullStoreChangeStream asStream( final List<NodeLabelUpdate> existingData )
    {
        return writer ->
        {
            long count = 0;
            for ( NodeLabelUpdate update : existingData )
            {
                writer.write( update );
                count++;
            }
            return count;
        };
    }

    private FullStoreChangeStream asStream( final List<NodeLabelUpdate> existingData )
    {
        return new FullStoreChangeStream()
        {
            @Override
            public long applyTo( LabelScanWriter writer ) throws IOException
            {
                long count = 0;
                for ( NodeLabelUpdate update : existingData )
                {
                    writer.write( update );
                    count++;
                }
                return count;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.labelscan.LuceneLabelScanStoreTest.asStream.new FullStoreChangeStream with writer -> {long count=0; in method private asStream(existingData List<NodeLabelUpdate>) : FullStoreChangeStream from class org.neo4j.kernel.api.impl.labelscan.LuceneLabelScanStoreTest


    @Override
    public RoleRecord newRole( String roleName, String... usernames ) throws IOException, InvalidArgumentsException
    {
        assertValidRoleName( roleName );
        for ( String username : usernames )
        {
            assertValidUsername( username );
        }

        SortedSet<String> userSet = new TreeSet<>( Arrays.asList( usernames ) );

        RoleRecord role = new RoleRecord.Builder().withName( roleName ).withUsers( userSet ).build();
        roleRepository.create( role );

        return role;
    }

    @Override
    public RoleRecord newRole( String roleName, String... usernames ) throws IOException, InvalidArgumentsException
    {
        assertValidRoleName( roleName );
        for ( String username : usernames )
        {
            assertValidUsername( username );
        }

        SortedSet<String> userSet = new TreeSet<String>( Arrays.asList( usernames ) );

        RoleRecord role = new RoleRecord.Builder().withName( roleName ).withUsers( userSet ).build();
        roleRepository.create( role );

        return role;
    }

Replace Generic With Diamond TreeSet<String> with TreeSet<> in method public newRole(roleName String, usernames String...) : RoleRecord from class org.neo4j.server.security.enterprise.auth.InternalFlatFileRealm


                    @Override
                    public Long apply( S subject )
                    {
                        try ( InternalTransaction tx = neo.startTransactionAsUser( subject ) )
                        {
                            barrier.reached();
                            neo.getGraph().execute( "CREATE (:Test { name: '" + neo.nameOf( subject ) + "-node'})" );
                            tx.success();
                            return 0L;
                        }
                        catch (Throwable t)
                        {
                            return 1L;
                        }
                    }

                    @Override
                    public Long apply( S subject )
                    {
                        try
                        {
                            InternalTransaction tx = neo.startTransactionAsUser( subject );
                            barrier.reached();
                            neo.getGraph().execute( "CREATE (:Test { name: '" + neo.nameOf( subject ) + "-node'})" );
                            tx.success();
                            tx.close();
                            return 0L;
                        }
                        catch (Throwable t)
                        {
                            return 1L;
                        }
                    }

Try With Resources try(InternalTransaction tx=neo.startTransactionAsUser(subject)) in method public apply(subject S) : Long from class org.neo4j.server.security.enterprise.auth.ThreadedTransactionCreate.execute.startTransaction.new NamedFunction<S,Long>


    @Test
    public void migratorShouldGetPickedUp()
    {

        // Given
        AnnotationBasedConfigurationMigrator migrator = new AnnotationBasedConfigurationMigrator( Arrays.asList( new Class<?>[]{SomeSettings.class} ) );

        // When
        migrator.apply( new HashMap<>(), null );

        // Then
        assertThat(wasCalled.get(), is(true));

    }

    @Test
    public void migratorShouldGetPickedUp()
    {

        // Given
        AnnotationBasedConfigurationMigrator migrator = new AnnotationBasedConfigurationMigrator( Arrays.asList( new Class<?>[]{SomeSettings.class} ) );

        // When
        migrator.apply( new HashMap<String,String>(), null );

        // Then
        assertThat(wasCalled.get(), is(true));

    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public migratorShouldGetPickedUp() : void from class org.neo4j.kernel.configuration.AnnotationBasedConfigurationMigratorTest


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

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

    private static Iterable<boolean[]> permutations( final int size )
    {
        final int max = 1 << size;
        return new Iterable<boolean[]>()
        {
            @Override
            public Iterator<boolean[]> iterator()
            {
                return new PrefetchingIterator<boolean[]>()
                {
                    int pos = 0;

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

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


    private Set<InstanceId> suspicionsFor( InstanceId uri )
    {
        Set<InstanceId> serverSuspicions = nodeSuspicions.get( uri );
        if ( serverSuspicions == null )
        {
            serverSuspicions = new HashSet<>();
            nodeSuspicions.put( uri, serverSuspicions );
        }
        return serverSuspicions;
    }

    private Set<InstanceId> suspicionsFor( InstanceId uri )
    {
        Set<InstanceId> serverSuspicions = nodeSuspicions.get( uri );
        if ( serverSuspicions == null )
        {
            serverSuspicions = new HashSet<InstanceId>();
            nodeSuspicions.put( uri, serverSuspicions );
        }
        return serverSuspicions;
    }

Replace Generic With Diamond HashSet<InstanceId> with HashSet<> in method private suspicionsFor(uri InstanceId) : Set<InstanceId> from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.context.HeartbeatContextImpl


            @Override
            protected GraphDatabaseService newDatabase( File storeDir, Map<String,String> config,
                    GraphDatabaseFacadeFactory.Dependencies dependencies )
            {
                Function<PlatformModule,EditionModule> factory =
                        ( platformModule ) -> new CommunityEditionModule( platformModule )
                        {

                            @Override
                            protected TransactionHeaderInformationFactory createHeaderInformationFactory()
                            {
                                return new TransactionHeaderInformationFactory.WithRandomBytes()
                                {
                                    @Override
                                    protected TransactionHeaderInformation createUsing( byte[] additionalHeader )
                                    {
                                        return new TransactionHeaderInformation( 1, 2, additionalHeader );
                                    }
                                };
                            }
                        };
                return new GraphDatabaseFacadeFactory( DatabaseInfo.COMMUNITY, factory )
                        .newFacade( storeDir, config, dependencies );
            }

            @Override
            protected GraphDatabaseService newDatabase( File storeDir, Map<String,String> config,
                    GraphDatabaseFacadeFactory.Dependencies dependencies )
            {
                return new CommunityFacadeFactory()
                {

                    @Override
                    protected EditionModule createEdition( PlatformModule platformModule )
                    {
                        return new CommunityEditionModule( platformModule )
                        {

                            @Override
                            protected TransactionHeaderInformationFactory createHeaderInformationFactory()
                            {
                                return new TransactionHeaderInformationFactory.WithRandomBytes()
                                {
                                    @Override
                                    protected TransactionHeaderInformation createUsing( byte[] additionalHeader )
                                    {
                                        return new TransactionHeaderInformation( 1, 2, additionalHeader );
                                    }
                                };
                            }
                        };
                    }
                }.newFacade( storeDir, config, dependencies );
            }

Replace Anonymous With Lambda org.neo4j.backup.TestBackup.startGraphDatabase.dbFactory.new TestGraphDatabaseFactory.newDatabase.newFacade.new CommunityFacadeFactory with (platformModule) -> new CommunityEditionModule(platformModule){ in method protected newDatabase(storeDir File, config Map<String,String>, dependencies GraphDatabaseFacadeFactory.Dependencies) : GraphDatabaseService from class org.neo4j.backup.TestBackup.startGraphDatabase.dbFactory.new TestGraphDatabaseFactory