    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 = new BiFunction<ConversationManager, LifeSupport, Master>()
        {
            @Override
            public Master apply( ConversationManager conversationManager, LifeSupport life )
            {
                return life.add( new MasterImpl( masterSPIFactory.newInstance(),
                        conversationManager, monitors.newMonitor( MasterImpl.Monitor.class, MasterImpl.class ), config ) );
            }
        };

        BiFunction<Master, ConversationManager, MasterServer> masterServerFactory = new BiFunction<Master, ConversationManager, MasterServer>()
        {
            @Override
            public MasterServer apply( final Master master, ConversationManager conversationManager ) throws RuntimeException
            {
                TransactionChecksumLookup txChecksumLookup = new TransactionChecksumLookup(
                        platformModule.dependencies.resolveDependency( TransactionIdStore.class ),
                        platformModule.dependencies.resolveDependency( LogicalTransactionStore.class ) );

                return new MasterServer( master, 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(),
                new org.neo4j.function.Predicate<PaxosClusterMemberEvents.ClusterMembersSnapshot>()
                {
                    @Override
                    public boolean test( PaxosClusterMemberEvents.ClusterMembersSnapshot 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 = new BiFunction<ConversationManager, LifeSupport, Master>()
        {
            @Override
            public Master apply( ConversationManager conversationManager, LifeSupport life )
            {
                return life.add( new MasterImpl( masterSPIFactory.newInstance(),
                        conversationManager, monitors.newMonitor( MasterImpl.Monitor.class, MasterImpl.class ), config ) );
            }
        };

        BiFunction<Master, ConversationManager, MasterServer> masterServerFactory = new BiFunction<Master, ConversationManager, MasterServer>()
        {
            @Override
            public MasterServer apply( final Master master, ConversationManager conversationManager ) throws RuntimeException
            {
                TransactionChecksumLookup txChecksumLookup = new TransactionChecksumLookup(
                        platformModule.dependencies.resolveDependency( TransactionIdStore.class ),
                        platformModule.dependencies.resolveDependency( LogicalTransactionStore.class ) );

                return new MasterServer( master, 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.localClusterEvents.new PaxosClusterMemberEvents.new org.neo4j.function.Predicate<PaxosClusterMemberEvents.ClusterMembersSnapshot> with 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())); in method public HighlyAvailableEditionModule(platformModule PlatformModule) from class org.neo4j.kernel.ha.factory.HighlyAvailableEditionModule


        @Override
        public void init() throws Throwable
        {
            currentFuture = starter.submit( (Callable<Void>) () -> {
                try
                {
                    wrapped.init();
                }
                catch ( Throwable throwable )
                {
                    throw new RuntimeException( throwable );
                }
                return null;
            } );
        }

        @Override
        public void init() throws Throwable
        {
            currentFuture = starter.submit( new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    try
                    {
                        wrapped.init();
                    }
                    catch ( Throwable throwable )
                    {
                        throw new RuntimeException( throwable );
                    }
                    return null;
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.FutureLifecycleAdapter.init.submit.new Callable<Void> with () -> {trywrapped.init(); in method public init() : void from class org.neo4j.kernel.impl.ha.ClusterManager.FutureLifecycleAdapter


        @Override
        public void start() throws Throwable
        {
            currentFuture.get();
            currentFuture = starter.submit( (Callable<Void>) () -> {
                try
                {
                    wrapped.start();
                }
                catch ( Throwable throwable )
                {
                    throw new RuntimeException( throwable );
                }
                return null;
            } );
        }

        @Override
        public void start() throws Throwable
        {
            currentFuture.get();
            currentFuture = starter.submit( new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    try
                    {
                        wrapped.start();
                    }
                    catch ( Throwable throwable )
                    {
                        throw new RuntimeException( throwable );
                    }
                    return null;
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.FutureLifecycleAdapter.start.submit.new Callable<Void> with () -> {trywrapped.start(); in method public start() : void from class org.neo4j.kernel.impl.ha.ClusterManager.FutureLifecycleAdapter


        @Override
        public void stop() throws Throwable
        {
            currentFuture.get();
            currentFuture = starter.submit( (Callable<Void>) () -> {
                try
                {
                    wrapped.stop();
                }
                catch ( Throwable throwable )
                {
                    throw new RuntimeException( throwable );
                }
                return null;
            } );
        }

        @Override
        public void stop() throws Throwable
        {
            currentFuture.get();
            currentFuture = starter.submit( new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    try
                    {
                        wrapped.stop();
                    }
                    catch ( Throwable throwable )
                    {
                        throw new RuntimeException( throwable );
                    }
                    return null;
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.FutureLifecycleAdapter.stop.submit.new Callable<Void> with () -> {trywrapped.stop(); in method public stop() : void from class org.neo4j.kernel.impl.ha.ClusterManager.FutureLifecycleAdapter


        @Override
        public void shutdown() throws Throwable
        {
            currentFuture = starter.submit( (Callable<Void>) () -> {
                try
                {
                    wrapped.shutdown();
                }
                catch ( Throwable throwable )
                {
                    throw new RuntimeException( throwable );
                }
                return null;
            } );
            currentFuture.get();
            starter.shutdownNow();
        }

        @Override
        public void shutdown() throws Throwable
        {
            currentFuture = starter.submit( new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    try
                    {
                        wrapped.shutdown();
                    }
                    catch ( Throwable throwable )
                    {
                        throw new RuntimeException( throwable );
                    }
                    return null;
                }
            } );
            currentFuture.get();
            starter.shutdownNow();
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.FutureLifecycleAdapter.shutdown.submit.new Callable<Void> with () -> {trywrapped.shutdown(); in method public shutdown() : void from class org.neo4j.kernel.impl.ha.ClusterManager.FutureLifecycleAdapter


    public static Predicate<ManagedCluster> allAvailabilityGuardsReleased()
    {
        return item -> {
            for ( HighlyAvailableGraphDatabase member : item.getAllMembers())
            {
                try
                {
                    member.beginTx().close();
                }
                catch ( TransactionFailureException e )
                {
                    return false;
                }
            }
            return true;
        };
    }

    public static Predicate<ManagedCluster> allAvailabilityGuardsReleased()
    {
        return new Predicate<ManagedCluster>()
        {
            @Override
            public boolean test( ManagedCluster item )
            {
                for ( HighlyAvailableGraphDatabase member : item.getAllMembers())
                {
                    try
                    {
                        member.beginTx().close();
                    }
                    catch ( TransactionFailureException e )
                    {
                        return false;
                    }
                }
                return true;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.allAvailabilityGuardsReleased.new Predicate<ManagedCluster> with item -> {for(HighlyAvailableGraphDatabase member: item.getAllMembers()){trymember.beginTx().close(); in method public allAvailabilityGuardsReleased() : Predicate<ManagedCluster> from class org.neo4j.kernel.impl.ha.ClusterManager


    public static Predicate<ManagedCluster> memberSeesOtherMemberAsFailed(
            final HighlyAvailableGraphDatabase observer, final HighlyAvailableGraphDatabase observed )
    {
        return cluster -> {
            InstanceId observedServerId = observed.getDependencyResolver().resolveDependency( Config.class )
                    .get( ClusterSettings.server_id );
            for ( ClusterMember member : observer.getDependencyResolver().resolveDependency(
                    ClusterMembers.class ).getMembers() )
            {
                if ( member.getInstanceId().equals( observedServerId ) )
                {
                    return !member.isAlive();
                }
            }
            throw new IllegalStateException( observed + " not a member according to " + observer );
        };
    }

    public static Predicate<ManagedCluster> memberSeesOtherMemberAsFailed(
            final HighlyAvailableGraphDatabase observer, final HighlyAvailableGraphDatabase observed )
    {
        return new Predicate<ManagedCluster>()
        {
            @Override
            public boolean test( ManagedCluster cluster )
            {
                InstanceId observedServerId = observed.getDependencyResolver().resolveDependency( Config.class )
                        .get( ClusterSettings.server_id );
                for ( ClusterMember member : observer.getDependencyResolver().resolveDependency(
                        ClusterMembers.class ).getMembers() )
                {
                    if ( member.getInstanceId().equals( observedServerId ) )
                    {
                        return !member.isAlive();
                    }
                }
                throw new IllegalStateException( observed + " not a member according to " + observer );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.memberSeesOtherMemberAsFailed.new Predicate<ManagedCluster> with cluster -> {InstanceId observedServerId=observed.getDependencyResolver().resolveDependency(Config.class).get(ClusterSettings.server_id); in method public memberSeesOtherMemberAsFailed(observer HighlyAvailableGraphDatabase, observed HighlyAvailableGraphDatabase) : Predicate<ManagedCluster> from class org.neo4j.kernel.impl.ha.ClusterManager


    public static <T> Predicate<T> in( final Iterable<T> allowed )
    {
        return item -> {
            for ( T allow : allowed )
            {
                if ( allow.equals( item ) )
                {
                    return true;
                }
            }
            return false;
        };
    }}

    @Deprecated
    public static <T> Predicate<T> in( final Iterable<T> allowed )
    {
        return new Predicate<T>()
        {
            @Override
            public boolean accept( T item )
            {
                for ( T allow : allowed )
                {
                    if ( allow.equals( item ) )
                    {
                        return true;
                    }
                }
                return false;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.helpers.Predicates.in.new Predicate<T> with item -> {for(T allow: allowed){if(allow.equals(item)){return true; in method public in(allowed Iterable<T>) : Predicate<T> from class org.neo4j.function.Predicates


    private <R> List<FlyweightHolder<R>>  acquireFromPool( final LinkedQueuePool<R> pool, int times )
            throws InterruptedException
    {
        List<FlyweightHolder<R>> acquirers = new LinkedList<>();
        for ( int i = 0; i < times; i++ )
        {
            FlyweightHolder<R> holder = new FlyweightHolder<>( pool );
            acquirers.add( holder );
            holder.run();
        }
        return acquirers;
    }

    private <R> List<FlyweightHolder<R>>  acquireFromPool( final LinkedQueuePool<R> pool, int times )
            throws InterruptedException
    {
        List<FlyweightHolder<R>> acquirers = new LinkedList<>();
        for ( int i = 0; i < times; i++ )
        {
            FlyweightHolder<R> holder = new FlyweightHolder<R>( pool );
            acquirers.add( holder );
            holder.run();
        }
        return acquirers;
    }

Replace Generic With Diamond FlyweightHolder<R> with FlyweightHolder<> in method private acquireFromPool(pool LinkedQueuePool<R>, times int) : List<FlyweightHolder<R>> from class org.neo4j.collection.pool.LinkedQueuePoolTest


    public Result runFullConsistencyCheck( final File storeDir, Config tuningConfiguration,
                                           ProgressMonitorFactory progressFactory,
                                           final LogProvider logProvider,
                                           final FileSystemAbstraction fileSystem,
                                           final PageCache pageCache )
            throws ConsistencyCheckIncompleteException
    {
        Log log = logProvider.getLog( getClass() );
        Config consistencyCheckerConfig = tuningConfiguration.with(
                MapUtil.stringMap( GraphDatabaseSettings.read_only.name(), Settings.TRUE ) );

        StoreFactory factory = new StoreFactory(
                storeDir,
                consistencyCheckerConfig,
                new DefaultIdGeneratorFactory( fileSystem ),
                pageCache, fileSystem, logProvider
        );

        ConsistencySummaryStatistics summary;
        final File reportFile = chooseReportPath( storeDir, tuningConfiguration );
        Log reportLog = new ConsistencyReportLog( Suppliers.lazySingleton( () -> {
            try
            {
                return new PrintWriter( createOrOpenAsOuputStream( fileSystem, reportFile, true ) );
            } catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
        } ) );

        try ( NeoStores neoStores = factory.openAllNeoStores() )
        {
            StoreAccess store = new StoreAccess( neoStores ).initialize();
            LabelScanStore labelScanStore = null;
            try
            {
                labelScanStore = new LuceneLabelScanStoreBuilder(
                        storeDir, store.getRawNeoStores(), fileSystem, logProvider ).build();
                SchemaIndexProvider indexes = new LuceneSchemaIndexProvider(
                        fileSystem, DirectoryFactory.PERSISTENT,
                        storeDir );
                DirectStoreAccess stores = new DirectStoreAccess( store, labelScanStore, indexes );
                FullCheck check = new FullCheck( tuningConfiguration, progressFactory );
                summary = check.execute( stores, new DuplicatingLog( log, reportLog ) );
            }
            finally
            {
                try
                {
                    if ( null != labelScanStore )
                    {
                        labelScanStore.shutdown();
                    }
                }
                catch ( IOException e )
                {
                    log.error( "Failure during shutdown of label scan store", e );
                }
            }
        }

        if ( !summary.isConsistent() )
        {
            log.warn( "See '%s' for a detailed consistency report.", reportFile.getPath() );
            return Result.FAILURE;
        }

        return Result.SUCCESS;
    }

    public Result runFullConsistencyCheck( final File storeDir, Config tuningConfiguration,
                                           ProgressMonitorFactory progressFactory,
                                           final LogProvider logProvider,
                                           final FileSystemAbstraction fileSystem,
                                           final PageCache pageCache )
            throws ConsistencyCheckIncompleteException
    {
        Log log = logProvider.getLog( getClass() );
        Config consistencyCheckerConfig = tuningConfiguration.with(
                MapUtil.stringMap( GraphDatabaseSettings.read_only.name(), Settings.TRUE ) );

        StoreFactory factory = new StoreFactory(
                storeDir,
                consistencyCheckerConfig,
                new DefaultIdGeneratorFactory( fileSystem ),
                pageCache, fileSystem, logProvider
        );

        ConsistencySummaryStatistics summary;
        final File reportFile = chooseReportPath( storeDir, tuningConfiguration );
        Log reportLog = new ConsistencyReportLog( Suppliers.lazySingleton( new Supplier<PrintWriter>()
        {
            @Override
            public PrintWriter get()
            {
                try
                {
                    return new PrintWriter( createOrOpenAsOuputStream( fileSystem, reportFile, true ) );
                } catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        } ) );

        try ( NeoStores neoStores = factory.openAllNeoStores() )
        {
            StoreAccess store = new StoreAccess( neoStores ).initialize();
            LabelScanStore labelScanStore = null;
            try
            {
                labelScanStore = new LuceneLabelScanStoreBuilder(
                        storeDir, store.getRawNeoStores(), fileSystem, logProvider ).build();
                SchemaIndexProvider indexes = new LuceneSchemaIndexProvider(
                        fileSystem, DirectoryFactory.PERSISTENT,
                        storeDir );
                DirectStoreAccess stores = new DirectStoreAccess( store, labelScanStore, indexes );
                FullCheck check = new FullCheck( tuningConfiguration, progressFactory );
                summary = check.execute( stores, new DuplicatingLog( log, reportLog ) );
            }
            finally
            {
                try
                {
                    if ( null != labelScanStore )
                    {
                        labelScanStore.shutdown();
                    }
                }
                catch ( IOException e )
                {
                    log.error( "Failure during shutdown of label scan store", e );
                }
            }
        }

        if ( !summary.isConsistent() )
        {
            log.warn( "See '%s' for a detailed consistency report.", reportFile.getPath() );
            return Result.FAILURE;
        }

        return Result.SUCCESS;
    }

Replace Anonymous With Lambda org.neo4j.legacy.consistency.ConsistencyCheckService.runFullConsistencyCheck.reportLog.new ConsistencyReportLog.lazySingleton.new Supplier<PrintWriter> with () -> {tryreturn new PrintWriter(createOrOpenAsOuputStream(fileSystem,reportFile,true)); in method public runFullConsistencyCheck(storeDir File, tuningConfiguration Config, progressFactory ProgressMonitorFactory, logProvider LogProvider, fileSystem FileSystemAbstraction, pageCache PageCache) : Result from class org.neo4j.legacy.consistency.ConsistencyCheckService


    public Result runFullConsistencyCheck( final File storeDir, Config tuningConfiguration,
            ProgressMonitorFactory progressFactory, final LogProvider logProvider,
            final FileSystemAbstraction fileSystem, final PageCache pageCache, final boolean verbose )
            throws ConsistencyCheckIncompleteException
    {
        Log log = logProvider.getLog( getClass() );
        Config consistencyCheckerConfig = tuningConfiguration.with(
                MapUtil.stringMap( GraphDatabaseSettings.read_only.name(), Settings.TRUE ) );
        StoreFactory factory = new StoreFactory( storeDir, consistencyCheckerConfig,
                new DefaultIdGeneratorFactory( fileSystem ), pageCache, fileSystem, logProvider );

        ConsistencySummaryStatistics summary;
        final File reportFile = chooseReportPath( storeDir, tuningConfiguration );
        Log reportLog = new ConsistencyReportLog( Suppliers.lazySingleton( () -> {
            try
            {
                return new PrintWriter( createOrOpenAsOuputStream( fileSystem, reportFile, true ) );
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
        } ) );

        try ( NeoStores neoStores = factory.openAllNeoStores() )
        {
            LabelScanStore labelScanStore = null;
            try
            {
                labelScanStore = new LuceneLabelScanStoreBuilder(
                        storeDir, neoStores, fileSystem, logProvider ).build();
                SchemaIndexProvider indexes = new LuceneSchemaIndexProvider(
                        fileSystem,
                        DirectoryFactory.PERSISTENT,
                        storeDir );

                int numberOfThreads = defaultConsistencyCheckThreadsNumber();
                Statistics statistics;
                StoreAccess storeAccess;
                AccessStatistics stats = new AccessStatistics();
                if ( verbose )
                {
                    statistics = new VerboseStatistics( stats, new DefaultCounts( numberOfThreads ), log );
                    storeAccess = new AccessStatsKeepingStoreAccess( neoStores, stats );
                }
                else
                {
                    statistics = Statistics.NONE;
                    storeAccess = new StoreAccess( neoStores );
                }
                storeAccess.initialize();
                DirectStoreAccess stores = new DirectStoreAccess( storeAccess, labelScanStore, indexes );
                FullCheck check = new FullCheck( tuningConfiguration, progressFactory, statistics, numberOfThreads );
                summary = check.execute( stores, new DuplicatingLog( log, reportLog ) );
            }
            finally
            {
                try
                {
                    if ( null != labelScanStore )
                    {
                        labelScanStore.shutdown();
                    }
                }
                catch ( IOException e )
                {
                    log.error( "Failure during shutdown of label scan store", e );
                }
            }
        }

        if ( !summary.isConsistent() )
        {
            log.warn( "See '%s' for a detailed consistency report.", reportFile.getPath() );
            return Result.FAILURE;
        }
        return Result.SUCCESS;
    }

    public Result runFullConsistencyCheck( final File storeDir, Config tuningConfiguration,
            ProgressMonitorFactory progressFactory, final LogProvider logProvider,
            final FileSystemAbstraction fileSystem, final PageCache pageCache, final boolean verbose )
            throws ConsistencyCheckIncompleteException
    {
        Log log = logProvider.getLog( getClass() );
        Config consistencyCheckerConfig = tuningConfiguration.with(
                MapUtil.stringMap( GraphDatabaseSettings.read_only.name(), Settings.TRUE ) );
        StoreFactory factory = new StoreFactory( storeDir, consistencyCheckerConfig,
                new DefaultIdGeneratorFactory( fileSystem ), pageCache, fileSystem, logProvider );

        ConsistencySummaryStatistics summary;
        final File reportFile = chooseReportPath( storeDir, tuningConfiguration );
        Log reportLog = new ConsistencyReportLog( Suppliers.lazySingleton( new Supplier<PrintWriter>()
        {
            @Override
            public PrintWriter get()
            {
                try
                {
                    return new PrintWriter( createOrOpenAsOuputStream( fileSystem, reportFile, true ) );
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        } ) );

        try ( NeoStores neoStores = factory.openAllNeoStores() )
        {
            LabelScanStore labelScanStore = null;
            try
            {
                labelScanStore = new LuceneLabelScanStoreBuilder(
                        storeDir, neoStores, fileSystem, logProvider ).build();
                SchemaIndexProvider indexes = new LuceneSchemaIndexProvider(
                        fileSystem,
                        DirectoryFactory.PERSISTENT,
                        storeDir );

                int numberOfThreads = defaultConsistencyCheckThreadsNumber();
                Statistics statistics;
                StoreAccess storeAccess;
                AccessStatistics stats = new AccessStatistics();
                if ( verbose )
                {
                    statistics = new VerboseStatistics( stats, new DefaultCounts( numberOfThreads ), log );
                    storeAccess = new AccessStatsKeepingStoreAccess( neoStores, stats );
                }
                else
                {
                    statistics = Statistics.NONE;
                    storeAccess = new StoreAccess( neoStores );
                }
                storeAccess.initialize();
                DirectStoreAccess stores = new DirectStoreAccess( storeAccess, labelScanStore, indexes );
                FullCheck check = new FullCheck( tuningConfiguration, progressFactory, statistics, numberOfThreads );
                summary = check.execute( stores, new DuplicatingLog( log, reportLog ) );
            }
            finally
            {
                try
                {
                    if ( null != labelScanStore )
                    {
                        labelScanStore.shutdown();
                    }
                }
                catch ( IOException e )
                {
                    log.error( "Failure during shutdown of label scan store", e );
                }
            }
        }

        if ( !summary.isConsistent() )
        {
            log.warn( "See '%s' for a detailed consistency report.", reportFile.getPath() );
            return Result.FAILURE;
        }
        return Result.SUCCESS;
    }

Replace Anonymous With Lambda org.neo4j.consistency.ConsistencyCheckService.runFullConsistencyCheck.reportLog.new ConsistencyReportLog.lazySingleton.new Supplier<PrintWriter> with () -> {tryreturn new PrintWriter(createOrOpenAsOuputStream(fileSystem,reportFile,true)); in method public runFullConsistencyCheck(storeDir File, tuningConfiguration Config, progressFactory ProgressMonitorFactory, logProvider LogProvider, fileSystem FileSystemAbstraction, pageCache PageCache, verbose boolean) : Result from class org.neo4j.consistency.ConsistencyCheckService


    /**
     * @deprecated use {@link #latchGuardedValue(Supplier, CountDownLatch, String)} instead
     * @param value the value getter
     * @param guardedByLatch the guard
     * @param jobDescription description
     * @param <T> the type
     * @return the future from which to get the value
     */
    @Deprecated
    public static <T> Future<T> latchGuardedValue( final ValueGetter<T> value, final CountDownLatch guardedByLatch,
            final String jobDescription )
    {
        return latchGuardedValue( (Supplier<T>) () -> {
            return value.get();
        }, guardedByLatch, jobDescription );
    }

    /**
     * @deprecated use {@link #latchGuardedValue(Supplier, CountDownLatch, String)} instead
     * @param value the value getter
     * @param guardedByLatch the guard
     * @param jobDescription description
     * @param <T> the type
     * @return the future from which to get the value
     */
    @Deprecated
    public static <T> Future<T> latchGuardedValue( final ValueGetter<T> value, final CountDownLatch guardedByLatch,
            final String jobDescription )
    {
        return latchGuardedValue( new Supplier<T>()
        {
            @Override
            public T get()
            {
                return value.get();
            }
        }, guardedByLatch, jobDescription );
    }

Replace Anonymous With Lambda org.neo4j.helpers.FutureAdapter.latchGuardedValue.latchGuardedValue.new Supplier<T> with () -> {return value.get(); in method public latchGuardedValue(value ValueGetter<T>, guardedByLatch CountDownLatch, jobDescription String) : Future<T> from class org.neo4j.helpers.FutureAdapter


    /**
     * @deprecated use {@link #await(Supplier, Predicate, long, TimeUnit)} instead
     * @param provider the provider
     * @param predicate the predicate
     * @param timeout the timeout
     * @param unit the unit
     * @param <TYPE> the type
     * @throws InterruptedException if interrupted
     * @throws TimeoutException if timeout occurs
     */
    @Deprecated
    public static <TYPE> void await( final Provider<TYPE> provider, Predicate<TYPE> predicate, long timeout, TimeUnit unit )
            throws TimeoutException, InterruptedException
    {
        await( (Supplier<TYPE>) () -> {
            return provider.instance();
        }, predicate, timeout, unit );
    }

    /**
     * @deprecated use {@link #await(Supplier, Predicate, long, TimeUnit)} instead
     * @param provider the provider
     * @param predicate the predicate
     * @param timeout the timeout
     * @param unit the unit
     * @param <TYPE> the type
     * @throws InterruptedException if interrupted
     * @throws TimeoutException if timeout occurs
     */
    @Deprecated
    public static <TYPE> void await( final Provider<TYPE> provider, Predicate<TYPE> predicate, long timeout, TimeUnit unit )
            throws TimeoutException, InterruptedException
    {
        await( new Supplier<TYPE>()
        {
            @Override
            public TYPE get()
            {
                return provider.instance();
            }
        }, predicate, timeout, unit );
    }

Replace Anonymous With Lambda org.neo4j.helpers.Predicates.await.await.new Supplier<TYPE> with () -> {return provider.instance(); in method public await(provider Provider<TYPE>, predicate Predicate<TYPE>, timeout long, unit TimeUnit) : void from class org.neo4j.helpers.Predicates


    /**
     * Creates a {@link DataFactory} where data exists in multiple files. If the first line of the first file is a header,
     * {@link #defaultFormatNodeFileHeader()} can be used to extract that.
     *
     * @return {@link DataFactory} that returns a {@link CharSeeker} over all the supplied {@code files}.
     */
    public static <ENTITY extends InputEntity> DataFactory<ENTITY> data( final Function<ENTITY,ENTITY> decorator,
            final Charset charset, final File... files )
    {
        if ( files.length == 0 )
        {
            throw new IllegalArgumentException( "No files specified" );
        }

        return config -> new Data<ENTITY>()
        {
            @Override
            public CharSeeker stream()
            {
                try
                {
                    return charSeeker( files( charset, files ), config, true );
                }
                catch ( IOException e )
                {
                    throw new InputException( e.getMessage(), e );
                }
            }

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

    /**
     * Creates a {@link DataFactory} where data exists in multiple files. If the first line of the first file is a header,
     * {@link #defaultFormatNodeFileHeader()} can be used to extract that.
     *
     * @return {@link DataFactory} that returns a {@link CharSeeker} over all the supplied {@code files}.
     */
    public static <ENTITY extends InputEntity> DataFactory<ENTITY> data( final Function<ENTITY,ENTITY> decorator,
            final Charset charset, final File... files )
    {
        if ( files.length == 0 )
        {
            throw new IllegalArgumentException( "No files specified" );
        }

        return new DataFactory<ENTITY>()
        {
            @Override
            public Data<ENTITY> create( final Configuration config )
            {
                return new Data<ENTITY>()
                {
                    @Override
                    public CharSeeker stream()
                    {
                        try
                        {
                            return charSeeker( files( charset, files ), config, true );
                        }
                        catch ( IOException e )
                        {
                            throw new InputException( e.getMessage(), e );
                        }
                    }

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

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.input.csv.DataFactories.data.new DataFactory<ENTITY> with config -> new Data<ENTITY>(){ in method public data(decorator Function<ENTITY,ENTITY>, charset Charset, files File...) : DataFactory<ENTITY> from class org.neo4j.unsafe.impl.batchimport.input.csv.DataFactories


    /**
     * @param readable we need to have this as a {@link Factory} since one data file may be opened and scanned
     * multiple times.
     * @return {@link DataFactory} that returns a {@link CharSeeker} over the supplied {@code readable}
     */
    public static <ENTITY extends InputEntity> DataFactory<ENTITY> data( final Function<ENTITY,ENTITY> decorator,
            final Supplier<CharReadable> readable )
    {
        return config -> new Data<ENTITY>()
        {
            @Override
            public CharSeeker stream()
            {
                return charSeeker( readable.get(), config, true );
            }

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

    /**
     * @param readable we need to have this as a {@link Factory} since one data file may be opened and scanned
     * multiple times.
     * @return {@link DataFactory} that returns a {@link CharSeeker} over the supplied {@code readable}
     */
    public static <ENTITY extends InputEntity> DataFactory<ENTITY> data( final Function<ENTITY,ENTITY> decorator,
            final Supplier<CharReadable> readable )
    {
        return new DataFactory<ENTITY>()
        {
            @Override
            public Data<ENTITY> create( final Configuration config )
            {
                return new Data<ENTITY>()
                {
                    @Override
                    public CharSeeker stream()
                    {
                        return charSeeker( readable.get(), config, true );
                    }

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

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.input.csv.DataFactories.data.new DataFactory<ENTITY> with config -> new Data<ENTITY>(){ in method public data(decorator Function<ENTITY,ENTITY>, readable Supplier<CharReadable>) : DataFactory<ENTITY> from class org.neo4j.unsafe.impl.batchimport.input.csv.DataFactories


    @Override
    public long receive( final long ticket, final T batch )
    {
        // Don't go too far ahead
        long idleTime = await( catchUp, workAheadSize );
        incrementQueue();

        executor.submit( sender -> {
            assertHealthy();
            sender.initialize( ticket );
            try
            {
                // If we're ordering tickets we will force calls to #permit to be ordered by ticket
                // since grabbing a permit may include locking.
                if ( guarantees( ORDER_PROCESS ) )
                {
                    await( rightBeginTicket, ticket );
                }
                try ( Resource precondition = permit( batch ) )
                {
                    begunBatches.incrementAndGet();
                    long startTime1 = currentTimeMillis();
                    process( batch, sender );
                    if ( downstream == null )
                    {
                        // No batches were emmitted so we couldn't track done batches in that way.
                        // We can see that we're the last step so increment here instead
                        doneBatches.incrementAndGet();
                    }
                    totalProcessingTime.add( currentTimeMillis() - startTime1 - sender.sendTime );
                }

                decrementQueue();
                checkNotifyEndDownstream();
            }
            catch ( Throwable e )
            {
                issuePanic( e );
            }
        } );

        return idleTime;
    }

    @Override
    public long receive( final long ticket, final T batch )
    {
        // Don't go too far ahead
        long idleTime = await( catchUp, workAheadSize );
        incrementQueue();

        executor.submit( new Task<Sender>()
        {
            @Override
            public void run( Sender sender )
            {
                assertHealthy();
                sender.initialize( ticket );
                try
                {
                    // If we're ordering tickets we will force calls to #permit to be ordered by ticket
                    // since grabbing a permit may include locking.
                    if ( guarantees( ORDER_PROCESS ) )
                    {
                        await( rightBeginTicket, ticket );
                    }
                    try ( Resource precondition = permit( batch ) )
                    {
                        begunBatches.incrementAndGet();
                        long startTime = currentTimeMillis();
                        process( batch, sender );
                        if ( downstream == null )
                        {
                            // No batches were emmitted so we couldn't track done batches in that way.
                            // We can see that we're the last step so increment here instead
                            doneBatches.incrementAndGet();
                        }
                        totalProcessingTime.add( currentTimeMillis()-startTime-sender.sendTime );
                    }

                    decrementQueue();
                    checkNotifyEndDownstream();
                }
                catch ( Throwable e )
                {
                    issuePanic( e );
                }
            }
        } );

        return idleTime;
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.staging.ProcessorStep.receive.submit.new Task<Sender> with sender -> {assertHealthy(); in method public receive(ticket long, batch T) : long from class org.neo4j.unsafe.impl.batchimport.staging.ProcessorStep


    @Test
    public void shouldParseHeaderFromFirstLineOfFirstInputFile() throws Exception
    {
        // GIVEN
        final Reader firstSource = new StringReader( "id:ID\tname:String\tbirth_date:long" );
        final Reader secondSource = new StringReader( "0\tThe node\t123456789" );
        DataFactory<InputNode> dataFactory = data( Functions.<InputNode>identity(), () -> {
            try
            {
                return sources( firstSource, secondSource );
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
        } );
        Header.Factory headerFactory = defaultFormatNodeFileHeader();
        Extractors extractors = new Extractors( ';' );

        // WHEN
        CharSeeker seeker = dataFactory.create( TABS ).stream();
        Header header = headerFactory.create( seeker, TABS, IdType.ACTUAL );

        // THEN
        assertArrayEquals( array(
                entry( "id", Type.ID, extractors.long_() ),
                entry( "name", Type.PROPERTY, extractors.string() ),
                entry( "birth_date", Type.PROPERTY, extractors.long_() ) ), header.entries() );
        seeker.close();
    }

    @Test
    public void shouldParseHeaderFromFirstLineOfFirstInputFile() throws Exception
    {
        // GIVEN
        final Reader firstSource = new StringReader( "id:ID\tname:String\tbirth_date:long" );
        final Reader secondSource = new StringReader( "0\tThe node\t123456789" );
        DataFactory<InputNode> dataFactory = data( Functions.<InputNode>identity(), new Supplier<CharReadable>()
        {
            @Override
            public CharReadable get()
            {
                try
                {
                    return sources( firstSource, secondSource );
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        } );
        Header.Factory headerFactory = defaultFormatNodeFileHeader();
        Extractors extractors = new Extractors( ';' );

        // WHEN
        CharSeeker seeker = dataFactory.create( TABS ).stream();
        Header header = headerFactory.create( seeker, TABS, IdType.ACTUAL );

        // THEN
        assertArrayEquals( array(
                entry( "id", Type.ID, extractors.long_() ),
                entry( "name", Type.PROPERTY, extractors.string() ),
                entry( "birth_date", Type.PROPERTY, extractors.long_() ) ), header.entries() );
        seeker.close();
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.input.csv.DataFactoriesTest.shouldParseHeaderFromFirstLineOfFirstInputFile.dataFactory.data.new Supplier<CharReadable> with () -> {tryreturn sources(firstSource,secondSource); in method public shouldParseHeaderFromFirstLineOfFirstInputFile() : void from class org.neo4j.unsafe.impl.batchimport.input.csv.DataFactoriesTest


    private void rotate()
    {
        if ( rotating.getAndSet( true ) )
        {
            // Already rotating
            return;
        }

        Runnable runnable = () -> {
            OutputStream newStream;
            try
            {
                if ( fileSystem.fileExists( outputFile ) )
                {
                    shiftArchivedOutputFiles();
                    fileSystem.renameFile( outputFile, archivedOutputFile( 1 ) );
                }
                newStream = openOutputFile();
            }
            catch ( Exception e )
            {
                rotationListener.rotationError( e, outRef.get() );
                rotating.set( false );
                return;
            }
            OutputStream oldStream = outRef.get();
            rotationListener.outputFileCreated( newStream, oldStream );
            synchronized ( outRef )
            {
                if ( !closed.get() )
                {
                    outRef.set( newStream );
                    removeCollectedReferences( archivedStreams );
                    archivedStreams.add( new WeakReference<>( oldStream ) );
                }
            }
            if ( rotationDelay > 0 )
            {
                earliestRotationTimeRef.set( currentTimeSupplier.getAsLong() + rotationDelay );
            }
            rotationListener.rotationCompleted( newStream, oldStream );
            rotating.set( false );
        };

        try
        {
            rotationExecutor.execute( runnable );
        }
        catch ( Exception e )
        {
            rotationListener.rotationError( e, outRef.get() );
            rotating.set( false );
        }
    }

    private void rotate()
    {
        if ( rotating.getAndSet( true ) )
        {
            // Already rotating
            return;
        }

        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                OutputStream newStream;
                try
                {
                    if ( fileSystem.fileExists( outputFile ) )
                    {
                        shiftArchivedOutputFiles();
                        fileSystem.renameFile( outputFile, archivedOutputFile( 1 ) );
                    }
                    newStream = openOutputFile();
                }
                catch ( Exception e )
                {
                    rotationListener.rotationError( e, outRef.get() );
                    rotating.set( false );
                    return;
                }
                OutputStream oldStream = outRef.get();
                rotationListener.outputFileCreated( newStream, oldStream );
                synchronized ( outRef )
                {
                    if ( !closed.get() )
                    {
                        outRef.set( newStream );
                        removeCollectedReferences( archivedStreams );
                        archivedStreams.add( new WeakReference<>( oldStream ) );
                    }
                }
                if ( rotationDelay > 0 )
                {
                    earliestRotationTimeRef.set( currentTimeSupplier.getAsLong() + rotationDelay );
                }
                rotationListener.rotationCompleted( newStream, oldStream );
                rotating.set( false );
            }
        };

        try
        {
            rotationExecutor.execute( runnable );
        }
        catch ( Exception e )
        {
            rotationListener.rotationError( e, outRef.get() );
            rotating.set( false );
        }
    }

Replace Anonymous With Lambda org.neo4j.logging.RotatingFileOutputStreamSupplier.rotate.runnable.new Runnable with () -> {OutputStream newStream; in method private rotate() : void from class org.neo4j.logging.RotatingFileOutputStreamSupplier


    private TransactionFacade createTransactionalActions()
    {
        final long timeoutMillis = getTransactionTimeoutMillis();
        final Clock clock = SYSTEM_CLOCK;

        transactionRegistry =
            new TransactionHandleRegistry( clock, timeoutMillis, logProvider );

        // ensure that this is > 0
        long runEvery = round( timeoutMillis / 2.0 );

        resolveDependency( JobScheduler.class ).scheduleRecurring( serverTransactionTimeout, () -> {
            long maxAge = clock.currentTimeMillis() - timeoutMillis;
            transactionRegistry.rollbackSuspendedTransactionsIdleSince( maxAge );
        }, runEvery, MILLISECONDS );

        return new TransactionFacade(
                new TransitionalPeriodTransactionMessContainer( database.getGraph() ),
                database.getGraph().getDependencyResolver().resolveDependency( QueryExecutionEngine.class ),
                transactionRegistry, logProvider
        );
    }

    private TransactionFacade createTransactionalActions()
    {
        final long timeoutMillis = getTransactionTimeoutMillis();
        final Clock clock = SYSTEM_CLOCK;

        transactionRegistry =
            new TransactionHandleRegistry( clock, timeoutMillis, logProvider );

        // ensure that this is > 0
        long runEvery = round( timeoutMillis / 2.0 );

        resolveDependency( JobScheduler.class ).scheduleRecurring( serverTransactionTimeout, new
                Runnable()
        {
            @Override
            public void run()
            {
                long maxAge = clock.currentTimeMillis() - timeoutMillis;
                transactionRegistry.rollbackSuspendedTransactionsIdleSince( maxAge );
            }
        }, runEvery, MILLISECONDS );

        return new TransactionFacade(
                new TransitionalPeriodTransactionMessContainer( database.getGraph() ),
                database.getGraph().getDependencyResolver().resolveDependency( QueryExecutionEngine.class ),
                transactionRegistry, logProvider
        );
    }

Replace Anonymous With Lambda org.neo4j.server.AbstractNeoServer.createTransactionalActions.scheduleRecurring.new Runnable with () -> {long maxAge=clock.currentTimeMillis() - timeoutMillis; in method private createTransactionalActions() : TransactionFacade from class org.neo4j.server.AbstractNeoServer


    public OnlineBackupKernelExtension( Config config, final GraphDatabaseAPI graphDatabaseAPI, final LogProvider logProvider,
                                        final Monitors monitors, final NeoStoreDataSource neoStoreDataSource,
                                        final Supplier<CheckPointer> checkPointerSupplier,
                                        final Supplier<TransactionIdStore> transactionIdStoreSupplier,
                                        final Supplier<LogicalTransactionStore> logicalTransactionStoreSupplier,
                                        final Supplier<LogFileInformation> logFileInformationSupplier,
                                        final FileSystemAbstraction fileSystemAbstraction)
    {
        this( config, graphDatabaseAPI, () -> {
            TransactionIdStore transactionIdStore = transactionIdStoreSupplier.get();
            StoreCopyServer copier = new StoreCopyServer( neoStoreDataSource, checkPointerSupplier.get(),
                    fileSystemAbstraction, new File( graphDatabaseAPI.getStoreDir() ),
                    monitors.newMonitor( StoreCopyServer.Monitor.class ) );
            LogicalTransactionStore logicalTransactionStore = logicalTransactionStoreSupplier.get();
            LogFileInformation logFileInformation = logFileInformationSupplier.get();
            return new BackupImpl( copier, monitors,
                    logicalTransactionStore, transactionIdStore, logFileInformation, new Supplier<StoreId>()
                    {
                        @Override
                        public StoreId get()
                        {
                            return graphDatabaseAPI.storeId();
                        }
                    } );
        }, monitors, logProvider );
    }

    public OnlineBackupKernelExtension( Config config, final GraphDatabaseAPI graphDatabaseAPI, final LogProvider logProvider,
                                        final Monitors monitors, final NeoStoreDataSource neoStoreDataSource,
                                        final Supplier<CheckPointer> checkPointerSupplier,
                                        final Supplier<TransactionIdStore> transactionIdStoreSupplier,
                                        final Supplier<LogicalTransactionStore> logicalTransactionStoreSupplier,
                                        final Supplier<LogFileInformation> logFileInformationSupplier,
                                        final FileSystemAbstraction fileSystemAbstraction)
    {
        this( config, graphDatabaseAPI, new BackupProvider()
        {
            @Override
            public TheBackupInterface newBackup()
            {
                TransactionIdStore transactionIdStore = transactionIdStoreSupplier.get();
                StoreCopyServer copier = new StoreCopyServer( neoStoreDataSource, checkPointerSupplier.get(),
                        fileSystemAbstraction, new File( graphDatabaseAPI.getStoreDir() ),
                        monitors.newMonitor( StoreCopyServer.Monitor.class ) );
                LogicalTransactionStore logicalTransactionStore = logicalTransactionStoreSupplier.get();
                LogFileInformation logFileInformation = logFileInformationSupplier.get();
                return new BackupImpl( copier, monitors,
                        logicalTransactionStore, transactionIdStore, logFileInformation, new Supplier<StoreId>()
                        {
                            @Override
                            public StoreId get()
                            {
                                return graphDatabaseAPI.storeId();
                            }
                        } );
            }
        }, monitors, logProvider );
    }

Replace Anonymous With Lambda org.neo4j.backup.OnlineBackupKernelExtension.OnlineBackupKernelExtension.new BackupProvider with () -> {TransactionIdStore transactionIdStore=transactionIdStoreSupplier.get(); in method public OnlineBackupKernelExtension(config Config, graphDatabaseAPI GraphDatabaseAPI, logProvider LogProvider, monitors Monitors, neoStoreDataSource NeoStoreDataSource, checkPointerSupplier Supplier<CheckPointer>, transactionIdStoreSupplier Supplier<TransactionIdStore>, logicalTransactionStoreSupplier Supplier<LogicalTransactionStore>, logFileInformationSupplier Supplier<LogFileInformation>, fileSystemAbstraction FileSystemAbstraction) from class org.neo4j.backup.OnlineBackupKernelExtension


    @Override
    public <T> Response<T> packTransactionStreamResponse( RequestContext context, T response )
    {
        final long toStartFrom = mandatoryStartTransactionId;
        final long toEndAt = transactionIdStore.getLastCommittedTransactionId();
        TransactionStream transactions = visitor -> {
            // Check so that it's even worth thinking about extracting any transactions at all
            if ( toStartFrom > BASE_TX_ID && toStartFrom <= toEndAt )
            {
                monitor.startStreamingTransactions( toStartFrom );
                extractTransactions( toStartFrom, filterVisitor( visitor, toEndAt ) );
                monitor.finishStreamingTransactions( toEndAt );
            }
        };
        return new TransactionStreamResponse<>( response, storeId.get(), transactions, ResourceReleaser.NO_OP );
    }

    @Override
    public <T> Response<T> packTransactionStreamResponse( RequestContext context, T response )
    {
        final long toStartFrom = mandatoryStartTransactionId;
        final long toEndAt = transactionIdStore.getLastCommittedTransactionId();
        TransactionStream transactions = new TransactionStream()
        {
            @Override
            public void accept( Visitor<CommittedTransactionRepresentation,Exception> visitor ) throws Exception
            {
                // Check so that it's even worth thinking about extracting any transactions at all
                if ( toStartFrom > BASE_TX_ID && toStartFrom <= toEndAt )
                {
                    monitor.startStreamingTransactions( toStartFrom );
                    extractTransactions( toStartFrom, filterVisitor( visitor, toEndAt ) );
                    monitor.finishStreamingTransactions( toEndAt );
                }
            }
        };
        return new TransactionStreamResponse<>( response, storeId.get(), transactions, ResourceReleaser.NO_OP );
    }

Replace Anonymous With Lambda org.neo4j.backup.StoreCopyResponsePacker.packTransactionStreamResponse.transactions.new TransactionStream with visitor -> {if(toStartFrom > BASE_TX_ID && toStartFrom <= toEndAt){monitor.startStreamingTransactions(toStartFrom); in method public packTransactionStreamResponse(context RequestContext, response T) : Response<T> from class org.neo4j.backup.StoreCopyResponsePacker


    public <T> Response<T> packTransactionStreamResponse( RequestContext context, T response )
    {
        final long toStartFrom = context.lastAppliedTransaction() + 1;
        final long toEndAt = transactionIdStore.getLastCommittedTransactionId();
        TransactionStream transactions = visitor -> {
            // Check so that it's even worth thinking about extracting any transactions at all
            if ( toStartFrom > BASE_TX_ID && toStartFrom <= toEndAt )
            {
                extractTransactions( toStartFrom, filterVisitor( visitor, toEndAt ) );
            }
        };
        return new TransactionStreamResponse<>( response, storeId.get(), transactions, ResourceReleaser.NO_OP );
    }

    public <T> Response<T> packTransactionStreamResponse( RequestContext context, T response )
    {
        final long toStartFrom = context.lastAppliedTransaction() + 1;
        final long toEndAt = transactionIdStore.getLastCommittedTransactionId();
        TransactionStream transactions = new TransactionStream()
        {
            @Override
            public void accept( Visitor<CommittedTransactionRepresentation,Exception> visitor ) throws Exception
            {
                // Check so that it's even worth thinking about extracting any transactions at all
                if ( toStartFrom > BASE_TX_ID && toStartFrom <= toEndAt )
                {
                    extractTransactions( toStartFrom, filterVisitor( visitor, toEndAt ) );
                }
            }
        };
        return new TransactionStreamResponse<>( response, storeId.get(), transactions, ResourceReleaser.NO_OP );
    }

Replace Anonymous With Lambda org.neo4j.com.storecopy.ResponsePacker.packTransactionStreamResponse.transactions.new TransactionStream with visitor -> {if(toStartFrom > BASE_TX_ID && toStartFrom <= toEndAt){extractTransactions(toStartFrom,filterVisitor(visitor,toEndAt)); in method public packTransactionStreamResponse(context RequestContext, response T) : Response<T> from class org.neo4j.com.storecopy.ResponsePacker


    protected Visitor<CommittedTransactionRepresentation,Exception> filterVisitor(
            final Visitor<CommittedTransactionRepresentation,Exception> delegate, final long txToEndAt )
    {
        return element -> {
            if ( element.getCommitEntry().getTxId() > txToEndAt )
            {
                return false;
            }
            return delegate.visit( element );
        };
    }

    protected Visitor<CommittedTransactionRepresentation,Exception> filterVisitor(
            final Visitor<CommittedTransactionRepresentation,Exception> delegate, final long txToEndAt )
    {
        return new Visitor<CommittedTransactionRepresentation,Exception>()
        {
            @Override
            public boolean visit( CommittedTransactionRepresentation element ) throws Exception
            {
                if ( element.getCommitEntry().getTxId() > txToEndAt )
                {
                    return false;
                }
                return delegate.visit( element );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.com.storecopy.ResponsePacker.filterVisitor.new Visitor<CommittedTransactionRepresentation,Exception> with element -> {if(element.getCommitEntry().getTxId() > txToEndAt){return false; in method protected filterVisitor(delegate Visitor<CommittedTransactionRepresentation,Exception>, txToEndAt long) : Visitor<CommittedTransactionRepresentation,Exception> from class org.neo4j.com.storecopy.ResponsePacker


    /**
     * Triggers pulling of updates up until at least {@code toTxId} if no pulling is currently happening
     * and returns immediately.
     */
    @Override
    public void fulfill( final long toTxId ) throws InterruptedException
    {
        updatePuller.pullUpdates( ( currentTicket, targetTicket ) -> {
            /*
             * We need to await last *closed* transaction id, not last *committed* transaction id since
             * right after leaving this method we might read records off of disk, and they had better
             * be up to date, otherwise we read stale data.
             */
            return transactionIdStore != null &&
                   transactionIdStore.getLastClosedTransactionId() >= toTxId;
        }, true /*We strictly need the update puller to be and remain active while we wait*/ );
    }

    /**
     * Triggers pulling of updates up until at least {@code toTxId} if no pulling is currently happening
     * and returns immediately.
     */
    @Override
    public void fulfill( final long toTxId ) throws InterruptedException
    {
        updatePuller.pullUpdates( new Condition()
        {
            @Override
            public boolean evaluate( int currentTicket, int targetTicket )
            {
                /*
                 * We need to await last *closed* transaction id, not last *committed* transaction id since
                 * right after leaving this method we might read records off of disk, and they had better
                 * be up to date, otherwise we read stale data.
                 */
                return transactionIdStore != null &&
                       transactionIdStore.getLastClosedTransactionId() >= toTxId;
            }
        }, true /*We strictly need the update puller to be and remain active while we wait*/ );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.UpdatePullingTransactionObligationFulfiller.fulfill.pullUpdates.new Condition with (currentTicket, targetTicket) -> {return transactionIdStore != null && transactionIdStore.getLastClosedTransactionId() >= toTxId; in method public fulfill(toTxId long) : void from class org.neo4j.kernel.ha.UpdatePullingTransactionObligationFulfiller