    private boolean schemaStateContains( String key )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Statement statement = statementContextSupplier.get();
            final AtomicBoolean result = new AtomicBoolean( true );
            statement.readOperations().schemaStateGetOrCreate( key, s -> {
                result.set( false );
                return null;
            } );
            tx.success();
            return result.get();
        }
    }

    private boolean schemaStateContains( String key )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Statement statement = statementContextSupplier.get();
            final AtomicBoolean result = new AtomicBoolean( true );
            statement.readOperations().schemaStateGetOrCreate( key, new Function<String,Object>()
            {
                @Override
                public Object apply( String s )
                {
                    result.set( false );
                    return null;
                }
            } );
            tx.success();
            return result.get();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.KernelIT.schemaStateContains.schemaStateGetOrCreate.new Function<String,Object> with s -> {result.set(false); in method private schemaStateContains(key String) : boolean from class org.neo4j.kernel.impl.api.integrationtest.KernelIT


    @Test
    public void shouldAllowConcurrentCreationOfNonConflictingData() throws Exception
    {
        // given
        database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) );

        // when
        Future<Boolean> created = database.executeAndCommit( db -> {
            db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
            return otherThread.execute( createNode( db, "Label1", "key1", "value2" ) );
        } );

        // then
        assertTrue( "Node creation should succeed", created.get() );
    }

    @Test
    public void shouldAllowConcurrentCreationOfNonConflictingData() throws Exception
    {
        // given
        database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) );

        // when
        Future<Boolean> created = database.executeAndCommit( new Function<GraphDatabaseService, Future<Boolean>>()
        {
            @Override
            public Future<Boolean> apply( GraphDatabaseService db )
            {
                db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
                return otherThread.execute( createNode( db, "Label1", "key1", "value2" ) );
            }
        } );

        // then
        assertTrue( "Node creation should succeed", created.get() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT.shouldAllowConcurrentCreationOfNonConflictingData.created.executeAndCommit.new Function<GraphDatabaseService,Future<Boolean>> with db -> {db.createNode(label("Label1")).setProperty("key1","value1"); in method public shouldAllowConcurrentCreationOfNonConflictingData() : void from class org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT


    @Test
    public void shouldPreventConcurrentCreationOfConflictingData() throws Exception
    {
        // given
        database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) );

        // when
        Future<Boolean> created = database.executeAndCommit( db -> {
            db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
            try
            {
                return otherThread.execute( createNode( db, "Label1", "key1", "value1" ) );
            }
            finally
            {
                assertThat( otherThread, isWaiting() );
            }
        } );

        // then
        assertFalse( "node creation should fail", created.get() );
    }

    @Test
    public void shouldPreventConcurrentCreationOfConflictingData() throws Exception
    {
        // given
        database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) );

        // when
        Future<Boolean> created = database.executeAndCommit( new Function<GraphDatabaseService, Future<Boolean>>()
        {
            @Override
            public Future<Boolean> apply( GraphDatabaseService db )
            {
                db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
                try
                {
                    return otherThread.execute( createNode( db, "Label1", "key1", "value1" ) );
                }
                finally
                {
                    assertThat( otherThread, isWaiting() );
                }
            }
        } );

        // then
        assertFalse( "node creation should fail", created.get() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT.shouldPreventConcurrentCreationOfConflictingData.created.executeAndCommit.new Function<GraphDatabaseService,Future<Boolean>> with db -> {db.createNode(label("Label1")).setProperty("key1","value1"); in method public shouldPreventConcurrentCreationOfConflictingData() : void from class org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT


    @Test
    public void shouldAllowOtherTransactionToCompleteIfFirstTransactionRollsBack() throws Exception
    {
        // given
        database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) );

        // when
        Future<Boolean> created = database.executeAndRollback( db -> {
            db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
            try
            {
                return otherThread.execute( createNode( db, "Label1", "key1", "value1" ) );
            }
            finally
            {
                assertThat( otherThread, isWaiting() );
            }
        } );

        // then
        assertTrue( "Node creation should succeed", created.get() );
    }

    @Test
    public void shouldAllowOtherTransactionToCompleteIfFirstTransactionRollsBack() throws Exception
    {
        // given
        database.executeAndCommit( createUniquenessConstraint( "Label1", "key1" ) );

        // when
        Future<Boolean> created = database.executeAndRollback( new Function<GraphDatabaseService, Future<Boolean>>()
        {
            @Override
            public Future<Boolean> apply( GraphDatabaseService db )
            {
                db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
                try
                {
                    return otherThread.execute( createNode( db, "Label1", "key1", "value1" ) );
                }
                finally
                {
                    assertThat( otherThread, isWaiting() );
                }
            }
        } );

        // then
        assertTrue( "Node creation should succeed", created.get() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT.shouldAllowOtherTransactionToCompleteIfFirstTransactionRollsBack.created.executeAndRollback.new Function<GraphDatabaseService,Future<Boolean>> with db -> {db.createNode(label("Label1")).setProperty("key1","value1"); in method public shouldAllowOtherTransactionToCompleteIfFirstTransactionRollsBack() : void from class org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT


    private static Function<GraphDatabaseService, Void> createUniquenessConstraint(
            final String label, final String propertyKey )
    {
        return db -> {
            db.schema().constraintFor( label( label ) ).assertPropertyIsUnique( propertyKey ).create();
            return null;
        };
    }

    private static Function<GraphDatabaseService, Void> createUniquenessConstraint(
            final String label, final String propertyKey )
    {
        return new Function<GraphDatabaseService, Void>()
        {
            @Override
            public Void apply( GraphDatabaseService db )
            {
                db.schema().constraintFor( label( label ) ).assertPropertyIsUnique( propertyKey ).create();
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT.createUniquenessConstraint.new Function<GraphDatabaseService,Void> with db -> {db.schema().constraintFor(label(label)).assertPropertyIsUnique(propertyKey).create(); in method private createUniquenessConstraint(label String, propertyKey String) : Function<GraphDatabaseService,Void> from class org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT


    public static OtherThreadExecutor.WorkerCommand<Void, Boolean> createNode(
            final GraphDatabaseService db, final String label, final String propertyKey, final Object propertyValue )
    {
        return nothing -> {
            try ( Transaction tx = db.beginTx() )
            {
                db.createNode( label( label ) ).setProperty( propertyKey, propertyValue );

                tx.success();
                return true;
            }
            catch ( ConstraintViolationException e )
            {
                return false;
            }
        };
    }

    public static OtherThreadExecutor.WorkerCommand<Void, Boolean> createNode(
            final GraphDatabaseService db, final String label, final String propertyKey, final Object propertyValue )
    {
        return new OtherThreadExecutor.WorkerCommand<Void, Boolean>()
        {
            @Override
            public Boolean doWork( Void nothing ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    db.createNode( label( label ) ).setProperty( propertyKey, propertyValue );

                    tx.success();
                    return true;
                }
                catch ( ConstraintViolationException e )
                {
                    return false;
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT.createNode.new OtherThreadExecutor.WorkerCommand<Void,Boolean> with nothing -> {try(Transaction tx=db.beginTx())db.createNode(label(label)).setProperty(propertyKey,propertyValue); in method public createNode(db GraphDatabaseService, label String, propertyKey String, propertyValue Object) : OtherThreadExecutor.WorkerCommand<Void,Boolean> from class org.neo4j.kernel.impl.api.integrationtest.UniquenessConstraintValidationConcurrencyIT


    public static Cursor<PropertyItem> asPropertyCursor( final DefinedProperty... properties )
    {
        return Cursors.cursor( Iterables.map( (Function<DefinedProperty,PropertyItem>) property -> {
            return new PropertyItem()
            {
                @Override
                public int propertyKeyId()
                {
                    return property.propertyKeyId();
                }

                @Override
                public Object value()
                {
                    return property.value();
                }
            };
        }, Arrays.asList( properties ) ) );
    }

    public static Cursor<PropertyItem> asPropertyCursor( final DefinedProperty... properties )
    {
        return Cursors.cursor( Iterables.map( new Function<DefinedProperty, PropertyItem>()
        {
            @Override
            public PropertyItem apply( final DefinedProperty property )
            {
                return new PropertyItem()
                {
                    @Override
                    public int propertyKeyId()
                    {
                        return property.propertyKeyId();
                    }

                    @Override
                    public Object value()
                    {
                        return property.value();
                    }
                };
            }
        }, Arrays.asList( properties ) ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.state.StubCursors.asPropertyCursor.cursor.map.new Function<DefinedProperty,PropertyItem> with property -> {return new PropertyItem(){ in method public asPropertyCursor(properties DefinedProperty...) : Cursor<PropertyItem> from class org.neo4j.kernel.impl.api.state.StubCursors


    @Test
    public void shouldBeAbleToReadUpToDateValueWhileAnotherThreadIsPerformingRotation() throws Exception
    {
        // given
        CountsOracle oracle = someData();
        final int firstTransaction = 2, secondTransaction = 3;
        try ( Lifespan life = new Lifespan() )
        {
            CountsTracker tracker = life.add( newTracker() );
            oracle.update( tracker, firstTransaction );
            tracker.rotate( firstTransaction );
        }

        // when
        final CountsOracle delta = new CountsOracle();
        {
            CountsOracle.Node n1 = delta.node( 1 );
            CountsOracle.Node n2 = delta.node( 1, 4 );  // Label 4 has not been used before...
            delta.relationship( n1, 1, n2 );
            delta.relationship( n2, 2, n1 ); // relationshipType 2 has not been used before...
        }
        delta.update( oracle );

        try ( Lifespan life = new Lifespan() )
        {
            final Barrier.Control barrier = new Barrier.Control();
            CountsTracker tracker = life.add( new CountsTracker(
                    resourceManager.logProvider(), resourceManager.fileSystem(), resourceManager.pageCache(),
                    new Config(), resourceManager.testPath() )
            {
                @Override
                protected boolean include( CountsKey countsKey, ReadableBuffer value )
                {
                    barrier.reached();
                    return super.include( countsKey, value );
                }
            } );
            Future<Void> task = threading.execute( (ThrowingFunction<CountsTracker,Void,RuntimeException>) t -> {
                try
                {
                    delta.update( t, secondTransaction );
                    t.rotate( secondTransaction );
                }
                catch ( IOException e )
                {
                    throw new AssertionError( e );
                }
                return null;
            }, tracker );

            // then
            barrier.await();
            oracle.verify( tracker );
            barrier.release();
            task.get();
            oracle.verify( tracker );
        }
    }

    @Test
    public void shouldBeAbleToReadUpToDateValueWhileAnotherThreadIsPerformingRotation() throws Exception
    {
        // given
        CountsOracle oracle = someData();
        final int firstTransaction = 2, secondTransaction = 3;
        try ( Lifespan life = new Lifespan() )
        {
            CountsTracker tracker = life.add( newTracker() );
            oracle.update( tracker, firstTransaction );
            tracker.rotate( firstTransaction );
        }

        // when
        final CountsOracle delta = new CountsOracle();
        {
            CountsOracle.Node n1 = delta.node( 1 );
            CountsOracle.Node n2 = delta.node( 1, 4 );  // Label 4 has not been used before...
            delta.relationship( n1, 1, n2 );
            delta.relationship( n2, 2, n1 ); // relationshipType 2 has not been used before...
        }
        delta.update( oracle );

        try ( Lifespan life = new Lifespan() )
        {
            final Barrier.Control barrier = new Barrier.Control();
            CountsTracker tracker = life.add( new CountsTracker(
                    resourceManager.logProvider(), resourceManager.fileSystem(), resourceManager.pageCache(),
                    new Config(), resourceManager.testPath() )
            {
                @Override
                protected boolean include( CountsKey countsKey, ReadableBuffer value )
                {
                    barrier.reached();
                    return super.include( countsKey, value );
                }
            } );
            Future<Void> task = threading.execute( new Function<CountsTracker, Void>()
            {
                @Override
                public Void apply( CountsTracker tracker )
                {
                    try
                    {
                        delta.update( tracker, secondTransaction );
                        tracker.rotate( secondTransaction );
                    }
                    catch ( IOException e )
                    {
                        throw new AssertionError( e );
                    }
                    return null;
                }
            }, tracker );

            // then
            barrier.await();
            oracle.verify( tracker );
            barrier.release();
            task.get();
            oracle.verify( tracker );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.counts.CountsTrackerTest.shouldBeAbleToReadUpToDateValueWhileAnotherThreadIsPerformingRotation.task.execute.new Function<CountsTracker,Void> with t -> {trydelta.update(t,secondTransaction); in method public shouldBeAbleToReadUpToDateValueWhileAnotherThreadIsPerformingRotation() : void from class org.neo4j.kernel.impl.store.counts.CountsTrackerTest


    private void assertCompiles( final String className, String source )
    {
        compile( className, source,
                ( success, manager, diagnostics ) -> {
                    assertSuccessfullyCompiled( success, diagnostics, className );
                    return true;
                }
        );
    }

    private void assertCompiles( final String className, String source )
    {
        compile( className, source,
                new CompilationListener<Boolean>()
                {
                    @Override
                    public Boolean compiled( Boolean success,
                                             JavaFileManager manager,
                                             List<Diagnostic<? extends JavaFileObject>> diagnostics )
                    {
                        assertSuccessfullyCompiled( success, diagnostics, className );
                        return true;
                    }
                }
        );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.util.dbstructure.DbStructureInvocationTracingAcceptanceTest.assertCompiles.compile.new CompilationListener<Boolean> with (success, manager, diagnostics) -> {assertSuccessfullyCompiled(success,diagnostics,className); in method private assertCompiles(className String, source String) : void from class org.neo4j.kernel.impl.util.dbstructure.DbStructureInvocationTracingAcceptanceTest


    private Visitable<DbStructureVisitor> compileVisitable( final String className, String inputSource )
    {
        return compile( className, inputSource,
                ( success, manager, diagnostics ) -> {
                    assertSuccessfullyCompiled( success, diagnostics, className );
                    Object instance;
                    try
                    {
                        ClassLoader classLoader = manager.getClassLoader( null );
                        Class<?> clazz = classLoader.loadClass( className );
                        instance = clazz.getDeclaredField( "INSTANCE" ).get( null );
                    }
                    catch ( IllegalAccessException | ClassNotFoundException | NoSuchFieldException e )
                    {
                        throw new AssertionError( "Failed to instantiate compiled class", e );
                    }
                    return (Visitable<DbStructureVisitor>) instance;
                }
        );
    }

    private Visitable<DbStructureVisitor> compileVisitable( final String className, String inputSource )
    {
        return compile( className, inputSource,
                new CompilationListener<Visitable<DbStructureVisitor>>()
                {
                    @Override
                    public Visitable<DbStructureVisitor> compiled( Boolean success, JavaFileManager manager,
                                                                   List<Diagnostic<? extends JavaFileObject>> diagnostics )
                    {
                        assertSuccessfullyCompiled( success, diagnostics, className );
                        Object instance;
                        try
                        {
                            ClassLoader classLoader = manager.getClassLoader( null );
                            Class<?> clazz = classLoader.loadClass( className );
                            instance = clazz.getDeclaredField( "INSTANCE" ).get( null );
                        }
                        catch ( IllegalAccessException | ClassNotFoundException | NoSuchFieldException e )
                        {
                            throw new AssertionError( "Failed to instantiate compiled class", e );
                        }
                        return (Visitable<DbStructureVisitor>) instance;
                    }
                }
        );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.util.dbstructure.DbStructureInvocationTracingAcceptanceTest.compileVisitable.compile.new CompilationListener<Visitable<DbStructureVisitor>> with (success, manager, diagnostics) -> {assertSuccessfullyCompiled(success,diagnostics,className); in method private compileVisitable(className String, inputSource String) : Visitable<DbStructureVisitor> from class org.neo4j.kernel.impl.util.dbstructure.DbStructureInvocationTracingAcceptanceTest


            @Override
            public TO apply( final FROM from )
            {
                return executeAndCommit( graphDb -> {
                    return function.apply( from );
                } );
            }

            @Override
            public TO apply( final FROM from )
            {
                return executeAndCommit( new Function<GraphDatabaseService, TO>()
                {
                    @Override
                    public TO apply( GraphDatabaseService graphDb )
                    {
                        return function.apply( from );
                    }
                } );
            }

Replace Anonymous With Lambda org.neo4j.test.DatabaseRule.tx.new AlgebraicFunction<FROM,TO>.apply.executeAndCommit.new Function<GraphDatabaseService,TO> with graphDb -> {return function.apply(from); in method public apply(from FROM) : TO from class org.neo4j.test.DatabaseRule.tx.new AlgebraicFunction<FROM,TO>


    @Override
    protected DuplicatingLog buildLog( final Class loggingClass )
    {
        return buildLog( logProvider -> {
            return logProvider.getLog( loggingClass );
        } );
    }

    @Override
    protected DuplicatingLog buildLog( final Class loggingClass )
    {
        return buildLog( new Function<LogProvider, Log>()
        {
            @Override
            public Log apply( LogProvider logProvider )
            {
                return logProvider.getLog( loggingClass );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.logging.DuplicatingLogProvider.buildLog.buildLog.new Function<LogProvider,Log> with logProvider -> {return logProvider.getLog(loggingClass); in method protected buildLog(loggingClass Class) : DuplicatingLog from class org.neo4j.logging.DuplicatingLogProvider


    @Override
    protected DuplicatingLog buildLog( final String name )
    {
        return buildLog( logProvider -> {
            return logProvider.getLog( name );
        } );
    }

    @Override
    protected DuplicatingLog buildLog( final String name )
    {
        return buildLog( new Function<LogProvider, Log>()
        {
            @Override
            public Log apply( LogProvider logProvider )
            {
                return logProvider.getLog( name );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.logging.DuplicatingLogProvider.buildLog.buildLog.new Function<LogProvider,Log> with logProvider -> {return logProvider.getLog(name); in method protected buildLog(name String) : DuplicatingLog from class org.neo4j.logging.DuplicatingLogProvider


    public IndexReaderStub( final Map<String,NumericDocValues> ndvs )
    {
        this.ndvs = s -> {
            NumericDocValues dv = ndvs.get( s );
            if ( dv == null )
            {
                return DocValues.emptyNumeric();
            }
            return dv;
        };
    }

    public IndexReaderStub( final Map<String,NumericDocValues> ndvs )
    {
        this.ndvs = new Function<String,NumericDocValues>()
        {
            @Override
            public NumericDocValues apply( String s )
            {
                NumericDocValues dv = ndvs.get( s );
                if ( dv == null )
                {
                    return DocValues.emptyNumeric();
                }
                return dv;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.index.IndexReaderStub.IndexReaderStub.new Function<String,NumericDocValues> with s -> {NumericDocValues dv=ndvs.get(s); in method public IndexReaderStub(ndvs Map<String,NumericDocValues>) from class org.neo4j.kernel.api.impl.index.IndexReaderStub


    private Function<GraphDatabaseService, List<Long>> listNodeIdsFromIndexLookup(
            final Label label, final String propertyKey, final Object value )
    {
        return graphDb -> {
            ArrayList<Long> ids = new ArrayList<>();
            for ( Node node : loop( graphDb.findNodes( label, propertyKey, value ) ) )
            {
                ids.add( node.getId() );
            }
            return ids;
        };
    }

    private Function<GraphDatabaseService, List<Long>> listNodeIdsFromIndexLookup(
            final Label label, final String propertyKey, final Object value )
    {
        return new Function<GraphDatabaseService, List<Long>>()
        {
            @Override
            public List<Long> apply( GraphDatabaseService graphDb )
            {
                ArrayList<Long> ids = new ArrayList<>();
                for ( Node node : loop( graphDb.findNodes( label, propertyKey, value ) ) )
                {
                    ids.add( node.getId() );
                }
                return ids;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.index.UniqueIndexApplicationIT.listNodeIdsFromIndexLookup.new Function<GraphDatabaseService,List<Long>> with graphDb -> {ArrayList<Long> ids=new ArrayList<>(); in method private listNodeIdsFromIndexLookup(label Label, propertyKey String, value Object) : Function<GraphDatabaseService,List<Long>> from class org.neo4j.kernel.api.impl.index.UniqueIndexApplicationIT


    @Test
    public void shouldHandleFunctionFixtures() throws Exception
    {
        // Given two files in the root folder
        File targetFolder = testDir.directory();

        // When

        try ( ServerControls server = getServerBuilder( targetFolder )
                .withFixture( graphDatabaseService -> {
                    try ( Transaction tx = graphDatabaseService.beginTx() )
                    {
                        graphDatabaseService.createNode( Label.label( "User" ) );
                        tx.success();
                    }
                    return null;
                } )
                .newServer() )
        {
            // Then
            HTTP.Response response = HTTP.POST( server.httpURI().toString() + "db/data/transaction/commit",
                    quotedJson( "{'statements':[{'statement':'MATCH (n:User) RETURN n'}]}" ) );

            assertThat( response.get( "results" ).get( 0 ).get( "data" ).size(), equalTo( 1 ) );
        }
    }

    @Test
    public void shouldHandleFunctionFixtures() throws Exception
    {
        // Given two files in the root folder
        File targetFolder = testDir.directory();

        // When
        try ( ServerControls server = getServerBuilder( targetFolder )
                .withFixture( new Function<GraphDatabaseService, Void>()
                {
                    @Override
                    public Void apply( GraphDatabaseService graphDatabaseService ) throws RuntimeException
                    {
                        try ( Transaction tx = graphDatabaseService.beginTx() )
                        {
                            graphDatabaseService.createNode( Label.label( "User" ) );
                            tx.success();
                        }
                        return null;
                    }
                } )
                .newServer() )
        {
            // Then
            HTTP.Response response = HTTP.POST( server.httpURI().toString() + "db/data/transaction/commit",
                    quotedJson( "{'statements':[{'statement':'MATCH (n:User) RETURN n'}]}" ) );

            assertThat( response.get( "results" ).get( 0 ).get( "data" ).size(), equalTo( 1 ) );
        }
    }

Replace Anonymous With Lambda org.neo4j.harness.FixturesTest.shouldHandleFunctionFixtures.newServer.withFixture.new Function<GraphDatabaseService,Void> with graphDatabaseService -> {try(Transaction tx=graphDatabaseService.beginTx())graphDatabaseService.createNode(Label.label("User")); in method public shouldHandleFunctionFixtures() : void from class org.neo4j.harness.FixturesTest


    private static Pair<String,String>[] parseConfigOverrides( Args arguments )
    {
        Collection<Pair<String,String>> options = arguments.interpretOptions( "c",
                Converters.<Pair<String,String>>optional(), s -> {
                    if ( s.contains( "=" ) )
                    {
                        String[] keyVal = s.split( "=", 2 );
                        return pair( keyVal[0], keyVal[1] );
                    }
                    // Shortcut to specify boolean flags ("-c dbms.enableTheFeature")
                    return pair( s, "true" );
                } );

        return options.toArray( new Pair[options.size()] );
    }

    private static Pair<String,String>[] parseConfigOverrides( Args arguments )
    {
        Collection<Pair<String,String>> options = arguments.interpretOptions( "c",
                Converters.<Pair<String,String>>optional(), new Function<String, Pair<String,String>>()
                {
                    @Override
                    public Pair<String,String> apply( String s )
                    {
                        if ( s.contains( "=" ) )
                        {
                            String[] keyVal = s.split( "=", 2 );
                            return pair( keyVal[0], keyVal[1] );
                        }
                        // Shortcut to specify boolean flags ("-c dbms.enableTheFeature")
                        return pair( s, "true" );
                    }
                });

        return options.toArray( new Pair[options.size()] );
    }

Replace Anonymous With Lambda org.neo4j.server.ServerCommandLineArgs.parseConfigOverrides.options.interpretOptions.new Function<String,Pair<String,String>> with s -> {if(s.contains("=")){String[] keyVal=s.split("=",2); in method private parseConfigOverrides(arguments Args) : Pair<String,String>[] from class org.neo4j.server.ServerCommandLineArgs


    private Function<Object, ExecutionPlanDescription> planProvider( final Result result )
    {
        return from -> result.getExecutionPlanDescription();
    }

    private Function<Object, ExecutionPlanDescription> planProvider( final Result result )
    {
        return new Function<Object,ExecutionPlanDescription>(){
            @Override
            public ExecutionPlanDescription apply( Object from )
            {
                return result.getExecutionPlanDescription();
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.server.rest.repr.CypherResultRepresentation.planProvider.new Function<Object,ExecutionPlanDescription> with from -> result.getExecutionPlanDescription() in method private planProvider(result Result) : Function<Object,ExecutionPlanDescription> from class org.neo4j.server.rest.repr.CypherResultRepresentation


    private <T> Function<Object, T> getProperty( final String propertyKey, final Class<T> propertyType )
    {
        return from -> {
            Map<?, ?> node = (Map<?, ?>) from;
            Map<?, ?> data1 = (Map<?, ?>) node.get( "data" );
            return propertyType.cast( data1.get( propertyKey ) );
        };
    }

    private <T> Function<Object, T> getProperty( final String propertyKey, final Class<T> propertyType )
    {
        return new Function<Object, T>()
        {
            @Override
            public T apply( Object from )
            {
                Map<?, ?> node = (Map<?, ?>) from;
                Map<?, ?> data = (Map<?, ?>) node.get( "data" );
                return propertyType.cast( data.get( propertyKey ) );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.server.rest.LabelsDocIT.getProperty.new Function<Object,T> with from -> {Map<?,?> node=(Map<?,?>)from; in method private getProperty(propertyKey String, propertyType Class<T>) : Function<Object,T> from class org.neo4j.server.rest.LabelsDocIT


    @Test
    public void getNodesWithLabel() throws Exception
    {
        // GIVEN
        String label1 = "first", label2 = "second";
        long node1 = graphdbHelper.createNode( label( label1 ) );
        long node2 = graphdbHelper.createNode( label( label1 ), label( label2 ) );
        graphdbHelper.createNode( label( label2 ) );

        // WHEN
        List<Object> representation;
        try ( Transaction transaction = graph.beginTx() )
        {
            representation = serialize( actions.getNodesWithLabel( label1, map() ) );
        }

        // THEN
        assertEquals( asSet( node1, node2 ), asSet( Iterables.map( from -> {
            Map<?, ?> nodeMap = (Map<?, ?>) from;
            return nodeUriToId( (String) nodeMap.get( "self" ) );
        }, representation ) ) );
    }

    @Test
    public void getNodesWithLabel() throws Exception
    {
        // GIVEN
        String label1 = "first", label2 = "second";
        long node1 = graphdbHelper.createNode( label( label1 ) );
        long node2 = graphdbHelper.createNode( label( label1 ), label( label2 ) );
        graphdbHelper.createNode( label( label2 ) );

        // WHEN
        List<Object> representation;
        try ( Transaction transaction = graph.beginTx() )
        {
            representation = serialize( actions.getNodesWithLabel( label1, map() ) );
        }

        // THEN
        assertEquals( asSet( node1, node2 ), asSet( Iterables.map( new Function<Object, Long>()
        {
            @Override
            public Long apply( Object from )
            {
                Map<?, ?> nodeMap = (Map<?, ?>) from;
                return nodeUriToId( (String) nodeMap.get( "self" ) );
            }
        }, representation ) ) );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.web.DatabaseActionsTest.getNodesWithLabel.assertEquals.asSet.map.new Function<Object,Long> with from -> {Map<?,?> nodeMap=(Map<?,?>)from; in method public getNodesWithLabel() : void from class org.neo4j.server.rest.web.DatabaseActionsTest


    private Function<ClusterMember, Slave> slaveForMember()
    {
        return from -> {
            synchronized ( HighAvailabilitySlaves.this )
            {
                Slave presentSlave = slaves.get( from );
                if ( presentSlave == null )
                {
                    presentSlave = slaveFactory.newSlave( life, from );
                    slaves.put( from, presentSlave );
                }
                return presentSlave;
            }
        };
    }

    private Function<ClusterMember, Slave> slaveForMember()
    {
        return new Function<ClusterMember, Slave>()
        {
            @Override
            public Slave apply( ClusterMember from )
            {
                synchronized ( HighAvailabilitySlaves.this )
                {
                    Slave presentSlave = slaves.get( from );
                    if ( presentSlave == null )
                    {
                        presentSlave = slaveFactory.newSlave( life, from );
                        slaves.put( from, presentSlave );
                    }
                    return presentSlave;
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.member.HighAvailabilitySlaves.slaveForMember.new Function<ClusterMember,Slave> with from -> {synchronized(HighAvailabilitySlaves.this){Slave presentSlave=slaves.get(from); in method private slaveForMember() : Function<ClusterMember,Slave> from class org.neo4j.kernel.ha.cluster.member.HighAvailabilitySlaves


    @Override
    public Response<Void> pullUpdates( final long upToAndIncludingTxId )
    {
        return sendRequest( SlaveRequestType.PULL_UPDATES, RequestContext.EMPTY, buffer -> {
            writeString( buffer, NeoStoreDataSource.DEFAULT_DATA_SOURCE_NAME );
            buffer.writeLong( upToAndIncludingTxId );
        }, Protocol.VOID_DESERIALIZER );
    }

    @Override
    public Response<Void> pullUpdates( final long upToAndIncludingTxId )
    {
        return sendRequest( SlaveRequestType.PULL_UPDATES, RequestContext.EMPTY, new Serializer()
        {
            @Override
            public void write( ChannelBuffer buffer ) throws IOException
            {
                writeString( buffer, NeoStoreDataSource.DEFAULT_DATA_SOURCE_NAME );
                buffer.writeLong( upToAndIncludingTxId );
            }
        }, Protocol.VOID_DESERIALIZER );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.com.master.SlaveClient.pullUpdates.sendRequest.new Serializer with buffer -> {writeString(buffer,NeoStoreDataSource.DEFAULT_DATA_SOURCE_NAME); in method public pullUpdates(upToAndIncludingTxId long) : Response<Void> from class org.neo4j.kernel.ha.com.master.SlaveClient


    public HighlyAvailableEditionModule( final PlatformModule platformModule )
    {
        final LifeSupport life = platformModule.life;
        life.add( platformModule.dataSourceManager );

        final LifeSupport paxosLife = new LifeSupport();
        final LifeSupport clusteringLife = new LifeSupport();

        final FileSystemAbstraction fs = platformModule.fileSystem;
        final File storeDir = platformModule.storeDir;
        final Config config = platformModule.config;
        final Dependencies dependencies = platformModule.dependencies;
        final LogService logging = platformModule.logging;
        final Monitors monitors = platformModule.monitors;

        // Set Netty logger
        InternalLoggerFactory.setDefaultFactory( new NettyLoggerFactory( logging.getInternalLogProvider() ) );

        life.add( new BranchedDataMigrator( platformModule.storeDir ) );
        DelegateInvocationHandler<Master> masterDelegateInvocationHandler =
                new DelegateInvocationHandler<>( Master.class );
        Master master = (Master) newProxyInstance( Master.class.getClassLoader(), new Class[]{Master.class},
                masterDelegateInvocationHandler );
        InstanceId serverId = config.get( ClusterSettings.server_id );

        RequestContextFactory requestContextFactory = dependencies.satisfyDependency( new RequestContextFactory(
                serverId.toIntegerIndex(),
                dependencies.provideDependency( TransactionIdStore.class ) ) );

        TransactionCommittingResponseUnpacker responseUnpacker = dependencies.satisfyDependency(
                new TransactionCommittingResponseUnpacker( dependencies,
                        config.get( HaSettings.pull_apply_batch_size ) ) );

        Supplier<KernelAPI> kernelProvider = dependencies.provideDependency( KernelAPI.class );

        transactionStartTimeout = config.get( HaSettings.state_switch_timeout );

        DelegateInvocationHandler<ClusterMemberEvents> clusterEventsDelegateInvocationHandler =
                new DelegateInvocationHandler<>( ClusterMemberEvents.class );
        DelegateInvocationHandler<HighAvailabilityMemberContext> memberContextDelegateInvocationHandler =
                new DelegateInvocationHandler<>( HighAvailabilityMemberContext.class );
        DelegateInvocationHandler<ClusterMemberAvailability> clusterMemberAvailabilityDelegateInvocationHandler =
                new DelegateInvocationHandler<>( ClusterMemberAvailability.class );

        ClusterMemberEvents clusterEvents = dependencies.satisfyDependency(
                (ClusterMemberEvents) newProxyInstance(
                        ClusterMemberEvents.class.getClassLoader(),
                        new Class[]{ClusterMemberEvents.class, Lifecycle.class},
                        clusterEventsDelegateInvocationHandler ) );

        HighAvailabilityMemberContext memberContext = (HighAvailabilityMemberContext) newProxyInstance(
                HighAvailabilityMemberContext.class.getClassLoader(),
                new Class[]{HighAvailabilityMemberContext.class}, memberContextDelegateInvocationHandler );
        ClusterMemberAvailability clusterMemberAvailability = dependencies.satisfyDependency(
                (ClusterMemberAvailability) newProxyInstance(
                        ClusterMemberAvailability.class.getClassLoader(),
                        new Class[]{ClusterMemberAvailability.class},
                        clusterMemberAvailabilityDelegateInvocationHandler ) );

        // TODO There's a cyclical dependency here that should be fixed
        final AtomicReference<HighAvailabilityMemberStateMachine> electionProviderRef = new AtomicReference<>();
        ElectionCredentialsProvider electionCredentialsProvider = config.get( HaSettings.slave_only ) ?
                new NotElectableElectionCredentialsProvider() :
                new DefaultElectionCredentialsProvider(
                        config.get( ClusterSettings.server_id ),
                        new OnDiskLastTxIdGetter( platformModule.dependencies.provideDependency( NeoStores.class ) ),
                        () -> electionProviderRef.get().getCurrentState()
                );

        ObjectStreamFactory objectStreamFactory = new ObjectStreamFactory();

        ClusterClientModule clusterClientModule = new ClusterClientModule( clusteringLife, dependencies, monitors,
                config, logging, electionCredentialsProvider );
        ClusterClient clusterClient = clusterClientModule.clusterClient;
        PaxosClusterMemberEvents localClusterEvents = new PaxosClusterMemberEvents( clusterClient, clusterClient,
                clusterClient, clusterClient, logging.getInternalLogProvider(),
                item -> {
                    for ( MemberIsAvailable member : item.getCurrentAvailableMembers() )
                    {
                        if ( member.getRoleUri().getScheme().equals( "ha" ) )
                        {
                            if ( HighAvailabilityModeSwitcher.getServerId( member.getRoleUri() ).equals(
                                    platformModule.config.get( ClusterSettings.server_id ) ) )
                            {
                                logging.getInternalLog( PaxosClusterMemberEvents.class ).error(
                                        String.format( "Instance " +
                                                        "%s has" +
                                                        " the same serverId as ours (%s) - will not " +
                                                        "join this cluster",
                                                member.getRoleUri(),
                                                config.get( ClusterSettings.server_id ).toIntegerIndex()
                                        ) );
                                return true;
                            }
                        }
                    }
                    return true;
                }, new HANewSnapshotFunction(), objectStreamFactory, objectStreamFactory,
                platformModule.monitors.newMonitor( NamedThreadFactory.Monitor.class )
        );

        // Force a reelection after we enter the cluster
        // and when that election is finished refresh the snapshot
        clusterClient.addClusterListener( new ClusterListener.Adapter()
        {
            boolean hasRequestedElection = true; // This ensures that the election result is (at least) from our
            // request or thereafter

            @Override
            public void enteredCluster( ClusterConfiguration clusterConfiguration )
            {
                clusterClient.performRoleElections();
            }

            @Override
            public void elected( String role, InstanceId instanceId, URI electedMember )
            {
                if ( hasRequestedElection && role.equals( ClusterConfiguration.COORDINATOR ) )
                {
                    clusterClient.removeClusterListener( this );
                }
            }
        } );

        HighAvailabilityMemberContext localMemberContext = new SimpleHighAvailabilityMemberContext( clusterClient
                .getServerId(), config.get( HaSettings.slave_only ) );
        PaxosClusterMemberAvailability localClusterMemberAvailability = new PaxosClusterMemberAvailability(
                clusterClient.getServerId(), clusterClient, clusterClient, logging.getInternalLogProvider(),
                objectStreamFactory,
                objectStreamFactory );

        memberContextDelegateInvocationHandler.setDelegate( localMemberContext );
        clusterEventsDelegateInvocationHandler.setDelegate( localClusterEvents );
        clusterMemberAvailabilityDelegateInvocationHandler.setDelegate( localClusterMemberAvailability );

        ObservedClusterMembers observedMembers = new ObservedClusterMembers( logging.getInternalLogProvider(),
                clusterClient, clusterClient, clusterEvents, config.get( ClusterSettings.server_id ) );

        HighAvailabilityMemberStateMachine stateMachine = new HighAvailabilityMemberStateMachine( memberContext,
                platformModule.availabilityGuard, observedMembers, clusterEvents, clusterClient,
                logging.getInternalLogProvider() );

        members = dependencies.satisfyDependency( new ClusterMembers( observedMembers, stateMachine ) );

        memberStateMachine = paxosLife.add( stateMachine );
        electionProviderRef.set( memberStateMachine );

        HighAvailabilityLogger highAvailabilityLogger = new HighAvailabilityLogger( logging.getUserLogProvider(),
                config.get( ClusterSettings.server_id ) );
        platformModule.availabilityGuard.addListener( highAvailabilityLogger );
        clusterEvents.addClusterMemberListener( highAvailabilityLogger );
        clusterClient.addClusterListener( highAvailabilityLogger );

        paxosLife.add( (Lifecycle)clusterEvents );
        paxosLife.add( localClusterMemberAvailability );

        idGeneratorFactory = dependencies.satisfyDependency( createIdGeneratorFactory(
                masterDelegateInvocationHandler, logging.getInternalLogProvider(), requestContextFactory, fs ) );

        // TODO There's a cyclical dependency here that should be fixed
        final AtomicReference<HighAvailabilityModeSwitcher> exceptionHandlerRef = new AtomicReference<>();
        InvalidEpochExceptionHandler invalidEpochHandler = () -> exceptionHandlerRef.get().forceElections();

        MasterClientResolver masterClientResolver = new MasterClientResolver( logging.getInternalLogProvider(),
                responseUnpacker,
                invalidEpochHandler,
                config.get( HaSettings.read_timeout ).intValue(),
                config.get( HaSettings.lock_read_timeout ).intValue(),
                config.get( HaSettings.max_concurrent_channels_per_slave ),
                config.get( HaSettings.com_chunk_size ).intValue() );

        LastUpdateTime lastUpdateTime = new LastUpdateTime();

        DelegateInvocationHandler<UpdatePuller> updatePullerDelegate =
                new DelegateInvocationHandler<>( UpdatePuller.class );
        UpdatePuller updatePullerProxy = (UpdatePuller) Proxy.newProxyInstance(
                UpdatePuller.class .getClassLoader(), new Class[]{UpdatePuller.class}, updatePullerDelegate );
        dependencies.satisfyDependency( updatePullerProxy );

        PullerFactory pullerFactory = new PullerFactory( requestContextFactory, master, lastUpdateTime,
                logging.getInternalLogProvider(), serverId, invalidEpochHandler,
                config.get( HaSettings.pull_interval ), platformModule.jobScheduler,
                dependencies, platformModule.availabilityGuard, memberStateMachine, monitors );

        dependencies.satisfyDependency( paxosLife.add( pullerFactory.createObligationFulfiller( updatePullerProxy ) ) );

        Function<Slave, SlaveServer> slaveServerFactory =
                slave -> new SlaveServer( slave, slaveServerConfig( config ), logging.getInternalLogProvider(),
                        monitors.newMonitor( ByteCounterMonitor.class, SlaveServer.class ),
                        monitors.newMonitor( RequestMonitor.class, SlaveServer.class ) );

        SwitchToSlave switchToSlaveInstance = new SwitchToSlave( platformModule.storeDir, logging,
                platformModule.fileSystem, config, dependencies, (HaIdGeneratorFactory) idGeneratorFactory,
                masterDelegateInvocationHandler, clusterMemberAvailability, requestContextFactory, pullerFactory,
                platformModule.kernelExtensions.listFactories(), masterClientResolver,
                monitors.newMonitor( SwitchToSlave.Monitor.class ),
                monitors.newMonitor( StoreCopyClient.Monitor.class ),
                dependencies.provideDependency( NeoStoreDataSource.class ),
                dependencies.provideDependency( TransactionIdStore.class ),
                slaveServerFactory, updatePullerProxy, platformModule.pageCache,
                monitors, platformModule.transactionMonitor );

        final Factory<MasterImpl.SPI> masterSPIFactory =
                () -> new DefaultMasterImplSPI( platformModule.graphDatabaseFacade, platformModule.fileSystem,
                        platformModule.monitors,
                        labelTokenHolder, propertyKeyTokenHolder, relationshipTypeTokenHolder, idGeneratorFactory,
                        platformModule.dependencies.resolveDependency( TransactionCommitProcess.class ),
                        platformModule.dependencies.resolveDependency( CheckPointer.class ),
                        platformModule.dependencies.resolveDependency( TransactionIdStore.class ),
                        platformModule.dependencies.resolveDependency( LogicalTransactionStore.class ),
                        platformModule.dependencies.resolveDependency( NeoStoreDataSource.class ));

        final Factory<ConversationSPI> conversationSPIFactory =
                () -> new DefaultConversationSPI( lockManager, platformModule.jobScheduler );
        Factory<ConversationManager> conversationManagerFactory =
                () -> new ConversationManager( conversationSPIFactory.newInstance(), config );

        BiFunction<ConversationManager, LifeSupport, Master> masterFactory = ( conversationManager, life1 ) ->
                life1.add( new MasterImpl( masterSPIFactory.newInstance(),
                conversationManager, monitors.newMonitor( MasterImpl.Monitor.class, MasterImpl.class ), config ) );

        BiFunction<Master, ConversationManager, MasterServer> masterServerFactory =
                ( master1, conversationManager ) -> {
                    TransactionChecksumLookup txChecksumLookup = new TransactionChecksumLookup(
                            platformModule.dependencies.resolveDependency( TransactionIdStore.class ),
                            platformModule.dependencies.resolveDependency( LogicalTransactionStore.class ) );

                    return new MasterServer( master1, logging.getInternalLogProvider(),
                            masterServerConfig( config ),
                            new BranchDetectingTxVerifier( logging.getInternalLogProvider(), txChecksumLookup ),
                            monitors.newMonitor( ByteCounterMonitor.class, MasterServer.class ),
                            monitors.newMonitor( RequestMonitor.class, MasterServer.class ), conversationManager );
                };

        SwitchToMaster switchToMasterInstance = new SwitchToMaster( logging, (HaIdGeneratorFactory) idGeneratorFactory,
                config, dependencies.provideDependency( SlaveFactory.class ),
                conversationManagerFactory,
                masterFactory,
                masterServerFactory,
                masterDelegateInvocationHandler, clusterMemberAvailability,
                platformModule.dependencies.provideDependency( NeoStoreDataSource.class ) );

        ComponentSwitcherContainer componentSwitcherContainer = new ComponentSwitcherContainer();
        Supplier<StoreId> storeIdSupplier = () -> dependencies.resolveDependency( NeoStoreDataSource.class ).getStoreId();

        HighAvailabilityModeSwitcher highAvailabilityModeSwitcher = new HighAvailabilityModeSwitcher(
                switchToSlaveInstance, switchToMasterInstance, clusterClient, clusterMemberAvailability, clusterClient,
                storeIdSupplier, config.get( ClusterSettings.server_id ), componentSwitcherContainer,
                platformModule.dataSourceManager, logging );

        exceptionHandlerRef.set( highAvailabilityModeSwitcher );

        clusterClient.addBindingListener( highAvailabilityModeSwitcher );
        memberStateMachine.addHighAvailabilityMemberListener( highAvailabilityModeSwitcher );

        paxosLife.add( highAvailabilityModeSwitcher );

        componentSwitcherContainer.add( new UpdatePullerSwitcher( updatePullerDelegate, pullerFactory ) );

        life.add( requestContextFactory );
        life.add( responseUnpacker );

        platformModule.diagnosticsManager.appendProvider( new HighAvailabilityDiagnostics( memberStateMachine,
                clusterClient ) );

        // Create HA services
        lockManager = dependencies.satisfyDependency(
                createLockManager( componentSwitcherContainer, config, masterDelegateInvocationHandler,
                        requestContextFactory, platformModule.availabilityGuard, logging ) );

        propertyKeyTokenHolder = dependencies.satisfyDependency( new DelegatingPropertyKeyTokenHolder(
                createPropertyKeyCreator( config, componentSwitcherContainer,
                        masterDelegateInvocationHandler, requestContextFactory, kernelProvider ) ) );
        labelTokenHolder = dependencies.satisfyDependency( new DelegatingLabelTokenHolder( createLabelIdCreator( config,
                componentSwitcherContainer, masterDelegateInvocationHandler, requestContextFactory,
                kernelProvider ) ) );
        relationshipTypeTokenHolder = dependencies.satisfyDependency( new DelegatingRelationshipTypeTokenHolder(
                createRelationshipTypeCreator( config, componentSwitcherContainer,
                        masterDelegateInvocationHandler, requestContextFactory, kernelProvider ) ) );

        dependencies.satisfyDependency(
                createKernelData( config, platformModule.graphDatabaseFacade, members, fs, platformModule.pageCache,
                        storeDir, lastUpdateTime, dependencies.provideDependency( NeoStores.class ), life ) );

        commitProcessFactory = createCommitProcessFactory( dependencies, logging, monitors, config, paxosLife,
                clusterClient, members, platformModule.jobScheduler, master, requestContextFactory,
                componentSwitcherContainer );

        headerInformationFactory = createHeaderInformationFactory( memberContext );

        schemaWriteGuard = () -> {
            if ( !memberStateMachine.isMaster() )
            {
                throw new InvalidTransactionTypeKernelException(
                        "Modifying the database schema can only be done on the master server, " +
                                "this server is a slave. Please issue schema modification commands directly to " +
                                "the master."
                );
            }
        };

        config.augment( MapUtil.stringMap( GraphDatabaseSettings.allow_store_upgrade.name(), Settings.FALSE ) );

        constraintSemantics = new EnterpriseConstraintSemantics();

        registerRecovery( config.get( GraphDatabaseFacadeFactory.Configuration.editionName ), dependencies, logging );

        publishEditionInfo( config, dependencies.resolveDependency( UsageData.class ) );

        // Ordering of lifecycles is important. Clustering infrastructure should start before paxos components
        life.add( clusteringLife );
        life.add( paxosLife );
    }

    public HighlyAvailableEditionModule( final PlatformModule platformModule )
    {
        final LifeSupport life = platformModule.life;
        life.add( platformModule.dataSourceManager );

        final LifeSupport paxosLife = new LifeSupport();
        final LifeSupport clusteringLife = new LifeSupport();

        final FileSystemAbstraction fs = platformModule.fileSystem;
        final File storeDir = platformModule.storeDir;
        final Config config = platformModule.config;
        final Dependencies dependencies = platformModule.dependencies;
        final LogService logging = platformModule.logging;
        final Monitors monitors = platformModule.monitors;

        // Set Netty logger
        InternalLoggerFactory.setDefaultFactory( new NettyLoggerFactory( logging.getInternalLogProvider() ) );

        life.add( new BranchedDataMigrator( platformModule.storeDir ) );
        DelegateInvocationHandler<Master> masterDelegateInvocationHandler =
                new DelegateInvocationHandler<>( Master.class );
        Master master = (Master) newProxyInstance( Master.class.getClassLoader(), new Class[]{Master.class},
                masterDelegateInvocationHandler );
        InstanceId serverId = config.get( ClusterSettings.server_id );

        RequestContextFactory requestContextFactory = dependencies.satisfyDependency( new RequestContextFactory(
                serverId.toIntegerIndex(),
                dependencies.provideDependency( TransactionIdStore.class ) ) );

        TransactionCommittingResponseUnpacker responseUnpacker = dependencies.satisfyDependency(
                new TransactionCommittingResponseUnpacker( dependencies,
                        config.get( HaSettings.pull_apply_batch_size ) ) );

        Supplier<KernelAPI> kernelProvider = dependencies.provideDependency( KernelAPI.class );

        transactionStartTimeout = config.get( HaSettings.state_switch_timeout );

        DelegateInvocationHandler<ClusterMemberEvents> clusterEventsDelegateInvocationHandler =
                new DelegateInvocationHandler<>( ClusterMemberEvents.class );
        DelegateInvocationHandler<HighAvailabilityMemberContext> memberContextDelegateInvocationHandler =
                new DelegateInvocationHandler<>( HighAvailabilityMemberContext.class );
        DelegateInvocationHandler<ClusterMemberAvailability> clusterMemberAvailabilityDelegateInvocationHandler =
                new DelegateInvocationHandler<>( ClusterMemberAvailability.class );

        ClusterMemberEvents clusterEvents = dependencies.satisfyDependency(
                (ClusterMemberEvents) newProxyInstance(
                        ClusterMemberEvents.class.getClassLoader(),
                        new Class[]{ClusterMemberEvents.class, Lifecycle.class},
                        clusterEventsDelegateInvocationHandler ) );

        HighAvailabilityMemberContext memberContext = (HighAvailabilityMemberContext) newProxyInstance(
                HighAvailabilityMemberContext.class.getClassLoader(),
                new Class[]{HighAvailabilityMemberContext.class}, memberContextDelegateInvocationHandler );
        ClusterMemberAvailability clusterMemberAvailability = dependencies.satisfyDependency(
                (ClusterMemberAvailability) newProxyInstance(
                        ClusterMemberAvailability.class.getClassLoader(),
                        new Class[]{ClusterMemberAvailability.class},
                        clusterMemberAvailabilityDelegateInvocationHandler ) );

        // TODO There's a cyclical dependency here that should be fixed
        final AtomicReference<HighAvailabilityMemberStateMachine> electionProviderRef = new AtomicReference<>();
        ElectionCredentialsProvider electionCredentialsProvider = config.get( HaSettings.slave_only ) ?
                new NotElectableElectionCredentialsProvider() :
                new DefaultElectionCredentialsProvider(
                        config.get( ClusterSettings.server_id ),
                        new OnDiskLastTxIdGetter( platformModule.dependencies.provideDependency( NeoStores.class ) ),
                        () -> electionProviderRef.get().getCurrentState()
                );

        ObjectStreamFactory objectStreamFactory = new ObjectStreamFactory();

        ClusterClientModule clusterClientModule = new ClusterClientModule( clusteringLife, dependencies, monitors,
                config, logging, electionCredentialsProvider );
        ClusterClient clusterClient = clusterClientModule.clusterClient;
        PaxosClusterMemberEvents localClusterEvents = new PaxosClusterMemberEvents( clusterClient, clusterClient,
                clusterClient, clusterClient, logging.getInternalLogProvider(),
                item -> {
                    for ( MemberIsAvailable member : item.getCurrentAvailableMembers() )
                    {
                        if ( member.getRoleUri().getScheme().equals( "ha" ) )
                        {
                            if ( HighAvailabilityModeSwitcher.getServerId( member.getRoleUri() ).equals(
                                    platformModule.config.get( ClusterSettings.server_id ) ) )
                            {
                                logging.getInternalLog( PaxosClusterMemberEvents.class ).error(
                                        String.format( "Instance " +
                                                        "%s has" +
                                                        " the same serverId as ours (%s) - will not " +
                                                        "join this cluster",
                                                member.getRoleUri(),
                                                config.get( ClusterSettings.server_id ).toIntegerIndex()
                                        ) );
                                return true;
                            }
                        }
                    }
                    return true;
                }, new HANewSnapshotFunction(), objectStreamFactory, objectStreamFactory,
                platformModule.monitors.newMonitor( NamedThreadFactory.Monitor.class )
        );

        // Force a reelection after we enter the cluster
        // and when that election is finished refresh the snapshot
        clusterClient.addClusterListener( new ClusterListener.Adapter()
        {
            boolean hasRequestedElection = true; // This ensures that the election result is (at least) from our
            // request or thereafter

            @Override
            public void enteredCluster( ClusterConfiguration clusterConfiguration )
            {
                clusterClient.performRoleElections();
            }

            @Override
            public void elected( String role, InstanceId instanceId, URI electedMember )
            {
                if ( hasRequestedElection && role.equals( ClusterConfiguration.COORDINATOR ) )
                {
                    clusterClient.removeClusterListener( this );
                }
            }
        } );

        HighAvailabilityMemberContext localMemberContext = new SimpleHighAvailabilityMemberContext( clusterClient
                .getServerId(), config.get( HaSettings.slave_only ) );
        PaxosClusterMemberAvailability localClusterMemberAvailability = new PaxosClusterMemberAvailability(
                clusterClient.getServerId(), clusterClient, clusterClient, logging.getInternalLogProvider(),
                objectStreamFactory,
                objectStreamFactory );

        memberContextDelegateInvocationHandler.setDelegate( localMemberContext );
        clusterEventsDelegateInvocationHandler.setDelegate( localClusterEvents );
        clusterMemberAvailabilityDelegateInvocationHandler.setDelegate( localClusterMemberAvailability );

        ObservedClusterMembers observedMembers = new ObservedClusterMembers( logging.getInternalLogProvider(),
                clusterClient, clusterClient, clusterEvents, config.get( ClusterSettings.server_id ) );

        HighAvailabilityMemberStateMachine stateMachine = new HighAvailabilityMemberStateMachine( memberContext,
                platformModule.availabilityGuard, observedMembers, clusterEvents, clusterClient,
                logging.getInternalLogProvider() );

        members = dependencies.satisfyDependency( new ClusterMembers( observedMembers, stateMachine ) );

        memberStateMachine = paxosLife.add( stateMachine );
        electionProviderRef.set( memberStateMachine );

        HighAvailabilityLogger highAvailabilityLogger = new HighAvailabilityLogger( logging.getUserLogProvider(),
                config.get( ClusterSettings.server_id ) );
        platformModule.availabilityGuard.addListener( highAvailabilityLogger );
        clusterEvents.addClusterMemberListener( highAvailabilityLogger );
        clusterClient.addClusterListener( highAvailabilityLogger );

        paxosLife.add( (Lifecycle)clusterEvents );
        paxosLife.add( localClusterMemberAvailability );

        idGeneratorFactory = dependencies.satisfyDependency( createIdGeneratorFactory(
                masterDelegateInvocationHandler, logging.getInternalLogProvider(), requestContextFactory, fs ) );

        // TODO There's a cyclical dependency here that should be fixed
        final AtomicReference<HighAvailabilityModeSwitcher> exceptionHandlerRef = new AtomicReference<>();
        InvalidEpochExceptionHandler invalidEpochHandler = () -> exceptionHandlerRef.get().forceElections();

        MasterClientResolver masterClientResolver = new MasterClientResolver( logging.getInternalLogProvider(),
                responseUnpacker,
                invalidEpochHandler,
                config.get( HaSettings.read_timeout ).intValue(),
                config.get( HaSettings.lock_read_timeout ).intValue(),
                config.get( HaSettings.max_concurrent_channels_per_slave ),
                config.get( HaSettings.com_chunk_size ).intValue() );

        LastUpdateTime lastUpdateTime = new LastUpdateTime();

        DelegateInvocationHandler<UpdatePuller> updatePullerDelegate =
                new DelegateInvocationHandler<>( UpdatePuller.class );
        UpdatePuller updatePullerProxy = (UpdatePuller) Proxy.newProxyInstance(
                UpdatePuller.class .getClassLoader(), new Class[]{UpdatePuller.class}, updatePullerDelegate );
        dependencies.satisfyDependency( updatePullerProxy );

        PullerFactory pullerFactory = new PullerFactory( requestContextFactory, master, lastUpdateTime,
                logging.getInternalLogProvider(), serverId, invalidEpochHandler,
                config.get( HaSettings.pull_interval ), platformModule.jobScheduler,
                dependencies, platformModule.availabilityGuard, memberStateMachine, monitors );

        dependencies.satisfyDependency( paxosLife.add( pullerFactory.createObligationFulfiller( updatePullerProxy ) ) );

        Function<Slave, SlaveServer> slaveServerFactory = new Function<Slave, SlaveServer>()
        {
            @Override
            public SlaveServer apply( Slave slave ) throws RuntimeException
            {
                return new SlaveServer( slave, slaveServerConfig( config ), logging.getInternalLogProvider(),
                        monitors.newMonitor( ByteCounterMonitor.class, SlaveServer.class ),
                        monitors.newMonitor( RequestMonitor.class, SlaveServer.class ) );
            }
        };

        SwitchToSlave switchToSlaveInstance = new SwitchToSlave( platformModule.storeDir, logging,
                platformModule.fileSystem, config, dependencies, (HaIdGeneratorFactory) idGeneratorFactory,
                masterDelegateInvocationHandler, clusterMemberAvailability, requestContextFactory, pullerFactory,
                platformModule.kernelExtensions.listFactories(), masterClientResolver,
                monitors.newMonitor( SwitchToSlave.Monitor.class ),
                monitors.newMonitor( StoreCopyClient.Monitor.class ),
                dependencies.provideDependency( NeoStoreDataSource.class ),
                dependencies.provideDependency( TransactionIdStore.class ),
                slaveServerFactory, updatePullerProxy, platformModule.pageCache,
                monitors, platformModule.transactionMonitor );

        final Factory<MasterImpl.SPI> masterSPIFactory =
                () -> new DefaultMasterImplSPI( platformModule.graphDatabaseFacade, platformModule.fileSystem,
                        platformModule.monitors,
                        labelTokenHolder, propertyKeyTokenHolder, relationshipTypeTokenHolder, idGeneratorFactory,
                        platformModule.dependencies.resolveDependency( TransactionCommitProcess.class ),
                        platformModule.dependencies.resolveDependency( CheckPointer.class ),
                        platformModule.dependencies.resolveDependency( TransactionIdStore.class ),
                        platformModule.dependencies.resolveDependency( LogicalTransactionStore.class ),
                        platformModule.dependencies.resolveDependency( NeoStoreDataSource.class ));

        final Factory<ConversationSPI> conversationSPIFactory =
                () -> new DefaultConversationSPI( lockManager, platformModule.jobScheduler );
        Factory<ConversationManager> conversationManagerFactory =
                () -> new ConversationManager( conversationSPIFactory.newInstance(), config );

        BiFunction<ConversationManager, LifeSupport, Master> masterFactory = ( conversationManager, life1 ) ->
                life1.add( new MasterImpl( masterSPIFactory.newInstance(),
                conversationManager, monitors.newMonitor( MasterImpl.Monitor.class, MasterImpl.class ), config ) );

        BiFunction<Master, ConversationManager, MasterServer> masterServerFactory =
                ( master1, conversationManager ) -> {
                    TransactionChecksumLookup txChecksumLookup = new TransactionChecksumLookup(
                            platformModule.dependencies.resolveDependency( TransactionIdStore.class ),
                            platformModule.dependencies.resolveDependency( LogicalTransactionStore.class ) );

                    return new MasterServer( master1, logging.getInternalLogProvider(),
                            masterServerConfig( config ),
                            new BranchDetectingTxVerifier( logging.getInternalLogProvider(), txChecksumLookup ),
                            monitors.newMonitor( ByteCounterMonitor.class, MasterServer.class ),
                            monitors.newMonitor( RequestMonitor.class, MasterServer.class ), conversationManager );
                };

        SwitchToMaster switchToMasterInstance = new SwitchToMaster( logging, (HaIdGeneratorFactory) idGeneratorFactory,
                config, dependencies.provideDependency( SlaveFactory.class ),
                conversationManagerFactory,
                masterFactory,
                masterServerFactory,
                masterDelegateInvocationHandler, clusterMemberAvailability,
                platformModule.dependencies.provideDependency( NeoStoreDataSource.class ) );

        ComponentSwitcherContainer componentSwitcherContainer = new ComponentSwitcherContainer();
        Supplier<StoreId> storeIdSupplier = () -> dependencies.resolveDependency( NeoStoreDataSource.class ).getStoreId();

        HighAvailabilityModeSwitcher highAvailabilityModeSwitcher = new HighAvailabilityModeSwitcher(
                switchToSlaveInstance, switchToMasterInstance, clusterClient, clusterMemberAvailability, clusterClient,
                storeIdSupplier, config.get( ClusterSettings.server_id ), componentSwitcherContainer,
                platformModule.dataSourceManager, logging );

        exceptionHandlerRef.set( highAvailabilityModeSwitcher );

        clusterClient.addBindingListener( highAvailabilityModeSwitcher );
        memberStateMachine.addHighAvailabilityMemberListener( highAvailabilityModeSwitcher );

        paxosLife.add( highAvailabilityModeSwitcher );

        componentSwitcherContainer.add( new UpdatePullerSwitcher( updatePullerDelegate, pullerFactory ) );

        life.add( requestContextFactory );
        life.add( responseUnpacker );

        platformModule.diagnosticsManager.appendProvider( new HighAvailabilityDiagnostics( memberStateMachine,
                clusterClient ) );

        // Create HA services
        lockManager = dependencies.satisfyDependency(
                createLockManager( componentSwitcherContainer, config, masterDelegateInvocationHandler,
                        requestContextFactory, platformModule.availabilityGuard, logging ) );

        propertyKeyTokenHolder = dependencies.satisfyDependency( new DelegatingPropertyKeyTokenHolder(
                createPropertyKeyCreator( config, componentSwitcherContainer,
                        masterDelegateInvocationHandler, requestContextFactory, kernelProvider ) ) );
        labelTokenHolder = dependencies.satisfyDependency( new DelegatingLabelTokenHolder( createLabelIdCreator( config,
                componentSwitcherContainer, masterDelegateInvocationHandler, requestContextFactory,
                kernelProvider ) ) );
        relationshipTypeTokenHolder = dependencies.satisfyDependency( new DelegatingRelationshipTypeTokenHolder(
                createRelationshipTypeCreator( config, componentSwitcherContainer,
                        masterDelegateInvocationHandler, requestContextFactory, kernelProvider ) ) );

        dependencies.satisfyDependency(
                createKernelData( config, platformModule.graphDatabaseFacade, members, fs, platformModule.pageCache,
                        storeDir, lastUpdateTime, dependencies.provideDependency( NeoStores.class ), life ) );

        commitProcessFactory = createCommitProcessFactory( dependencies, logging, monitors, config, paxosLife,
                clusterClient, members, platformModule.jobScheduler, master, requestContextFactory,
                componentSwitcherContainer );

        headerInformationFactory = createHeaderInformationFactory( memberContext );

        schemaWriteGuard = () -> {
            if ( !memberStateMachine.isMaster() )
            {
                throw new InvalidTransactionTypeKernelException(
                        "Modifying the database schema can only be done on the master server, " +
                                "this server is a slave. Please issue schema modification commands directly to " +
                                "the master."
                );
            }
        };

        config.augment( MapUtil.stringMap( GraphDatabaseSettings.allow_store_upgrade.name(), Settings.FALSE ) );

        constraintSemantics = new EnterpriseConstraintSemantics();

        registerRecovery( config.get( GraphDatabaseFacadeFactory.Configuration.editionName ), dependencies, logging );

        publishEditionInfo( config, dependencies.resolveDependency( UsageData.class ) );

        // Ordering of lifecycles is important. Clustering infrastructure should start before paxos components
        life.add( clusteringLife );
        life.add( paxosLife );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.factory.HighlyAvailableEditionModule.HighlyAvailableEditionModule.slaveServerFactory.new Function<Slave,SlaveServer> with slave -> new SlaveServer(slave,slaveServerConfig(config),logging.getInternalLogProvider(),monitors.newMonitor(ByteCounterMonitor.class,SlaveServer.class),monitors.newMonitor(RequestMonitor.class,SlaveServer.class)) in method public HighlyAvailableEditionModule(platformModule PlatformModule) from class org.neo4j.kernel.ha.factory.HighlyAvailableEditionModule


    public static URI getUriForScheme( final String scheme, Iterable<URI> uris )
    {
        return first( filter( item -> {
            return item.getScheme().equals( scheme );
        }, uris ) );
    }

    public static URI getUriForScheme( final String scheme, Iterable<URI> uris )
    {
        return first( filter( new Predicate<URI>()
        {
            @Override
            public boolean test( URI item )
            {
                return item.getScheme().equals( scheme );
            }
        }, uris ) );
    }

Replace Anonymous With Lambda jmx.HaBeanIT.getUriForScheme.first.filter.new Predicate<URI> with item -> {return item.getScheme().equals(scheme); in method public getUriForScheme(scheme String, uris Iterable<URI>) : URI from class jmx.HaBeanIT


    private Iterable<String> stateMachineStates()
    {
        return Iterables.map( stateMachine -> {
            return stateMachine.getState().toString();
        }, server.getStateMachines().getStateMachines() );
    }

    private Iterable<String> stateMachineStates()
    {
        return Iterables.map( new Function<StateMachine, String>()
        {
            @Override
            public String apply( StateMachine stateMachine )
            {
                return stateMachine.getState().toString();
            }
        }, server.getStateMachines().getStateMachines() );
    }

Replace Anonymous With Lambda org.neo4j.ha.correctness.ClusterInstance.stateMachineStates.map.new Function<StateMachine,String> with stateMachine -> {return stateMachine.getState().toString(); in method private stateMachineStates() : Iterable<String> from class org.neo4j.ha.correctness.ClusterInstance


    private int commitLargeTx( final GraphDatabaseService db )
    {
        return template.with( db ).execute( transaction -> {
            // We're not actually asserting that this transaction produces log data
            // bigger than the threshold.
            long rotationThreshold = parseLongWithUnit( ROTATION_THRESHOLD );
            int nodeCount = 100;
            byte[] arrayProperty = new byte[(int) (rotationThreshold / nodeCount)];
            for ( int i = 0; i < nodeCount; i++ )
            {
                Node node = db.createNode();
                node.setProperty( "name", "big" + i );
                node.setProperty( "data", arrayProperty );
            }
            return nodeCount;
        } );
    }

    private int commitLargeTx( final GraphDatabaseService db )
    {
        return template.with( db ).execute( new Function<Transaction,Integer>()
        {
            @Override
            public Integer apply( Transaction transaction ) throws RuntimeException
            {
                // We're not actually asserting that this transaction produces log data
                // bigger than the threshold.
                long rotationThreshold = parseLongWithUnit( ROTATION_THRESHOLD );
                int nodeCount = 100;
                byte[] arrayProperty = new byte[(int) (rotationThreshold / nodeCount)];
                for ( int i = 0; i < nodeCount; i++ )
                {
                    Node node = db.createNode();
                    node.setProperty( "name", "big" + i );
                    node.setProperty( "data", arrayProperty );
                }
                return nodeCount;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.BiggerThanLogTxIT.commitLargeTx.execute.new Function<Transaction,Integer> with transaction -> {long rotationThreshold=parseLongWithUnit(ROTATION_THRESHOLD); in method private commitLargeTx(db GraphDatabaseService) : int from class org.neo4j.kernel.ha.BiggerThanLogTxIT


    @Test
    public void whenHAModeSwitcherSwitchesToSlaveTheOtherModeSwitcherDoNotGetTheOldMasterClient() throws Throwable
    {
        InstanceId me = new InstanceId( 1 );
        StoreId storeId = new StoreId();
        HighAvailabilityMemberContext context = mock( HighAvailabilityMemberContext.class );
        when( context.getMyId() ).thenReturn( me );
        AvailabilityGuard guard = mock( AvailabilityGuard.class );
        ObservedClusterMembers members = mock( ObservedClusterMembers.class );
        ClusterMember masterMember = mock( ClusterMember.class );
        when( masterMember.getHARole() ).thenReturn( "master" );
        when( masterMember.hasRole( "master" ) ).thenReturn( true );
        when( masterMember.getInstanceId() ).thenReturn( new InstanceId( 2 ) );
        when( masterMember.getStoreId() ).thenReturn( storeId );
        ClusterMember self = new ClusterMember( me );
        when( members.getMembers() ).thenReturn( Arrays.asList( self, masterMember ) );
        when( members.getCurrentMember() ).thenReturn( self );
        DependencyResolver dependencyResolver = mock( DependencyResolver.class );
        FileSystemAbstraction fs = mock( FileSystemAbstraction.class );
        when( fs.fileExists( any( File.class ) ) ).thenReturn( true );
        when( dependencyResolver.resolveDependency( FileSystemAbstraction.class ) ).thenReturn( fs );
        when( dependencyResolver.resolveDependency( Monitors.class ) ).thenReturn( new Monitors() );
        NeoStoreDataSource dataSource = mock( NeoStoreDataSource.class );
        when( dataSource.getDependencyResolver() ).thenReturn( dependencyResolver );
        when( dataSource.getStoreId() ).thenReturn( storeId );
        when( dependencyResolver.resolveDependency( NeoStoreDataSource.class ) ).thenReturn( dataSource );
        when( dependencyResolver.resolveDependency( TransactionIdStore.class ) ).
                thenReturn( new DeadSimpleTransactionIdStore() );
        when( dependencyResolver.resolveDependency( ObservedClusterMembers.class ) ).thenReturn( members );
        UpdatePuller updatePuller = mock( UpdatePuller.class );
        when( updatePuller.tryPullUpdates() ).thenReturn( true );
        when( dependencyResolver.resolveDependency( UpdatePuller.class ) ).thenReturn( updatePuller );

        ClusterMemberAvailability clusterMemberAvailability = mock( ClusterMemberAvailability.class );
        final TriggerableClusterMemberEvents events = new TriggerableClusterMemberEvents();

        Election election = mock( Election.class );
        HighAvailabilityMemberStateMachine stateMachine =
                new HighAvailabilityMemberStateMachine( context, guard, members, events, election,
                        NullLogProvider.getInstance() );

        ClusterMembers clusterMembers = new ClusterMembers( members, stateMachine );
        when( dependencyResolver.resolveDependency( ClusterMembers.class ) ).thenReturn( clusterMembers );

        stateMachine.init();
        stateMachine.start();

        final DelegateInvocationHandler<Master> handler = new DelegateInvocationHandler<>( Master.class );

        MasterClientResolver masterClientResolver = mock( MasterClientResolver.class );
        MasterClient masterClient = mock( MasterClient.class );
        when( masterClient.getProtocolVersion() ).thenReturn( MasterClient214.PROTOCOL_VERSION );
        when( masterClient.handshake( anyLong(), any( StoreId.class ) ) ).thenReturn(
                new Response<HandshakeResult>( new HandshakeResult( 0, 42 ), storeId, mock( ResourceReleaser.class ) )
                {
                    @Override
                    public void accept( Handler handler ) throws IOException
                    {
                    }

                    @Override
                    public boolean hasTransactionsToBeApplied()
                    {
                        return false;
                    }
                } );
        when( masterClient.toString() ).thenReturn( "TheExpectedMasterClient!" );
        when( masterClientResolver.instantiate( anyString(), anyInt(), any( Monitors.class ),
                any( StoreId.class ), any( LifeSupport.class ) ) ).thenReturn( masterClient );

        final CountDownLatch latch = new CountDownLatch( 2 );
        final AtomicBoolean switchedSuccessfully = new AtomicBoolean();

        SwitchToSlave.Monitor monitor = new SwitchToSlave.Monitor()
        {
            @Override
            public void switchToSlaveStarted()
            {
            }

            @Override
            public void switchToSlaveCompleted( boolean wasSuccessful )
            {
                switchedSuccessfully.set( wasSuccessful );
                latch.countDown();
            }

            @Override
            public void storeCopyStarted()
            {
            }

            @Override
            public void storeCopyCompleted( boolean wasSuccessful )
            {

            }

            @Override
            public void catchupStarted()
            {

            }

            @Override
            public void catchupCompleted()
            {

            }
        };

        Config config = new Config( Collections.singletonMap( ClusterSettings.server_id.name(), me.toString() ) );

        TransactionStats transactionCounters = mock( TransactionStats.class );
        when( transactionCounters.getNumberOfActiveTransactions() ).thenReturn( 0l );

        PageCache pageCacheMock = mock( PageCache.class );
        PagedFile pagedFileMock = mock( PagedFile.class );
        when( pagedFileMock.getLastPageId() ).thenReturn( 1l );
        when( pageCacheMock.map( any( File.class ), anyInt() ) ).thenReturn( pagedFileMock );

        TransactionIdStore transactionIdStoreMock = mock( TransactionIdStore.class );
        when( transactionIdStoreMock.getLastCommittedTransaction() ).thenReturn( new TransactionId( 0, 0 ) );
        SwitchToSlave switchToSlave = new SwitchToSlave( new File( "" ), NullLogService.getInstance(),
                mock( FileSystemAbstraction.class ),
                config, dependencyResolver,
                mock( HaIdGeneratorFactory.class ),
                handler,
                mock( ClusterMemberAvailability.class ), mock( RequestContextFactory.class ),
                mock( PullerFactory.class, RETURNS_MOCKS ),
                Iterables.<KernelExtensionFactory<?>>empty(), masterClientResolver,
                monitor,
                new StoreCopyClient.Monitor.Adapter(),
                Suppliers.singleton( dataSource ),
                Suppliers.singleton( transactionIdStoreMock ),
                slave -> {
                    SlaveServer mock = mock( SlaveServer.class );
                    when( mock.getSocketAddress() ).thenReturn( new InetSocketAddress( "localhost", 123 ) );
                    return mock;
                }, updatePuller, pageCacheMock, mock( Monitors.class ), transactionCounters );

        ComponentSwitcherContainer switcherContainer = new ComponentSwitcherContainer();
        HighAvailabilityModeSwitcher haModeSwitcher = new HighAvailabilityModeSwitcher( switchToSlave,
                mock( SwitchToMaster.class ), election, clusterMemberAvailability, mock( ClusterClient.class ),
                storeSupplierMock(), me, switcherContainer, neoStoreDataSourceSupplierMock(),
                NullLogService.getInstance() );
        haModeSwitcher.init();
        haModeSwitcher.start();
        haModeSwitcher.listeningAt( URI.create( "http://localhost:12345" ) );

        stateMachine.addHighAvailabilityMemberListener( haModeSwitcher );

        final AtomicReference<Master> ref = new AtomicReference<>( null );

        //noinspection unchecked
        AbstractComponentSwitcher<Object> otherModeSwitcher = new AbstractComponentSwitcher<Object>( mock(
                DelegateInvocationHandler.class ) )
        {
            @Override
            protected Object getSlaveImpl()
            {
                Master master = handler.cement();
                ref.set( master );
                latch.countDown();
                return null;
            }

            @Override
            protected Object getMasterImpl()
            {
                return null;
            }
        };
        switcherContainer.add( otherModeSwitcher );
        // When
        events.switchToSlave( me );

        // Then
        latch.await();
        assertTrue( "mode switch failed", switchedSuccessfully.get() );
        Master actual = ref.get();
        // let's test the toString()s since there are too many wrappers of proxies
        assertEquals( masterClient.toString(), actual.toString() );

        stateMachine.stop();
        stateMachine.shutdown();
        haModeSwitcher.stop();
        haModeSwitcher.shutdown();
    }

    @Test
    public void whenHAModeSwitcherSwitchesToSlaveTheOtherModeSwitcherDoNotGetTheOldMasterClient() throws Throwable
    {
        InstanceId me = new InstanceId( 1 );
        StoreId storeId = new StoreId();
        HighAvailabilityMemberContext context = mock( HighAvailabilityMemberContext.class );
        when( context.getMyId() ).thenReturn( me );
        AvailabilityGuard guard = mock( AvailabilityGuard.class );
        ObservedClusterMembers members = mock( ObservedClusterMembers.class );
        ClusterMember masterMember = mock( ClusterMember.class );
        when( masterMember.getHARole() ).thenReturn( "master" );
        when( masterMember.hasRole( "master" ) ).thenReturn( true );
        when( masterMember.getInstanceId() ).thenReturn( new InstanceId( 2 ) );
        when( masterMember.getStoreId() ).thenReturn( storeId );
        ClusterMember self = new ClusterMember( me );
        when( members.getMembers() ).thenReturn( Arrays.asList( self, masterMember ) );
        when( members.getCurrentMember() ).thenReturn( self );
        DependencyResolver dependencyResolver = mock( DependencyResolver.class );
        FileSystemAbstraction fs = mock( FileSystemAbstraction.class );
        when( fs.fileExists( any( File.class ) ) ).thenReturn( true );
        when( dependencyResolver.resolveDependency( FileSystemAbstraction.class ) ).thenReturn( fs );
        when( dependencyResolver.resolveDependency( Monitors.class ) ).thenReturn( new Monitors() );
        NeoStoreDataSource dataSource = mock( NeoStoreDataSource.class );
        when( dataSource.getDependencyResolver() ).thenReturn( dependencyResolver );
        when( dataSource.getStoreId() ).thenReturn( storeId );
        when( dependencyResolver.resolveDependency( NeoStoreDataSource.class ) ).thenReturn( dataSource );
        when( dependencyResolver.resolveDependency( TransactionIdStore.class ) ).
                thenReturn( new DeadSimpleTransactionIdStore() );
        when( dependencyResolver.resolveDependency( ObservedClusterMembers.class ) ).thenReturn( members );
        UpdatePuller updatePuller = mock( UpdatePuller.class );
        when( updatePuller.tryPullUpdates() ).thenReturn( true );
        when( dependencyResolver.resolveDependency( UpdatePuller.class ) ).thenReturn( updatePuller );

        ClusterMemberAvailability clusterMemberAvailability = mock( ClusterMemberAvailability.class );
        final TriggerableClusterMemberEvents events = new TriggerableClusterMemberEvents();

        Election election = mock( Election.class );
        HighAvailabilityMemberStateMachine stateMachine =
                new HighAvailabilityMemberStateMachine( context, guard, members, events, election,
                        NullLogProvider.getInstance() );

        ClusterMembers clusterMembers = new ClusterMembers( members, stateMachine );
        when( dependencyResolver.resolveDependency( ClusterMembers.class ) ).thenReturn( clusterMembers );

        stateMachine.init();
        stateMachine.start();

        final DelegateInvocationHandler<Master> handler = new DelegateInvocationHandler<>( Master.class );

        MasterClientResolver masterClientResolver = mock( MasterClientResolver.class );
        MasterClient masterClient = mock( MasterClient.class );
        when( masterClient.getProtocolVersion() ).thenReturn( MasterClient214.PROTOCOL_VERSION );
        when( masterClient.handshake( anyLong(), any( StoreId.class ) ) ).thenReturn(
                new Response<HandshakeResult>( new HandshakeResult( 0, 42 ), storeId, mock( ResourceReleaser.class ) )
                {
                    @Override
                    public void accept( Handler handler ) throws IOException
                    {
                    }

                    @Override
                    public boolean hasTransactionsToBeApplied()
                    {
                        return false;
                    }
                } );
        when( masterClient.toString() ).thenReturn( "TheExpectedMasterClient!" );
        when( masterClientResolver.instantiate( anyString(), anyInt(), any( Monitors.class ),
                any( StoreId.class ), any( LifeSupport.class ) ) ).thenReturn( masterClient );

        final CountDownLatch latch = new CountDownLatch( 2 );
        final AtomicBoolean switchedSuccessfully = new AtomicBoolean();

        SwitchToSlave.Monitor monitor = new SwitchToSlave.Monitor()
        {
            @Override
            public void switchToSlaveStarted()
            {
            }

            @Override
            public void switchToSlaveCompleted( boolean wasSuccessful )
            {
                switchedSuccessfully.set( wasSuccessful );
                latch.countDown();
            }

            @Override
            public void storeCopyStarted()
            {
            }

            @Override
            public void storeCopyCompleted( boolean wasSuccessful )
            {

            }

            @Override
            public void catchupStarted()
            {

            }

            @Override
            public void catchupCompleted()
            {

            }
        };

        Config config = new Config( Collections.singletonMap( ClusterSettings.server_id.name(), me.toString() ) );

        TransactionStats transactionCounters = mock( TransactionStats.class );
        when( transactionCounters.getNumberOfActiveTransactions() ).thenReturn( 0l );

        PageCache pageCacheMock = mock( PageCache.class );
        PagedFile pagedFileMock = mock( PagedFile.class );
        when( pagedFileMock.getLastPageId() ).thenReturn( 1l );
        when( pageCacheMock.map( any( File.class ), anyInt() ) ).thenReturn( pagedFileMock );

        TransactionIdStore transactionIdStoreMock = mock( TransactionIdStore.class );
        when( transactionIdStoreMock.getLastCommittedTransaction() ).thenReturn( new TransactionId( 0, 0 ) );
        SwitchToSlave switchToSlave = new SwitchToSlave( new File( "" ), NullLogService.getInstance(),
                mock( FileSystemAbstraction.class ),
                config, dependencyResolver,
                mock( HaIdGeneratorFactory.class ),
                handler,
                mock( ClusterMemberAvailability.class ), mock( RequestContextFactory.class ),
                mock( PullerFactory.class, RETURNS_MOCKS ),
                Iterables.<KernelExtensionFactory<?>>empty(), masterClientResolver,
                monitor,
                new StoreCopyClient.Monitor.Adapter(),
                Suppliers.singleton( dataSource ),
                Suppliers.singleton( transactionIdStoreMock ),
                new Function<Slave,SlaveServer>()
                {
                    @Override
                    public SlaveServer apply( Slave slave ) throws RuntimeException
                    {
                        SlaveServer mock = mock( SlaveServer.class );
                        when( mock.getSocketAddress() ).thenReturn( new InetSocketAddress( "localhost", 123 ) );
                        return mock;
                    }
                }, updatePuller, pageCacheMock, mock( Monitors.class ), transactionCounters );

        ComponentSwitcherContainer switcherContainer = new ComponentSwitcherContainer();
        HighAvailabilityModeSwitcher haModeSwitcher = new HighAvailabilityModeSwitcher( switchToSlave,
                mock( SwitchToMaster.class ), election, clusterMemberAvailability, mock( ClusterClient.class ),
                storeSupplierMock(), me, switcherContainer, neoStoreDataSourceSupplierMock(),
                NullLogService.getInstance() );
        haModeSwitcher.init();
        haModeSwitcher.start();
        haModeSwitcher.listeningAt( URI.create( "http://localhost:12345" ) );

        stateMachine.addHighAvailabilityMemberListener( haModeSwitcher );

        final AtomicReference<Master> ref = new AtomicReference<>( null );

        //noinspection unchecked
        AbstractComponentSwitcher<Object> otherModeSwitcher = new AbstractComponentSwitcher<Object>( mock(
                DelegateInvocationHandler.class ) )
        {
            @Override
            protected Object getSlaveImpl()
            {
                Master master = handler.cement();
                ref.set( master );
                latch.countDown();
                return null;
            }

            @Override
            protected Object getMasterImpl()
            {
                return null;
            }
        };
        switcherContainer.add( otherModeSwitcher );
        // When
        events.switchToSlave( me );

        // Then
        latch.await();
        assertTrue( "mode switch failed", switchedSuccessfully.get() );
        Master actual = ref.get();
        // let's test the toString()s since there are too many wrappers of proxies
        assertEquals( masterClient.toString(), actual.toString() );

        stateMachine.stop();
        stateMachine.shutdown();
        haModeSwitcher.stop();
        haModeSwitcher.shutdown();
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.HighAvailabilityMemberStateMachineTest.whenHAModeSwitcherSwitchesToSlaveTheOtherModeSwitcherDoNotGetTheOldMasterClient.switchToSlave.new SwitchToSlave.new Function<Slave,SlaveServer> with slave -> {SlaveServer mock=mock(SlaveServer.class); in method public whenHAModeSwitcherSwitchesToSlaveTheOtherModeSwitcherDoNotGetTheOldMasterClient() : void from class org.neo4j.kernel.ha.cluster.HighAvailabilityMemberStateMachineTest