    private WorkerCommand<Void,Void> receive( final int processors, final ProcessorStep<Void> step )
    {
        return state ->
        {
            step.receive( processors, null );
            return null;
        };
    }

    private WorkerCommand<Void,Void> receive( final int processors, final ProcessorStep<Void> step )
    {
        return new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                step.receive( processors, null );
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.staging.ProcessorStepTest.receive.new WorkerCommand<Void,Void> with state -> {step.receive(processors,null); in method private receive(processors int, step ProcessorStep<Void>) : WorkerCommand<Void,Void> from class org.neo4j.unsafe.impl.batchimport.staging.ProcessorStepTest


    @Test
    public void shouldReturnTicketsInOrder() throws Exception
    {
        // GIVEN
        int items = 1_000;
        ParkStrategy park = new ParkStrategy.Park( 2, MILLISECONDS );
        BiFunction<Integer,Void,Integer> processor = ( from, ignore ) ->
        {
            if ( ThreadLocalRandom.current().nextFloat() < 0.01f )
            {
                park.park( Thread.currentThread() );
            }
            return from * 2;
        };
        int processorCount = Runtime.getRuntime().availableProcessors();
        Future<Void> assertions;
        try ( TicketedProcessing<Integer,Void,Integer> processing = new TicketedProcessing<>(
                "Doubler", processorCount, processor, () -> null ) )
        {
            processing.processors( processorCount - processing.processors( 0 ) );

            // WHEN
            assertions = t2.execute( state ->
            {
                for ( int i = 0; i < items; i++ )
                {
                    Integer next = processing.next();
                    assertNotNull( next );
                    assertEquals( i * 2, next.intValue() );
                }
                assertNull( processing.next() );
                return null;
            } );
            for ( int i = 0; i < items; i++ )
            {
                processing.submit( i );
            }
        }

        // THEN
        assertions.get();
    }

    @Test
    public void shouldReturnTicketsInOrder() throws Exception
    {
        // GIVEN
        int items = 1_000;
        ParkStrategy park = new ParkStrategy.Park( 2, MILLISECONDS );
        BiFunction<Integer,Void,Integer> processor = ( from, ignore ) ->
        {
            if ( ThreadLocalRandom.current().nextFloat() < 0.01f )
            {
                park.park( Thread.currentThread() );
            }
            return from * 2;
        };
        int processorCount = Runtime.getRuntime().availableProcessors();
        Future<Void> assertions;
        try ( TicketedProcessing<Integer,Void,Integer> processing = new TicketedProcessing<>(
                "Doubler", processorCount, processor, () -> null ) )
        {
            processing.processors( processorCount - processing.processors( 0 ) );

            // WHEN
            assertions = t2.execute( new WorkerCommand<Void,Void>()
            {
                @Override
                public Void doWork( Void state ) throws Exception
                {
                    for ( int i = 0; i < items; i++ )
                    {
                        Integer next = processing.next();
                        assertNotNull( next );
                        assertEquals( i * 2, next.intValue() );
                    }
                    assertNull( processing.next() );
                    return null;
                }
            } );
            for ( int i = 0; i < items; i++ )
            {
                processing.submit( i );
            }
        }

        // THEN
        assertions.get();
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.staging.TicketedProcessingTest.shouldReturnTicketsInOrder.execute.new WorkerCommand<Void,Void> with state -> {for(int i=0; i < items; i++){Integer next=processing.next(); in method public shouldReturnTicketsInOrder() : void from class org.neo4j.unsafe.impl.batchimport.staging.TicketedProcessingTest


    @Test
    public void shouldNotBeAbleToSubmitTooFarAhead() throws Exception
    {
        // GIVEN
        try ( TicketedProcessing<StringJob,Void,Integer> processing = new TicketedProcessing<>( "Parser", 2,
                ( job, state ) ->
                {
                    awaitLatch( job.latch );
                    return parseInt( job.string );
                }, () -> null ) )
        {
            processing.processors( 1 ); // now at 2
            StringJob firstJob = new StringJob( "1" );
            processing.submit( firstJob );
            StringJob secondJob = new StringJob( "2" );
            processing.submit( secondJob );
            // now both processors have taken the 2 submitted jobs and so there should be 2 slots available

            // WHEN
            StringJob thirdJob = new StringJob( "3" );
            thirdJob.latch.countDown();
            processing.submit( thirdJob );
            StringJob fourthJob = new StringJob( "4" );
            fourthJob.latch.countDown();
            processing.submit( fourthJob );

            StringJob fifthJob = new StringJob( "5" );
            fifthJob.latch.countDown();
            Future<Void> fifthSubmit = t2.execute( state ->
            {
                processing.submit( fifthJob );
                return null;
            } );
            t2.get().waitUntilThreadState( Thread.State.TIMED_WAITING, Thread.State.WAITING );
            firstJob.latch.countDown();
            assertEquals( 1, processing.next().intValue() );
            fifthSubmit.get();
            secondJob.latch.countDown();
            assertEquals( 2, processing.next().intValue() );
            assertEquals( 3, processing.next().intValue() );
        }
    }

    @Test
    public void shouldNotBeAbleToSubmitTooFarAhead() throws Exception
    {
        // GIVEN
        try ( TicketedProcessing<StringJob,Void,Integer> processing = new TicketedProcessing<>( "Parser", 2,
                ( job, state ) ->
                {
                    awaitLatch( job.latch );
                    return parseInt( job.string );
                }, () -> null ) )
        {
            processing.processors( 1 ); // now at 2
            StringJob firstJob = new StringJob( "1" );
            processing.submit( firstJob );
            StringJob secondJob = new StringJob( "2" );
            processing.submit( secondJob );
            // now both processors have taken the 2 submitted jobs and so there should be 2 slots available

            // WHEN
            StringJob thirdJob = new StringJob( "3" );
            thirdJob.latch.countDown();
            processing.submit( thirdJob );
            StringJob fourthJob = new StringJob( "4" );
            fourthJob.latch.countDown();
            processing.submit( fourthJob );

            StringJob fifthJob = new StringJob( "5" );
            fifthJob.latch.countDown();
            Future<Void> fifthSubmit = t2.execute( new WorkerCommand<Void,Void>()
            {
                @Override
                public Void doWork( Void state ) throws Exception
                {
                    processing.submit( fifthJob );
                    return null;
                }
            } );
            t2.get().waitUntilThreadState( Thread.State.TIMED_WAITING, Thread.State.WAITING );
            firstJob.latch.countDown();
            assertEquals( 1, processing.next().intValue() );
            fifthSubmit.get();
            secondJob.latch.countDown();
            assertEquals( 2, processing.next().intValue() );
            assertEquals( 3, processing.next().intValue() );
        }
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.staging.TicketedProcessingTest.shouldNotBeAbleToSubmitTooFarAhead.fifthSubmit.execute.new WorkerCommand<Void,Void> with state -> {processing.submit(fifthJob); in method public shouldNotBeAbleToSubmitTooFarAhead() : void from class org.neo4j.unsafe.impl.batchimport.staging.TicketedProcessingTest


    public void add( final Node node, final String key, final Object value ) throws Exception
    {
        execute( (WorkerCommand<CommandState,Void>) state ->
        {
            state.index.add( node, key, value );
            return null;
        } );
    }

    public void add( final Node node, final String key, final Object value ) throws Exception
    {
        execute( new WorkerCommand<CommandState, Void>()
        {
            @Override
            public Void doWork( CommandState state )
            {
                state.index.add( node, key, value );
                return null;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.index.impl.lucene.legacy.WorkThread.add.execute.new WorkerCommand<CommandState,Void> with state -> {state.index.add(node,key,value); in method public add(node Node, key String, value Object) : void from class org.neo4j.index.impl.lucene.legacy.WorkThread


    public Future<Node> getOrCreate( final String key, final Object value, final Object initialValue ) throws Exception
    {
        return executeDontWait( state ->
        {
            UniqueFactory.UniqueNodeFactory factory = new UniqueFactory.UniqueNodeFactory( state.index )
            {
                @Override
                protected void initialize( Node node, Map<String, Object> properties )
                {
                    node.setProperty( key, initialValue );
                }
            };
            return factory.getOrCreate( key, value );
        } );
    }

    public Future<Node> getOrCreate( final String key, final Object value, final Object initialValue ) throws Exception
    {
        return executeDontWait( new WorkerCommand<CommandState, Node>()
        {
            @Override
            public Node doWork( CommandState state )
            {
                UniqueFactory.UniqueNodeFactory factory = new UniqueFactory.UniqueNodeFactory( state.index )
                {
                    @Override
                    protected void initialize( Node node, Map<String, Object> properties )
                    {
                        node.setProperty( key, initialValue );
                    }
                };
                return factory.getOrCreate( key, value );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.index.impl.lucene.legacy.WorkThread.getOrCreate.executeDontWait.new WorkerCommand<CommandState,Node> with state -> {UniqueFactory.UniqueNodeFactory factory=new UniqueFactory.UniqueNodeFactory(state.index){ in method public getOrCreate(key String, value Object, initialValue Object) : Future<Node> from class org.neo4j.index.impl.lucene.legacy.WorkThread


    private File snapshot( final File path ) throws IOException
    {
        File snapshotDir = new File( path, "snapshot-" + new Random().nextInt() );
        FileUtils.copyRecursively( path, snapshotDir, pathName ->
        {
            String subPath = pathName.getAbsolutePath().substring( path.getPath().length() ).replace( File.separatorChar, '/' );
            if ( "/store_lock".equals( subPath ) )
            {
                return false; // since the db is running, exclude the 'store_lock' file
            }
            if ( subPath.startsWith( "/schema/index/lucene/" ) || subPath.startsWith( "/schema/label/lucene/" ) )
            {
                return !subPath.endsWith( "/write.lock" ); // since the db is running, exclude lucene lock files
            }
            return true;
        } );
        return snapshotDir;
    }

    private File snapshot( final File path ) throws IOException
    {
        File snapshotDir = new File( path, "snapshot-" + new Random().nextInt() );
        FileUtils.copyRecursively( path, snapshotDir, new FileFilter()
        {
            @Override
            public boolean accept( File pathName )
            {
                String subPath = pathName.getAbsolutePath().substring( path.getPath().length() ).replace( File.separatorChar, '/' );
                if ( "/store_lock".equals( subPath ) )
                {
                    return false; // since the db is running, exclude the 'store_lock' file
                }
                if ( subPath.startsWith( "/schema/index/lucene/" ) || subPath.startsWith( "/schema/label/lucene/" ) )
                {
                    return !subPath.endsWith( "/write.lock" ); // since the db is running, exclude lucene lock files
                }
                return true;
            }
        } );
        return snapshotDir;
    }

Replace Anonymous With Lambda org.neo4j.index.recovery.UniqueIndexRecoveryTest.snapshot.copyRecursively.new FileFilter with pathName -> {String subPath=pathName.getAbsolutePath().substring(path.getPath().length()).replace(File.separatorChar,'/'); in method private snapshot(path File) : File from class org.neo4j.index.recovery.UniqueIndexRecoveryTest


    @Test
    public void shouldStopSamplingWhenIndexIsDropped() throws Exception
    {
        // given
        updateAndCommit( asList( add( nodeId, values ), add( nodeId2, values2 ) ) );

        // when
        IndexReader indexReader = accessor.newReader(); // needs to be acquired before drop() is called
        IndexSampler indexSampler = indexReader.createSampler();

        Future<Void> drop = threading.executeAndAwait( (IOFunction<Void,Void>) nothing ->
        {
            accessor.drop();
            return nothing;
        }, null, waitingWhileIn( TaskCoordinator.class, "awaitCompletion" ), 3, SECONDS );

        try ( IndexReader reader = indexReader /* do not inline! */ )
        {
            indexSampler.sampleIndex();
            fail( "expected exception" );
        }
        catch ( IndexNotFoundKernelException e )
        {
            assertEquals( "Index dropped while sampling.", e.getMessage() );
        }
        finally
        {
            drop.get();
        }
    }

    @Test
    public void shouldStopSamplingWhenIndexIsDropped() throws Exception
    {
        // given
        updateAndCommit( asList( add( nodeId, values ), add( nodeId2, values2 ) ) );

        // when
        IndexReader indexReader = accessor.newReader(); // needs to be acquired before drop() is called
        IndexSampler indexSampler = indexReader.createSampler();

        Future<Void> drop = threading.executeAndAwait( new IOFunction<Void,Void>()
        {
            @Override
            public Void apply( Void nothing ) throws IOException
            {
                accessor.drop();
                return nothing;
            }
        }, null, waitingWhileIn( TaskCoordinator.class, "awaitCompletion" ), 3, SECONDS );

        try ( IndexReader reader = indexReader /* do not inline! */ )
        {
            indexSampler.sampleIndex();
            fail( "expected exception" );
        }
        catch ( IndexNotFoundKernelException e )
        {
            assertEquals( "Index dropped while sampling.", e.getMessage() );
        }
        finally
        {
            drop.get();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.schema.DatabaseCompositeIndexAccessorTest.shouldStopSamplingWhenIndexIsDropped.drop.executeAndAwait.new IOFunction<Void,Void> with nothing -> {accessor.drop(); in method public shouldStopSamplingWhenIndexIsDropped() : void from class org.neo4j.kernel.api.impl.schema.DatabaseCompositeIndexAccessorTest


    private void killDb() throws Exception
    {
        if ( db != null )
        {
            fs.snapshot( () ->
            {
                db.shutdown();
                db = null;
            } );
        }
    }

    private void killDb() throws Exception
    {
        if ( db != null )
        {
            fs.snapshot( new Runnable()
            {
                @Override
                public void run()
                {
                    db.shutdown();
                    db = null;
                }
            } );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.schema.LuceneIndexRecoveryIT.killDb.snapshot.new Runnable with () -> {db.shutdown(); in method private killDb() : void from class org.neo4j.kernel.api.impl.schema.LuceneIndexRecoveryIT


    private void assertNodeIsNotIndexedOutsideThisTransaction() throws Exception
    {
        final Collection<Exception> problems = new HashSet<>();

        Thread thread = new Thread( () ->
        {
            try ( Transaction ignored = graphDatabaseService.beginTx() )
            {
                assertThat(
                        graphDatabaseService.index().forNodes( INDEX_NAME ).get( INDEX_KEY, INDEX_VALUE ).size(),
                        is( 0 ) );
            }
            catch ( Throwable t )
            {
                problems.add( new Exception( t ) );
            }
        } );
        thread.start();
        thread.join();

        if ( problems.size() > 0 )
        {
            throw problems.iterator().next();
        }
    }

    private void assertNodeIsNotIndexedOutsideThisTransaction() throws Exception
    {
        final Collection<Exception> problems = new HashSet<>();

        Thread thread = new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                try ( Transaction ignored = graphDatabaseService.beginTx() )
                {
                    assertThat(
                            graphDatabaseService.index().forNodes( INDEX_NAME ).get( INDEX_KEY, INDEX_VALUE ).size(),
                            is( 0 ) );
                }
                catch ( Throwable t )
                {
                    problems.add( new Exception( t ) );
                }
            }
        } );
        thread.start();
        thread.join();

        if ( problems.size() > 0 )
        {
            throw problems.iterator().next();
        }
    }

Replace Anonymous With Lambda visibility.TestDatasourceCommitOrderDataVisibility.assertNodeIsNotIndexedOutsideThisTransaction.thread.new Thread.new Runnable with () -> {try(Transaction ignored=graphDatabaseService.beginTx())assertThat(graphDatabaseService.index().forNodes(INDEX_NAME).get(INDEX_KEY,INDEX_VALUE).size(),is(0)); in method private assertNodeIsNotIndexedOutsideThisTransaction() : void from class visibility.TestDatasourceCommitOrderDataVisibility


    private void assertNodeIsUnchangedOutsideThisTransaction( final Node commonNode ) throws Exception
    {
        final Collection<Exception> problems = new HashSet<>();

        Thread thread = new Thread( () ->
        {
            try ( Transaction ignored = graphDatabaseService.beginTx() )
            {
                assertThat( commonNode.hasProperty( PROPERTY_NAME ), is( false ) );
            }
            catch ( Throwable t )
            {
                problems.add( new Exception( t ) );
            }
        } );
        thread.start();
        thread.join();

        if ( problems.size() > 0 )
        {
            throw problems.iterator().next();
        }
    }

    private void assertNodeIsUnchangedOutsideThisTransaction( final Node commonNode ) throws Exception
    {
        final Collection<Exception> problems = new HashSet<>();

        Thread thread = new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                try ( Transaction ignored = graphDatabaseService.beginTx() )
                {
                    assertThat( commonNode.hasProperty( PROPERTY_NAME ), is( false ) );
                }
                catch ( Throwable t )
                {
                    problems.add( new Exception( t ) );
                }
            }
        } );
        thread.start();
        thread.join();

        if ( problems.size() > 0 )
        {
            throw problems.iterator().next();
        }
    }

Replace Anonymous With Lambda visibility.TestDatasourceCommitOrderDataVisibility.assertNodeIsUnchangedOutsideThisTransaction.thread.new Thread.new Runnable with () -> {try(Transaction ignored=graphDatabaseService.beginTx())assertThat(commonNode.hasProperty(PROPERTY_NAME),is(false)); in method private assertNodeIsUnchangedOutsideThisTransaction(commonNode Node) : void from class visibility.TestDatasourceCommitOrderDataVisibility


    private void assertNodeIsIndexed( final Node commonNode ) throws Exception
    {
        final Collection<Exception> problems = new HashSet<>();

        Thread thread = new Thread( () ->
        {
            try ( Transaction ignored = graphDatabaseService.beginTx() )
            {
                Node node = graphDatabaseService.index().forNodes( INDEX_NAME ).get( INDEX_KEY, INDEX_VALUE )
                        .getSingle();
                assertThat( node, is( commonNode ) );
            }
            catch ( Throwable t )
            {
                problems.add( new Exception( t ) );
            }
        } );
        thread.start();
        thread.join();

        if ( problems.size() > 0 )
        {
            throw problems.iterator().next();
        }
    }

    private void assertNodeIsIndexed( final Node commonNode ) throws Exception
    {
        final Collection<Exception> problems = new HashSet<>();

        Thread thread = new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                try ( Transaction ignored = graphDatabaseService.beginTx() )
                {
                    Node node = graphDatabaseService.index().forNodes( INDEX_NAME ).get( INDEX_KEY, INDEX_VALUE )
                            .getSingle();
                    assertThat( node, is( commonNode ) );
                }
                catch ( Throwable t )
                {
                    problems.add( new Exception( t ) );
                }
            }
        } );
        thread.start();
        thread.join();

        if ( problems.size() > 0 )
        {
            throw problems.iterator().next();
        }
    }

Replace Anonymous With Lambda visibility.TestDatasourceCommitOrderDataVisibility.assertNodeIsIndexed.thread.new Thread.new Runnable with () -> {try(Transaction ignored=graphDatabaseService.beginTx())Node node=graphDatabaseService.index().forNodes(INDEX_NAME).get(INDEX_KEY,INDEX_VALUE).getSingle(); in method private assertNodeIsIndexed(commonNode Node) : void from class visibility.TestDatasourceCommitOrderDataVisibility


    private void assertNodeHasBeenUpdated( final Node commonNode ) throws Exception
    {
        final Collection<Exception> problems = new HashSet<>();

        Thread thread = new Thread( () ->
        {
            try ( Transaction ignored = graphDatabaseService.beginTx() )
            {
                assertThat( commonNode.getProperty( PROPERTY_NAME ), is( PROPERTY_VALUE ) );
            }
            catch ( Throwable t )
            {
                problems.add( new Exception( t ) );
            }
        } );
        thread.start();
        thread.join();

        if ( problems.size() > 0 )
        {
            throw problems.iterator().next();
        }
    }

    private void assertNodeHasBeenUpdated( final Node commonNode ) throws Exception
    {
        final Collection<Exception> problems = new HashSet<>();

        Thread thread = new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                try ( Transaction ignored = graphDatabaseService.beginTx() )
                {
                    assertThat( commonNode.getProperty( PROPERTY_NAME ), is( PROPERTY_VALUE ) );
                }
                catch ( Throwable t )
                {
                    problems.add( new Exception( t ) );
                }
            }
        } );
        thread.start();
        thread.join();

        if ( problems.size() > 0 )
        {
            throw problems.iterator().next();
        }
    }

Replace Anonymous With Lambda visibility.TestDatasourceCommitOrderDataVisibility.assertNodeHasBeenUpdated.thread.new Thread.new Runnable with () -> {try(Transaction ignored=graphDatabaseService.beginTx())assertThat(commonNode.getProperty(PROPERTY_NAME),is(PROPERTY_VALUE)); in method private assertNodeHasBeenUpdated(commonNode Node) : void from class visibility.TestDatasourceCommitOrderDataVisibility


    private void claimAndReleaseInSeparateThread( final MarshlandPool<Object> pool ) throws InterruptedException
    {
        Thread thread = new Thread( () ->
        {
            Object obj = pool.acquire();
            pool.release( obj );
        } );
        thread.start();
        thread.join();
    }

    private void claimAndReleaseInSeparateThread( final MarshlandPool<Object> pool ) throws InterruptedException
    {
        Thread thread = new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                Object obj = pool.acquire();
                pool.release( obj );
            }
        } );
        thread.start();
        thread.join();
    }

Replace Anonymous With Lambda org.neo4j.collection.pool.MarshlandPoolTest.claimAndReleaseInSeparateThread.thread.new Thread.new Runnable with () -> {Object obj=pool.acquire(); in method private claimAndReleaseInSeparateThread(pool MarshlandPool<Object>) : void from class org.neo4j.collection.pool.MarshlandPoolTest


    @Test
    public void shouldContainAddedValues_generated_1() throws Exception
    {
        // GIVEN
        PrimitiveLongSet set = newSet( 15 );
        Set<Long> expectedValues = new HashSet<>();
        long[] valuesToAdd = new long[] {
                1207043189,
                380713862,
                1902858197,
                1996873101,
                1357024628,
                1044248801,
                1558157493,
                2040311008,
                2017660098,
                1332670047,
                663662790,
                2063747422,
                1554358949,
                1761477445,
                1141526838,
                1698679618,
                1279767067,
                508574,
                2071755904
        };
        for ( long key : valuesToAdd )
        {
            set.add( key );
            expectedValues.add( key );
        }

        // WHEN/THEN
        boolean existedBefore = set.contains( 679990875 );
        boolean added = set.add( 679990875 );
        boolean existsAfter = set.contains( 679990875 );
        assertFalse( "679990875 should not exist before adding here", existedBefore );
        assertTrue( "679990875 should be reported as added here", added );
        assertTrue( "679990875 should exist", existsAfter );
        expectedValues.add( 679990875L );

        final Set<Long> visitedKeys = new HashSet<>();
        set.visitKeys( value ->
        {
            assertTrue( visitedKeys.add( value ) );
            return false;
        } );
        assertEquals( expectedValues, visitedKeys );
    }

    @Test
    public void shouldContainAddedValues_generated_1() throws Exception
    {
        // GIVEN
        PrimitiveLongSet set = newSet( 15 );
        Set<Long> expectedValues = new HashSet<>();
        long[] valuesToAdd = new long[] {
                1207043189,
                380713862,
                1902858197,
                1996873101,
                1357024628,
                1044248801,
                1558157493,
                2040311008,
                2017660098,
                1332670047,
                663662790,
                2063747422,
                1554358949,
                1761477445,
                1141526838,
                1698679618,
                1279767067,
                508574,
                2071755904
        };
        for ( long key : valuesToAdd )
        {
            set.add( key );
            expectedValues.add( key );
        }

        // WHEN/THEN
        boolean existedBefore = set.contains( 679990875 );
        boolean added = set.add( 679990875 );
        boolean existsAfter = set.contains( 679990875 );
        assertFalse( "679990875 should not exist before adding here", existedBefore );
        assertTrue( "679990875 should be reported as added here", added );
        assertTrue( "679990875 should exist", existsAfter );
        expectedValues.add( 679990875L );

        final Set<Long> visitedKeys = new HashSet<>();
        set.visitKeys( new PrimitiveLongVisitor()
        {
            @Override
            public boolean visited( long value )
            {
                assertTrue( visitedKeys.add( value ) );
                return false;
            }
        } );
        assertEquals( expectedValues, visitedKeys );
    }

Replace Anonymous With Lambda org.neo4j.collection.primitive.hopscotch.PrimitiveLongSetTest.shouldContainAddedValues_generated_1.visitKeys.new PrimitiveLongVisitor with value -> {assertTrue(visitedKeys.add(value)); in method public shouldContainAddedValues_generated_1() : void from class org.neo4j.collection.primitive.hopscotch.PrimitiveLongSetTest


    @Test( timeout = 60000 )
    public void stressLatch() throws Exception
    {
        final AtomicReference<BinaryLatch> latchRef = new AtomicReference<>( new BinaryLatch() );
        Runnable awaiter = () ->
        {
            BinaryLatch latch;
            while ( (latch = latchRef.get()) != null )
            {
                latch.await();
            }
        };

        int awaiters = 6;
        Future<?>[] futures = new Future<?>[awaiters];
        for ( int i = 0; i < awaiters; i++ )
        {
            futures[i] = executor.submit( awaiter );
        }

        ThreadLocalRandom rng = ThreadLocalRandom.current();
        for ( int i = 0; i < 500000; i++ )
        {
            latchRef.getAndSet( new BinaryLatch() ).release();
            spinwaitu( rng.nextLong( 0, 10 ) );
        }

        latchRef.getAndSet( null ).release();

        // None of the tasks we started should get stuck, e.g. miss a release signal:
        for ( Future<?> future : futures )
        {
            future.get();
        }
    }

    @Test( timeout = 60000 )
    public void stressLatch() throws Exception
    {
        final AtomicReference<BinaryLatch> latchRef = new AtomicReference<>( new BinaryLatch() );
        Runnable awaiter = new Runnable()
        {
            @Override
            public void run()
            {
                BinaryLatch latch;
                while ( (latch = latchRef.get()) != null )
                {
                    latch.await();
                }
            }
        };

        int awaiters = 6;
        Future<?>[] futures = new Future<?>[awaiters];
        for ( int i = 0; i < awaiters; i++ )
        {
            futures[i] = executor.submit( awaiter );
        }

        ThreadLocalRandom rng = ThreadLocalRandom.current();
        for ( int i = 0; i < 500000; i++ )
        {
            latchRef.getAndSet( new BinaryLatch() ).release();
            spinwaitu( rng.nextLong( 0, 10 ) );
        }

        latchRef.getAndSet( null ).release();

        // None of the tasks we started should get stuck, e.g. miss a release signal:
        for ( Future<?> future : futures )
        {
            future.get();
        }
    }

Replace Anonymous With Lambda org.neo4j.concurrent.BinaryLatchTest.stressLatch.awaiter.new Runnable with () -> {BinaryLatch latch; in method public stressLatch() : void from class org.neo4j.concurrent.BinaryLatchTest


    public static ListRepresentation numbers( final long... values )
    {
        return new ListRepresentation( RepresentationType.LONG, (Iterable<ValueRepresentation>) () ->
                new PrefetchingIterator<ValueRepresentation>()
                {
                    int pos;

                    @Override
                    protected ValueRepresentation fetchNextOrNull()
                    {
                        if ( pos >= values.length )
                        {
                            return null;
                        }
                        return ValueRepresentation.number( values[pos++] );
                    }
                } );
    }

    public static ListRepresentation numbers( final long... values )
    {
        return new ListRepresentation( RepresentationType.LONG, new Iterable<ValueRepresentation>()
        {
            @Override
            public Iterator<ValueRepresentation> iterator()
            {
                return new PrefetchingIterator<ValueRepresentation>()
                {
                    int pos;

                    @Override
                    protected ValueRepresentation fetchNextOrNull()
                    {
                        if ( pos >= values.length )
                        {
                            return null;
                        }
                        return ValueRepresentation.number( values[pos++] );
                    }
                };
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.repr.ListRepresentation.numbers.new ListRepresentation.new Iterable<ValueRepresentation> with () -> new PrefetchingIterator<ValueRepresentation>(){ in method public numbers(values long...) : ListRepresentation from class org.neo4j.server.rest.repr.ListRepresentation


    public static ListRepresentation numbers( final double[] values )
    {
        return new ListRepresentation( RepresentationType.DOUBLE,
                (Iterable<ValueRepresentation>) () -> new PrefetchingIterator<ValueRepresentation>()
                {
                    int pos;

                    @Override
                    protected ValueRepresentation fetchNextOrNull()
                    {
                        if ( pos >= values.length )
                        {
                            return null;
                        }
                        return ValueRepresentation.number( values[pos++] );
                    }
                } );
    }

    public static ListRepresentation numbers( final double[] values )
    {
        return new ListRepresentation( RepresentationType.DOUBLE,
                new Iterable<ValueRepresentation>()
                {
                    @Override
                    public Iterator<ValueRepresentation> iterator()
                    {
                        return new PrefetchingIterator<ValueRepresentation>()
                        {
                            int pos;

                            @Override
                            protected ValueRepresentation fetchNextOrNull()
                            {
                                if ( pos >= values.length )
                                {
                                    return null;
                                }
                                return ValueRepresentation.number( values[pos++] );
                            }
                        };
                    }
                } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.repr.ListRepresentation.numbers.new ListRepresentation.new Iterable<ValueRepresentation> with () -> new PrefetchingIterator<ValueRepresentation>(){ in method public numbers(values double[]) : ListRepresentation from class org.neo4j.server.rest.repr.ListRepresentation


    private Traverser traverseToDepth( GraphDatabaseService graphDb, final Node startNode, final int depth )
    {

        TraversalDescription traversalDescription = graphDb.traversalDescription()
                .expand( PathExpanders.allTypesAndDirections() )
                .depthFirst()
                .evaluator( path ->
                {
                    if ( path.length() < depth )
                    {
                        return Evaluation.INCLUDE_AND_CONTINUE;
                    }
                    else
                    {
                        return Evaluation.INCLUDE_AND_PRUNE;
                    }
                } );

        return traversalDescription.traverse( startNode );

    }

    private Traverser traverseToDepth( GraphDatabaseService graphDb, final Node startNode, final int depth )
    {

        TraversalDescription traversalDescription = graphDb.traversalDescription()
                .expand( PathExpanders.allTypesAndDirections() )
                .depthFirst()
                .evaluator( new Evaluator()
                {

                    @Override
                    public Evaluation evaluate( Path path )
                    {
                        if ( path.length() < depth )
                        {
                            return Evaluation.INCLUDE_AND_CONTINUE;
                        }
                        else
                        {
                            return Evaluation.INCLUDE_AND_PRUNE;
                        }
                    }
                } );

        return traversalDescription.traverse( startNode );

    }

Replace Anonymous With Lambda org.neo4j.server.plugins.GraphCloner.traverseToDepth.traversalDescription.evaluator.new Evaluator with path -> {if(path.length() < depth){return Evaluation.INCLUDE_AND_CONTINUE; in method private traverseToDepth(graphDb GraphDatabaseService, startNode Node, depth int) : Traverser from class org.neo4j.server.plugins.GraphCloner


    private Object stream( final Representation representation, final StreamingFormat streamingFormat, final boolean mustFail )
    {
        return (StreamingOutput) output ->
        {
            RepresentationFormat outputStreamFormat = streamingFormat.writeTo( output );
            try
            {
                representation.serialize( outputStreamFormat, baseUri, extensions );

                if ( !mustFail )
                {
                    representationWriteHandler.onRepresentationWritten();
                }
            }
            catch ( Exception e )
            {
                if ( e instanceof NodeNotFoundException || e instanceof RelationshipNotFoundException )
                {
                    throw new WebApplicationException( notFound( e ) );
                }
                if ( e instanceof BadInputException )
                {
                    throw new WebApplicationException( badRequest( e ) );
                }
                throw new WebApplicationException( e, serverError( e ) );
            }
            finally
            {
                representationWriteHandler.onRepresentationFinal();
            }
        };
    }

    private Object stream( final Representation representation, final StreamingFormat streamingFormat, final boolean mustFail )
    {
        return new StreamingOutput()
        {
            public void write( OutputStream output ) throws IOException, WebApplicationException
            {
                RepresentationFormat outputStreamFormat = streamingFormat.writeTo( output );
                try
                {
                    representation.serialize( outputStreamFormat, baseUri, extensions );

                    if ( !mustFail )
                    {
                        representationWriteHandler.onRepresentationWritten();
                    }
                }
                catch ( Exception e )
                {
                    if ( e instanceof NodeNotFoundException || e instanceof RelationshipNotFoundException )
                    {
                        throw new WebApplicationException( notFound( e ) );
                    }
                    if ( e instanceof BadInputException )
                    {
                        throw new WebApplicationException( badRequest( e ) );
                    }
                    throw new WebApplicationException( e, serverError( e ) );
                }
                finally
                {
                    representationWriteHandler.onRepresentationFinal();
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.server.rest.repr.OutputFormat.stream.new StreamingOutput with output -> {RepresentationFormat outputStreamFormat=streamingFormat.writeTo(output); in method private stream(representation Representation, streamingFormat StreamingFormat, mustFail boolean) : Object from class org.neo4j.server.rest.repr.OutputFormat


    @Override
    public ResourceMethodDispatchProvider adapt( final ResourceMethodDispatchProvider resourceMethodDispatchProvider )
    {
        return abstractResourceMethod ->
        {
            final RequestDispatcher requestDispatcher = resourceMethodDispatchProvider.create(
                    abstractResourceMethod );

            return new TransactionalRequestDispatcher( database, requestDispatcher );
        };
    }

    @Override
    public ResourceMethodDispatchProvider adapt( final ResourceMethodDispatchProvider resourceMethodDispatchProvider )
    {
        return new ResourceMethodDispatchProvider()
        {
            @Override
            public RequestDispatcher create( AbstractResourceMethod abstractResourceMethod )
            {
                final RequestDispatcher requestDispatcher = resourceMethodDispatchProvider.create(
                        abstractResourceMethod );

                return new TransactionalRequestDispatcher( database, requestDispatcher );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.TransactionFilter.adapt.new ResourceMethodDispatchProvider with abstractResourceMethod -> {final RequestDispatcher requestDispatcher=resourceMethodDispatchProvider.create(abstractResourceMethod); in method public adapt(resourceMethodDispatchProvider ResourceMethodDispatchProvider) : ResourceMethodDispatchProvider from class org.neo4j.server.rest.transactional.TransactionFilter


    private Response batchProcessAndStream( final UriInfo uriInfo, final HttpHeaders httpHeaders,
                                            final HttpServletRequest req, final InputStream body )
    {
        try
        {
            final StreamingOutput stream = output ->
            {
                try
                {
                    final ServletOutputStream servletOutputStream = new ServletOutputStream()
                    {
                        @Override
                        public void write( int i ) throws IOException
                        {
                            output.write( i );
                        }

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

                        @Override
                        public void setWriteListener( WriteListener writeListener )
                        {
                            try
                            {
                                writeListener.onWritePossible();
                            }
                            catch ( IOException e )
                            {
                                // Ignore
                            }
                        }
                    };
                    new StreamingBatchOperations( webServer ).readAndExecuteOperations( uriInfo, httpHeaders, req,
                            body, servletOutputStream );
                    representationWriteHandler.onRepresentationWritten();
                }
                catch ( Exception e )
                {
                    LOGGER.warn( "Error executing batch request ", e );
                }
                finally
                {
                    representationWriteHandler.onRepresentationFinal();
                }
            };
            return Response.ok(stream)
                    .type( HttpHeaderUtils.mediaTypeWithCharsetUtf8(MediaType.APPLICATION_JSON_TYPE) ).build();
        }
        catch ( Exception e )
        {
            return output.serverError( e );
        }
    }

    private Response batchProcessAndStream( final UriInfo uriInfo, final HttpHeaders httpHeaders,
                                            final HttpServletRequest req, final InputStream body )
    {
        try
        {
            final StreamingOutput stream = new StreamingOutput()
            {
                @Override
                public void write( final OutputStream output ) throws IOException, WebApplicationException
                {
                    try
                    {
                        final ServletOutputStream servletOutputStream = new ServletOutputStream()
                        {
                            @Override
                            public void write( int i ) throws IOException
                            {
                                output.write( i );
                            }

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

                            @Override
                            public void setWriteListener( WriteListener writeListener )
                            {
                                try
                                {
                                    writeListener.onWritePossible();
                                }
                                catch ( IOException e )
                                {
                                    // Ignore
                                }
                            }
                        };
                        new StreamingBatchOperations( webServer ).readAndExecuteOperations( uriInfo, httpHeaders, req,
                                body, servletOutputStream );
                        representationWriteHandler.onRepresentationWritten();
                    }
                    catch ( Exception e )
                    {
                        LOGGER.warn( "Error executing batch request ", e );
                    }
                    finally
                    {
                        representationWriteHandler.onRepresentationFinal();
                    }
                }
            };
            return Response.ok(stream)
                    .type( HttpHeaderUtils.mediaTypeWithCharsetUtf8(MediaType.APPLICATION_JSON_TYPE) ).build();
        }
        catch ( Exception e )
        {
            return output.serverError( e );
        }
    }

Replace Anonymous With Lambda org.neo4j.server.rest.web.BatchOperationService.batchProcessAndStream.stream.new StreamingOutput with output -> {tryfinal ServletOutputStream servletOutputStream=new ServletOutputStream(){ in method private batchProcessAndStream(uriInfo UriInfo, httpHeaders HttpHeaders, req HttpServletRequest, body InputStream) : Response from class org.neo4j.server.rest.web.BatchOperationService


    private int createSimpleDatabase( final GraphDatabaseAPI graph )
    {
        final int numberOfNodes = 10;
        new Transactor( graph, () ->
        {
            for ( int i = 0; i < numberOfNodes; i++ )
            {
                graph.createNode();
            }

            for ( Node n1 : graph.getAllNodes() )
            {
                for ( Node n2 : graph.getAllNodes() )
                {
                    if ( n1.equals( n2 ) )
                    {
                        continue;
                    }

                    n1.createRelationshipTo( n2, RelationshipType.withName( "REL" ) );
                }
            }
        } ).execute();

        return numberOfNodes;
    }

    private int createSimpleDatabase( final GraphDatabaseAPI graph )
    {
        final int numberOfNodes = 10;
        new Transactor( graph, new UnitOfWork()
        {

            @Override
            public void doWork()
            {
                for ( int i = 0; i < numberOfNodes; i++ )
                {
                    graph.createNode();
                }

                for ( Node n1 : graph.getAllNodes() )
                {
                    for ( Node n2 : graph.getAllNodes() )
                    {
                        if ( n1.equals( n2 ) )
                        {
                            continue;
                        }

                        n1.createRelationshipTo( n2, RelationshipType.withName( "REL" ) );
                    }
                }
            }
        } ).execute();

        return numberOfNodes;
    }

Replace Anonymous With Lambda org.neo4j.server.NeoServerJAXRSIT.createSimpleDatabase.execute.new Transactor.new UnitOfWork with () -> {for(int i=0; i < numberOfNodes; i++){graph.createNode(); in method private createSimpleDatabase(graph GraphDatabaseAPI) : int from class org.neo4j.server.NeoServerJAXRSIT


    @Test
    public void shouldFailWhenUsingPeriodicCommitViaNewTxEndpoint() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, url ->
        {
            // Given
            String jsonString = new PrettyJSON()
                    .array()
                    .object()
                    .key( "method" ).value("POST")
                    .key( "to" ).value("/transaction/commit")
                    .key( "body" ).object()
                    .key("statements").array()
                    .object()
                    .key( "statement" )
                    .value( "USING PERIODIC COMMIT LOAD CSV FROM '" + url + "' AS line CREATE ()" )
                    .endObject()
                    .endArray()
                    .endObject()
                    .endObject()
                    .endArray()
                    .toString();

            // When
            JsonNode result = JsonHelper.jsonNode(gen.get()
                    .expectedStatus(200)
                    .payload(jsonString)
                    .post(batchUri())
                    .entity());

            // Then
            JsonNode results = result.get(0).get("body").get("results");
            JsonNode errors = result.get(0).get("body").get("errors");

            assertTrue( "Results not an array", results.isArray() );
            assertEquals( 0, results.size() );
            assertTrue( "Errors not an array", errors.isArray() );
            assertEquals( 1, errors.size() );

            String errorCode = errors.get(0).get("code").getTextValue();
            assertEquals( "Neo.ClientError.Statement.SemanticError", errorCode );
        } );
    }

    @Test
    public void shouldFailWhenUsingPeriodicCommitViaNewTxEndpoint() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, new ServerTestUtils.BlockWithCSVFileURL()
        {
            @Override
            public void execute( String url ) throws Exception
            {
                // Given
                String jsonString = new PrettyJSON()
                        .array()
                        .object()
                        .key( "method" ).value("POST")
                        .key( "to" ).value("/transaction/commit")
                        .key( "body" ).object()
                        .key("statements").array()
                        .object()
                        .key( "statement" )
                        .value( "USING PERIODIC COMMIT LOAD CSV FROM '" + url + "' AS line CREATE ()" )
                        .endObject()
                        .endArray()
                        .endObject()
                        .endObject()
                        .endArray()
                        .toString();

                // When
                JsonNode result = JsonHelper.jsonNode(gen.get()
                        .expectedStatus(200)
                        .payload(jsonString)
                        .post(batchUri())
                        .entity());

                // Then
                JsonNode results = result.get(0).get("body").get("results");
                JsonNode errors = result.get(0).get("body").get("errors");

                assertTrue( "Results not an array", results.isArray() );
                assertEquals( 0, results.size() );
                assertTrue( "Errors not an array", errors.isArray() );
                assertEquals( 1, errors.size() );

                String errorCode = errors.get(0).get("code").getTextValue();
                assertEquals( "Neo.ClientError.Statement.SemanticError", errorCode );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.BatchOperationIT.shouldFailWhenUsingPeriodicCommitViaNewTxEndpoint.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {String jsonString=new PrettyJSON().array().object().key("method").value("POST").key("to").value("/transaction/commit").key("body").object().key("statements").array().object().key("statement").value("USING PERIODIC COMMIT LOAD CSV FROM '" + url + "' AS line CREATE ()").endObject().endArray().endObject().endObject().endArray().toString(); in method public shouldFailWhenUsingPeriodicCommitViaNewTxEndpoint() : void from class org.neo4j.server.rest.BatchOperationIT


        @BeforeClass
        public static void setupServer() throws Exception
        {
            clock = Clocks.fakeClock();
            server = CommunityServerBuilder.server()
                    .usingDataDir( staticFolder.getRoot().getAbsolutePath() )
                    .withClock( clock )
                    .build();

            suppressAll().call( (Callable<Void>) () ->
            {
                server.start();
                return null;
            } );
            functionalTestHelper = new FunctionalTestHelper( server );
        }

        @BeforeClass
        public static void setupServer() throws Exception
        {
            clock = Clocks.fakeClock();
            server = CommunityServerBuilder.server()
                    .usingDataDir( staticFolder.getRoot().getAbsolutePath() )
                    .withClock( clock )
                    .build();

            suppressAll().call( new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    server.start();
                    return null;
                }
            } );
            functionalTestHelper = new FunctionalTestHelper( server );
        }

Replace Anonymous With Lambda org.neo4j.server.rest.ManageNodeIT.CommunityVersionAndEditionServiceDocIT.setupServer.call.new Callable<Void> with () -> {server.start(); in method public setupServer() : void from class org.neo4j.server.rest.ManageNodeIT.CommunityVersionAndEditionServiceDocIT


        @AfterClass
        public static void stopServer() throws Exception
        {
            suppressAll().call( (Callable<Void>) () ->
            {
                server.stop();
                return null;
            } );
        }

        @AfterClass
        public static void stopServer() throws Exception
        {
            suppressAll().call( new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    server.stop();
                    return null;
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.server.rest.ManageNodeIT.CommunityVersionAndEditionServiceDocIT.stopServer.call.new Callable<Void> with () -> {server.stop(); in method public stopServer() : void from class org.neo4j.server.rest.ManageNodeIT.CommunityVersionAndEditionServiceDocIT


    @Documented( "List indexes for a label." )
    @Test
    @GraphDescription.Graph( nodes = {} )
    public void get_indexes_for_label() throws Exception
    {
        data.get();

        String labelName = labels.newInstance();
        String propertyKey = properties.newInstance();
        createIndex( labelName, propertyKey );
        Map<String,Object> definition = map( "property_keys", singletonList( propertyKey ) );

        List<Map<String,Object>> serializedList = retryOnStillPopulating( () -> gen.get()
                                                                           .expectedStatus( 200 )
                                                                           .payload( createJsonFrom( definition ) )
                                                                           .get( getSchemaIndexLabelUri( labelName ) )
                                                                           .entity() );

        Map<String,Object> index = new HashMap<>();
        index.put( "label", labelName );
        index.put( "property_keys", singletonList( propertyKey ) );

        assertThat( serializedList, hasItem( index ) );
    }

    @Documented( "List indexes for a label." )
    @Test
    @GraphDescription.Graph( nodes = {} )
    public void get_indexes_for_label() throws Exception
    {
        data.get();

        String labelName = labels.newInstance();
        String propertyKey = properties.newInstance();
        createIndex( labelName, propertyKey );
        Map<String,Object> definition = map( "property_keys", singletonList( propertyKey ) );

        List<Map<String,Object>> serializedList = retryOnStillPopulating( new Callable<String>()
        {
            @Override
            public String call()
            {
                return gen.get()
                        .expectedStatus( 200 )
                        .payload( createJsonFrom( definition ) )
                        .get( getSchemaIndexLabelUri( labelName ) )
                        .entity();
            }
        } );

        Map<String,Object> index = new HashMap<>();
        index.put( "label", labelName );
        index.put( "property_keys", singletonList( propertyKey ) );

        assertThat( serializedList, hasItem( index ) );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.SchemaIndexIT.get_indexes_for_label.serializedList.retryOnStillPopulating.new Callable<String> with () -> gen.get().expectedStatus(200).payload(createJsonFrom(definition)).get(getSchemaIndexLabelUri(labelName)).entity() in method public get_indexes_for_label() : void from class org.neo4j.server.rest.SchemaIndexIT


    private Response.ResponseBuilder mockResponsBuilder( Response response, final AtomicReference<StreamingOutput> ref )
    {
        final Response.ResponseBuilder responseBuilder = mock( Response.ResponseBuilder.class );
        when( responseBuilder.entity( Matchers.isA( StreamingOutput.class ) ) ).thenAnswer(
                invocationOnMock ->
                {
                    ref.set( (StreamingOutput) invocationOnMock.getArguments()[0] );
                    return responseBuilder;
                } );
        when( responseBuilder.type( Matchers.<MediaType>any() ) ).thenReturn( responseBuilder );
        when( responseBuilder.build() ).thenReturn( response );
        return responseBuilder;
    }

    private Response.ResponseBuilder mockResponsBuilder( Response response, final AtomicReference<StreamingOutput> ref )
    {
        final Response.ResponseBuilder responseBuilder = mock( Response.ResponseBuilder.class );
        when( responseBuilder.entity( Matchers.isA( StreamingOutput.class ) ) ).thenAnswer(
                new Answer<Response.ResponseBuilder>()
                {
                    @Override
                    public Response.ResponseBuilder answer( InvocationOnMock invocationOnMock ) throws Throwable
                    {
                        ref.set( (StreamingOutput) invocationOnMock.getArguments()[0] );
                        return responseBuilder;
                    }
                } );
        when( responseBuilder.type( Matchers.<MediaType>any() ) ).thenReturn( responseBuilder );
        when( responseBuilder.build() ).thenReturn( response );
        return responseBuilder;
    }

Replace Anonymous With Lambda org.neo4j.server.rest.repr.RepresentationFormatRepositoryTest.mockResponsBuilder.thenAnswer.new Answer<Response.ResponseBuilder> with invocationOnMock -> {ref.set((StreamingOutput)invocationOnMock.getArguments()[0]); in method private mockResponsBuilder(response Response, ref AtomicReference<StreamingOutput>) : Response.ResponseBuilder from class org.neo4j.server.rest.repr.RepresentationFormatRepositoryTest


    private static void mockAccept( Result mock )
    {
        doAnswer( invocation ->
        {
            Result result = (Result) invocation.getMock();
            Result.ResultVisitor visitor = (Result.ResultVisitor) invocation.getArguments()[0];
            while ( result.hasNext() )
            {
                visitor.visit( new MapRow( result.next() ) );
            }
            return null;
        } ).when( mock )
               .accept( (Result.ResultVisitor<RuntimeException>) any( Result.ResultVisitor.class ) );
    }

    private static void mockAccept( Result mock )
    {
        doAnswer( new Answer<Void>()
        {
            @Override
            public Void answer( InvocationOnMock invocation ) throws Throwable
            {
                Result result = (Result) invocation.getMock();
                Result.ResultVisitor visitor = (Result.ResultVisitor) invocation.getArguments()[0];
                while ( result.hasNext() )
                {
                    visitor.visit( new MapRow( result.next() ) );
                }
                return null;
            }
        } ).when( mock )
           .accept( (Result.ResultVisitor<RuntimeException>) any( Result.ResultVisitor.class ) );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.ExecutionResultSerializerTest.mockAccept.accept.when.doAnswer.new Answer<Void> with invocation -> {Result result=(Result)invocation.getMock(); in method private mockAccept(mock Result) : void from class org.neo4j.server.rest.transactional.ExecutionResultSerializerTest


    private OtherThreadExecutor.WorkerCommand<Object, Object> writeToFirstAndSecond()
    {
        return state ->
        {
            HTTP.Response post = http.POST( "/db/data/transaction",
                    quotedJson( "{ 'statements': [ { 'statement': 'MATCH (n:Second) SET n.prop=1' } ] }" ) );
            secondNodeLocked.countDown();
            http.POST( post.location(),
                    quotedJson( "{ 'statements': [ { 'statement': 'MATCH (n:First) SET n.prop=1' } ] }" ) );
            return null;
        };
    }

    private OtherThreadExecutor.WorkerCommand<Object, Object> writeToFirstAndSecond()
    {
        return new OtherThreadExecutor.WorkerCommand<Object, Object>()
        {
            @Override
            public Object doWork( Object state ) throws Exception
            {
                HTTP.Response post = http.POST( "/db/data/transaction",
                        quotedJson( "{ 'statements': [ { 'statement': 'MATCH (n:Second) SET n.prop=1' } ] }" ) );
                secondNodeLocked.countDown();
                http.POST( post.location(),
                        quotedJson( "{ 'statements': [ { 'statement': 'MATCH (n:First) SET n.prop=1' } ] }" ) );
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.DeadlockIT.writeToFirstAndSecond.new OtherThreadExecutor.WorkerCommand<Object,Object> with state -> {HTTP.Response post=http.POST("/db/data/transaction",quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:Second) SET n.prop=1' } ] }")); in method private writeToFirstAndSecond() : OtherThreadExecutor.WorkerCommand<Object,Object> from class org.neo4j.server.rest.transactional.integration.DeadlockIT


    @BeforeClass
    public static void ensureServerNotRunning() throws Exception
    {
        System.setProperty( "org.neo4j.useInsecureCertificateGeneration", "true" );
        suppressAll().call( (Callable<Void>) () ->
        {
            ServerHolder.ensureNotRunning();
            return null;
        } );
    }

    @BeforeClass
    public static void ensureServerNotRunning() throws Exception
    {
        System.setProperty( "org.neo4j.useInsecureCertificateGeneration", "true" );
        suppressAll().call( new Callable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                ServerHolder.ensureNotRunning();
                return null;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.test.server.ExclusiveServerTestBase.ensureServerNotRunning.call.new Callable<Void> with () -> {ServerHolder.ensureNotRunning(); in method public ensureServerNotRunning() : void from class org.neo4j.test.server.ExclusiveServerTestBase


    @BeforeClass
    public static void allocateServer() throws Throwable
    {
        System.setProperty( "org.neo4j.useInsecureCertificateGeneration", "true" );
        if ( !useExternal )
        {
            suppressAll().call( (Callable<Void>) () ->
            {
                ServerHolder.setServerBuilderProperty( GraphDatabaseSettings.cypher_hints_error.name(), "true" );
                server = ServerHolder.allocate();
                ServerHelper.cleanTheDatabase( server );
                return null;
            } );
        }
    }

    @BeforeClass
    public static void allocateServer() throws Throwable
    {
        System.setProperty( "org.neo4j.useInsecureCertificateGeneration", "true" );
        if ( !useExternal )
        {
            suppressAll().call( new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    ServerHolder.setServerBuilderProperty( GraphDatabaseSettings.cypher_hints_error.name(), "true" );
                    server = ServerHolder.allocate();
                    ServerHelper.cleanTheDatabase( server );
                    return null;
                }
            } );
        }
    }

Replace Anonymous With Lambda org.neo4j.test.server.SharedServerTestBase.allocateServer.call.new Callable<Void> with () -> {ServerHolder.setServerBuilderProperty(GraphDatabaseSettings.cypher_hints_error.name(),"true"); in method public allocateServer() : void from class org.neo4j.test.server.SharedServerTestBase


    @AfterClass
    public static void releaseServer() throws Exception
    {
        if ( !useExternal )
        {
            try
            {
                suppressAll().call( (Callable<Void>) () ->
                {
                    ServerHolder.release( server );
                    return null;
                } );
            }
            finally
            {
                server = null;
            }
        }
    }

    @AfterClass
    public static void releaseServer() throws Exception
    {
        if ( !useExternal )
        {
            try
            {
                suppressAll().call( new Callable<Void>()
                {
                    @Override
                    public Void call() throws Exception
                    {
                        ServerHolder.release( server );
                        return null;
                    }
                } );
            }
            finally
            {
                server = null;
            }
        }
    }

Replace Anonymous With Lambda org.neo4j.test.server.SharedServerTestBase.releaseServer.call.new Callable<Void> with () -> {ServerHolder.release(server); in method public releaseServer() : void from class org.neo4j.test.server.SharedServerTestBase


    @Override
    public Cancelable install( final Runnable action )
    {
        if ( !actionRef.compareAndSet( null, action ) )
        {
            throw new RuntimeException( "An action has already been registered" );
        }

        final SignalHandler oldHandler = Signal.handle( signal, this );
        final InterruptSignalHandler self = this;
        return () ->
        {
            SignalHandler handle = Signal.handle( signal, oldHandler );
            if ( self != handle )
            {
                throw new RuntimeException( "Error uninstalling ShellSignalHandler: " +
                        "another handler interjected in the mean time" );
            }
            if ( !self.actionRef.compareAndSet( action, null ) )
            {
                throw new RuntimeException( "Popping a action that has not been pushed before" );
            }
        };
    }

    @Override
    public Cancelable install( final Runnable action )
    {
        if ( !actionRef.compareAndSet( null, action ) )
        {
            throw new RuntimeException( "An action has already been registered" );
        }

        final SignalHandler oldHandler = Signal.handle( signal, this );
        final InterruptSignalHandler self = this;
        return new Cancelable()
        {
            @Override
            public void cancel()
            {
                SignalHandler handle = Signal.handle( signal, oldHandler );
                if ( self != handle )
                {
                    throw new RuntimeException( "Error uninstalling ShellSignalHandler: " +
                            "another handler interjected in the mean time" );
                }
                if ( !self.actionRef.compareAndSet( action, null ) )
                {
                    throw new RuntimeException( "Popping a action that has not been pushed before" );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.shell.InterruptSignalHandler.install.new Cancelable with () -> {SignalHandler handle=Signal.handle(signal,oldHandler); in method public install(action Runnable) : Cancelable from class org.neo4j.shell.InterruptSignalHandler


    private Runnable getTerminateAction()
    {
        return () ->
        {
            try
            {
                getServer().terminate( getId() );
            }
            catch ( Exception e )
            {
                printStackTrace( e );
            }
        };
    }

    private Runnable getTerminateAction()
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    getServer().terminate( getId() );
                }
                catch ( Exception e )
                {
                    printStackTrace( e );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.shell.impl.AbstractClient.getTerminateAction.new Runnable with () -> {trygetServer().terminate(getId()); in method private getTerminateAction() : Runnable from class org.neo4j.shell.impl.AbstractClient


    @Override
    public ResourceIterable<Relationship> getAllRelationships()
    {
        return () ->
        {
            final ResourceIterator<Relationship> iterator = actual.getAllRelationships().iterator();
            return new PrefetchingResourceIterator<Relationship>()
            {
                @Override
                protected Relationship fetchNextOrNull()
                {
                    return new ReadOnlyRelationshipProxy( iterator.next() );
                }

                @Override
                public void close()
                {
                    iterator.close();
                }
            };
        };
    }

    @Override
    public ResourceIterable<Relationship> getAllRelationships()
    {
        return new ResourceIterable<Relationship>()
        {
            @Override
            public ResourceIterator<Relationship> iterator()
            {
                final ResourceIterator<Relationship> iterator = actual.getAllRelationships().iterator();
                return new PrefetchingResourceIterator<Relationship>()
                {
                    @Override
                    protected Relationship fetchNextOrNull()
                    {
                        return new ReadOnlyRelationshipProxy( iterator.next() );
                    }

                    @Override
                    public void close()
                    {
                        iterator.close();
                    }
                };
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.shell.kernel.ReadOnlyGraphDatabaseProxy.getAllRelationships.new ResourceIterable<Relationship> with () -> {final ResourceIterator<Relationship> iterator=actual.getAllRelationships().iterator(); in method public getAllRelationships() : ResourceIterable<Relationship> from class org.neo4j.shell.kernel.ReadOnlyGraphDatabaseProxy


    @Override
    protected ChannelFutureListener newChannelFutureListener( final ChannelBuffer buffer )
    {
        return future ->
        {
            buffer.clear();
            freeBuffers.offer( buffer );
            BufferReusingChunkingChannelBuffer.super.operationComplete( future );
        };
    }

    @Override
    protected ChannelFutureListener newChannelFutureListener( final ChannelBuffer buffer )
    {
        return new ChannelFutureListener()
        {
            @Override
            public void operationComplete( ChannelFuture future ) throws Exception
            {
                buffer.clear();
                freeBuffers.offer( buffer );
                BufferReusingChunkingChannelBuffer.super.operationComplete( future );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.backup.BufferReusingChunkingChannelBuffer.newChannelFutureListener.new ChannelFutureListener with future -> {buffer.clear(); in method protected newChannelFutureListener(buffer ChannelBuffer) : ChannelFutureListener from class org.neo4j.backup.BufferReusingChunkingChannelBuffer


            @Override
            public void start()
                    throws Throwable
            {
                scheduler = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory( "timeout" ) );

                scheduler.scheduleWithFixedDelay( () ->
                {
                    long now = System.currentTimeMillis();

                    protocolServer.getTimeouts().tick( now );
                }, 0, 10, TimeUnit.MILLISECONDS );
            }

            @Override
            public void start()
                    throws Throwable
            {
                scheduler = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory( "timeout" ) );

                scheduler.scheduleWithFixedDelay( new Runnable()
                {
                    @Override
                    public void run()
                    {
                        long now = System.currentTimeMillis();

                        protocolServer.getTimeouts().tick( now );
                    }
                }, 0, 10, TimeUnit.MILLISECONDS );
            }

Replace Anonymous With Lambda org.neo4j.cluster.NetworkedServerFactory.newNetworkedServer.add.new Lifecycle.start.scheduleWithFixedDelay.new Runnable with () -> {long now=System.currentTimeMillis(); in method public start() : void from class org.neo4j.cluster.NetworkedServerFactory.newNetworkedServer.add.new Lifecycle


    private synchronized void send( final Message message )
    {
        monitor.queuedMessage( message );

        final URI to = URI.create( message.getHeader( Message.TO ) );

        ExecutorService senderExecutor = senderExecutors.get( to );
        if ( senderExecutor == null )
        {
            senderExecutor = Executors.newSingleThreadExecutor( new NamedThreadFactory( "Cluster Sender " + to
                    .toASCIIString(), monitor ) );
            senderExecutors.put( to, senderExecutor );
        }

        senderExecutor.submit( () ->
        {
            Channel channel = getChannel( to );

            try
            {
                if ( channel == null )
                {
                    channel = openChannel( to );
                    openedChannel( to, channel );

                    // Instance could be connected to, remove any marker of it being failed
                    failedInstances.remove( to );
                }
            }
            catch ( Exception e )
            {
                // Only print out failure message on first fail
                if ( !failedInstances.contains( to ) )
                {
                    msgLog.warn( e.getMessage() );
                    failedInstances.add( to );
                }

                return;
            }

            try
            {
                // Set FROM header
                message.setHeader( Message.FROM, me.toASCIIString() );

                msgLog.debug( "Sending to " + to + ": " + message );

                ChannelFuture future = channel.write( message );
                future.addListener( future1 ->
                {
                    monitor.sentMessage( message );

                    if ( !future1.isSuccess() )
                    {
                        msgLog.debug( "Unable to write " + message + " to " + future1.getChannel(),
                                future1.getCause() );
                        closedChannel( future1.getChannel() );

                        // Try again
                        send( message );
                    }
                } );
            }
            catch ( Exception e )
            {
                if ( Exceptions.contains( e, ClosedChannelException.class ) )
                {
                    msgLog.warn( "Could not send message, because the connection has been closed." );
                }
                else
                {
                    msgLog.warn( "Could not send message", e );
                }
                channel.close();
            }
        } );
    }

    private synchronized void send( final Message message )
    {
        monitor.queuedMessage( message );

        final URI to = URI.create( message.getHeader( Message.TO ) );

        ExecutorService senderExecutor = senderExecutors.get( to );
        if ( senderExecutor == null )
        {
            senderExecutor = Executors.newSingleThreadExecutor( new NamedThreadFactory( "Cluster Sender " + to
                    .toASCIIString(), monitor ) );
            senderExecutors.put( to, senderExecutor );
        }

        senderExecutor.submit( new Runnable()
        {
            @Override
            public void run()
            {
                Channel channel = getChannel( to );

                try
                {
                    if ( channel == null )
                    {
                        channel = openChannel( to );
                        openedChannel( to, channel );

                        // Instance could be connected to, remove any marker of it being failed
                        failedInstances.remove( to );
                    }
                }
                catch ( Exception e )
                {
                    // Only print out failure message on first fail
                    if ( !failedInstances.contains( to ) )
                    {
                        msgLog.warn( e.getMessage() );
                        failedInstances.add( to );
                    }

                    return;
                }

                try
                {
                    // Set FROM header
                    message.setHeader( Message.FROM, me.toASCIIString() );

                    msgLog.debug( "Sending to " + to + ": " + message );

                    ChannelFuture future = channel.write( message );
                    future.addListener( new ChannelFutureListener()
                    {
                        @Override
                        public void operationComplete( ChannelFuture future ) throws Exception
                        {
                            monitor.sentMessage( message );

                            if ( !future.isSuccess() )
                            {
                                msgLog.debug( "Unable to write " + message + " to " + future.getChannel(),
                                        future.getCause() );
                                closedChannel( future.getChannel() );

                                // Try again
                                send( message );
                            }
                        }
                    } );
                }
                catch ( Exception e )
                {
                    if ( Exceptions.contains( e, ClosedChannelException.class ) )
                    {
                        msgLog.warn( "Could not send message, because the connection has been closed." );
                    }
                    else
                    {
                        msgLog.warn( "Could not send message", e );
                    }
                    channel.close();
                }
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.cluster.com.NetworkSender.send.submit.new Runnable with () -> {Channel channel=getChannel(to); in method private send(message Message) : void from class org.neo4j.cluster.com.NetworkSender


    public PaxosClusterMemberAvailability( InstanceId myId, BindingNotifier binding, AtomicBroadcast atomicBroadcast,
                                           LogProvider logProvider, ObjectInputStreamFactory objectInputStreamFactory,
                                           ObjectOutputStreamFactory objectOutputStreamFactory )
    {
        this.myId = myId;
        this.binding = binding;
        this.atomicBroadcast = atomicBroadcast;
        this.objectInputStreamFactory = objectInputStreamFactory;
        this.objectOutputStreamFactory = objectOutputStreamFactory;
        this.log = logProvider.getLog( getClass() );

        bindingListener = me ->
        {
            serverClusterId = me;
            PaxosClusterMemberAvailability.this.log.info( "Listening at:" + me );
        };
    }

    public PaxosClusterMemberAvailability( InstanceId myId, BindingNotifier binding, AtomicBroadcast atomicBroadcast,
                                           LogProvider logProvider, ObjectInputStreamFactory objectInputStreamFactory,
                                           ObjectOutputStreamFactory objectOutputStreamFactory )
    {
        this.myId = myId;
        this.binding = binding;
        this.atomicBroadcast = atomicBroadcast;
        this.objectInputStreamFactory = objectInputStreamFactory;
        this.objectOutputStreamFactory = objectOutputStreamFactory;
        this.log = logProvider.getLog( getClass() );

        bindingListener = new BindingListener()
        {
            @Override
            public void listeningAt( URI me )
            {
                serverClusterId = me;
                PaxosClusterMemberAvailability.this.log.info( "Listening at:" + me );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.cluster.member.paxos.PaxosClusterMemberAvailability.PaxosClusterMemberAvailability.new BindingListener with me -> {serverClusterId=me; in method public PaxosClusterMemberAvailability(myId InstanceId, binding BindingNotifier, atomicBroadcast AtomicBroadcast, logProvider LogProvider, objectInputStreamFactory ObjectInputStreamFactory, objectOutputStreamFactory ObjectOutputStreamFactory) from class org.neo4j.cluster.member.paxos.PaxosClusterMemberAvailability


                @Override
                public void start() throws Throwable
                {
                    networkReceiver.addMessageProcessor( message ->
                    {
                        // server receives a message
                        processedMessage.set( true );
                        latch.countDown();
                        return true;
                    } );
                }

                @Override
                public void start() throws Throwable
                {
                    networkReceiver.addMessageProcessor( new MessageProcessor()
                    {
                        @Override
                        public boolean process( Message<? extends MessageType> message )
                        {
                            // server receives a message
                            processedMessage.set( true );
                            latch.countDown();
                            return true;
                        }
                    } );
                }

Replace Anonymous With Lambda org.neo4j.cluster.com.message.NetworkSenderReceiverTest.Server.Server.add.new LifecycleAdapter.start.addMessageProcessor.new MessageProcessor with message -> {processedMessage.set(true); in method public start() : void from class org.neo4j.cluster.com.message.NetworkSenderReceiverTest.Server.Server.add.new LifecycleAdapter


    public void start()
            throws IOException
    {
        broadcastSerializer = new AtomicBroadcastSerializer( new ObjectStreamFactory(), new ObjectStreamFactory() );
        final LifeSupport life = new LifeSupport();
        try
        {
            MessageTimeoutStrategy timeoutStrategy = new MessageTimeoutStrategy( new FixedTimeoutStrategy( 5000 ) )
                    .timeout( HeartbeatMessage.sendHeartbeat, 200 );

            Monitors monitors = new Monitors();
            NetworkedServerFactory serverFactory = new NetworkedServerFactory( life,
                    new MultiPaxosServerFactory( new ClusterConfiguration( "default", NullLogProvider.getInstance() ),
                            NullLogProvider.getInstance(), monitors.newMonitor( StateMachines.Monitor.class ) ),
                    timeoutStrategy, NullLogProvider.getInstance(), new ObjectStreamFactory(), new ObjectStreamFactory(),
                    monitors.newMonitor( NetworkReceiver.Monitor.class ),
                    monitors.newMonitor( NetworkSender.Monitor.class ),
                    monitors.newMonitor( NamedThreadFactory.Monitor.class )
            );

            ServerIdElectionCredentialsProvider electionCredentialsProvider = new ServerIdElectionCredentialsProvider();
            server = serverFactory.newNetworkedServer(
                    Config.embeddedDefaults(),
                    new InMemoryAcceptorInstanceStore(),
                    electionCredentialsProvider );
            server.addBindingListener( electionCredentialsProvider );
            server.addBindingListener( me -> System.out.println( "Listening at:" + me ) );

            cluster = server.newClient( Cluster.class );
            cluster.addClusterListener( new ClusterListener()
            {
                @Override
                public void enteredCluster( ClusterConfiguration clusterConfiguration )
                {
                    System.out.println( "Entered cluster:" + clusterConfiguration );
                }

                @Override
                public void joinedCluster( InstanceId instanceId, URI member )
                {
                    System.out.println( "Joined cluster:" + instanceId + " (at URI " + member + ")" );
                }

                @Override
                public void leftCluster( InstanceId instanceId, URI member )
                {
                    System.out.println( "Left cluster:" + instanceId );
                }

                @Override
                public void leftCluster()
                {
                    System.out.println( "Left cluster" );
                }

                @Override
                public void elected( String role, InstanceId instanceId, URI electedMember )
                {
                    System.out.println( instanceId + " at URI " + electedMember + " was elected as " + role );
                }

                @Override
                public void unelected( String role, InstanceId instanceId, URI electedMember )
                {
                    System.out.println( instanceId + " at URI " + electedMember + " was removed from " + role );
                }
            } );

            Heartbeat heartbeat = server.newClient( Heartbeat.class );
            heartbeat.addHeartbeatListener( new HeartbeatListener()
            {
                @Override
                public void failed( InstanceId server )
                {
                    System.out.println( server + " failed" );
                }

                @Override
                public void alive( InstanceId server )
                {
                    System.out.println( server + " alive" );
                }
            } );

            broadcast = server.newClient( AtomicBroadcast.class );
            broadcast.addAtomicBroadcastListener( value ->
            {
                try
                {
                    System.out.println( broadcastSerializer.receive( value ) );
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                }
                catch ( ClassNotFoundException e )
                {
                    e.printStackTrace();
                }
            } );

            life.start();

            String command;
            BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
            while ( !(command = reader.readLine()).equals( "quit" ) )
            {
                String[] arguments = command.split( " " );
                Method method = getCommandMethod( arguments[0] );
                if ( method != null )
                {
                    String[] realArgs = new String[arguments.length - 1];
                    System.arraycopy( arguments, 1, realArgs, 0, realArgs.length );
                    try
                    {
                        method.invoke( this, (Object[]) realArgs );
                    }
                    catch ( IllegalAccessException e )
                    {
                        e.printStackTrace();
                    }
                    catch ( IllegalArgumentException e )
                    {
                        e.printStackTrace();
                    }
                    catch ( InvocationTargetException e )
                    {
                        e.printStackTrace();
                    }
                }
            }

            cluster.leave();
        }
        finally
        {
            life.shutdown();
            System.out.println( "Done" );
        }
    }

    public void start()
            throws IOException
    {
        broadcastSerializer = new AtomicBroadcastSerializer( new ObjectStreamFactory(), new ObjectStreamFactory() );
        final LifeSupport life = new LifeSupport();
        try
        {
            MessageTimeoutStrategy timeoutStrategy = new MessageTimeoutStrategy( new FixedTimeoutStrategy( 5000 ) )
                    .timeout( HeartbeatMessage.sendHeartbeat, 200 );

            Monitors monitors = new Monitors();
            NetworkedServerFactory serverFactory = new NetworkedServerFactory( life,
                    new MultiPaxosServerFactory( new ClusterConfiguration( "default", NullLogProvider.getInstance() ),
                            NullLogProvider.getInstance(), monitors.newMonitor( StateMachines.Monitor.class ) ),
                    timeoutStrategy, NullLogProvider.getInstance(), new ObjectStreamFactory(), new ObjectStreamFactory(),
                    monitors.newMonitor( NetworkReceiver.Monitor.class ),
                    monitors.newMonitor( NetworkSender.Monitor.class ),
                    monitors.newMonitor( NamedThreadFactory.Monitor.class )
            );

            ServerIdElectionCredentialsProvider electionCredentialsProvider = new ServerIdElectionCredentialsProvider();
            server = serverFactory.newNetworkedServer(
                    Config.embeddedDefaults(),
                    new InMemoryAcceptorInstanceStore(),
                    electionCredentialsProvider );
            server.addBindingListener( electionCredentialsProvider );
            server.addBindingListener( new BindingListener()
            {
                @Override
                public void listeningAt( URI me )
                {
                    System.out.println( "Listening at:" + me );
                }
            } );

            cluster = server.newClient( Cluster.class );
            cluster.addClusterListener( new ClusterListener()
            {
                @Override
                public void enteredCluster( ClusterConfiguration clusterConfiguration )
                {
                    System.out.println( "Entered cluster:" + clusterConfiguration );
                }

                @Override
                public void joinedCluster( InstanceId instanceId, URI member )
                {
                    System.out.println( "Joined cluster:" + instanceId + " (at URI " + member + ")" );
                }

                @Override
                public void leftCluster( InstanceId instanceId, URI member )
                {
                    System.out.println( "Left cluster:" + instanceId );
                }

                @Override
                public void leftCluster()
                {
                    System.out.println( "Left cluster" );
                }

                @Override
                public void elected( String role, InstanceId instanceId, URI electedMember )
                {
                    System.out.println( instanceId + " at URI " + electedMember + " was elected as " + role );
                }

                @Override
                public void unelected( String role, InstanceId instanceId, URI electedMember )
                {
                    System.out.println( instanceId + " at URI " + electedMember + " was removed from " + role );
                }
            } );

            Heartbeat heartbeat = server.newClient( Heartbeat.class );
            heartbeat.addHeartbeatListener( new HeartbeatListener()
            {
                @Override
                public void failed( InstanceId server )
                {
                    System.out.println( server + " failed" );
                }

                @Override
                public void alive( InstanceId server )
                {
                    System.out.println( server + " alive" );
                }
            } );

            broadcast = server.newClient( AtomicBroadcast.class );
            broadcast.addAtomicBroadcastListener( new AtomicBroadcastListener()
            {
                @Override
                public void receive( Payload value )
                {
                    try
                    {
                        System.out.println( broadcastSerializer.receive( value ) );
                    }
                    catch ( IOException e )
                    {
                        e.printStackTrace();
                    }
                    catch ( ClassNotFoundException e )
                    {
                        e.printStackTrace();
                    }
                }
            } );

            life.start();

            String command;
            BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
            while ( !(command = reader.readLine()).equals( "quit" ) )
            {
                String[] arguments = command.split( " " );
                Method method = getCommandMethod( arguments[0] );
                if ( method != null )
                {
                    String[] realArgs = new String[arguments.length - 1];
                    System.arraycopy( arguments, 1, realArgs, 0, realArgs.length );
                    try
                    {
                        method.invoke( this, (Object[]) realArgs );
                    }
                    catch ( IllegalAccessException e )
                    {
                        e.printStackTrace();
                    }
                    catch ( IllegalArgumentException e )
                    {
                        e.printStackTrace();
                    }
                    catch ( InvocationTargetException e )
                    {
                        e.printStackTrace();
                    }
                }
            }

            cluster.leave();
        }
        finally
        {
            life.shutdown();
            System.out.println( "Done" );
        }
    }

Replace Anonymous With Lambda org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.MultiPaxosServer.start.addAtomicBroadcastListener.new AtomicBroadcastListener with value -> {trySystem.out.println(broadcastSerializer.receive(value)); in method public start() : void from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.MultiPaxosServer