    private ClusterMemberListenerContainer mockAddClusterMemberListener( ClusterMemberEvents events )
    {
        final ClusterMemberListenerContainer listenerContainer = new ClusterMemberListenerContainer();
        doAnswer( invocation -> {
            listenerContainer.set( (ClusterMemberListener) invocation.getArguments()[0] );
            return null;
        } ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );
        return listenerContainer;
    }

    private ClusterMemberListenerContainer mockAddClusterMemberListener( ClusterMemberEvents events )
    {
        final ClusterMemberListenerContainer listenerContainer = new ClusterMemberListenerContainer();
        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                listenerContainer.set( (ClusterMemberListener) invocation.getArguments()[0] );
                return null;
            }

        } ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );
        return listenerContainer;
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.HighAvailabilityMemberStateMachineTest.mockAddClusterMemberListener.addClusterMemberListener.when.doAnswer.new Answer with invocation -> {listenerContainer.set((ClusterMemberListener)invocation.getArguments()[0]); in method private mockAddClusterMemberListener(events ClusterMemberEvents) : ClusterMemberListenerContainer from class org.neo4j.kernel.ha.cluster.HighAvailabilityMemberStateMachineTest


    @SuppressWarnings( "unchecked" )
    private SwitchToSlave newSwitchToSlaveSpy( PageCache pageCacheMock, StoreCopyClient storeCopyClient )
            throws IOException
    {
        ClusterMembers clusterMembers = mock( ClusterMembers.class );
        ClusterMember master = mock( ClusterMember.class );
        when( master.getStoreId() ).thenReturn( storeId );
        when( master.getHARole() ).thenReturn( HighAvailabilityModeSwitcher.MASTER );
        when( master.hasRole( eq( HighAvailabilityModeSwitcher.MASTER ) ) ).thenReturn( true );
        when( master.getInstanceId() ).thenReturn( new InstanceId( 1 ) );
        when( clusterMembers.getMembers() ).thenReturn( asList( master ) );

        Dependencies resolver = new Dependencies();
        resolver.satisfyDependencies( requestContextFactory, clusterMembers,
                mock( TransactionObligationFulfiller.class ),
                mock( OnlineBackupKernelExtension.class ),
                mock( IndexConfigStore.class ),
                mock( TransactionCommittingResponseUnpacker.class ),
                mock( DataSourceManager.class ),
                mock( StoreLockerLifecycleAdapter.class )
                );

        NeoStoreDataSource dataSource = mock( NeoStoreDataSource.class );
        when( dataSource.getStoreId() ).thenReturn( storeId );

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

        Response<HandshakeResult> response = mock( Response.class );
        when( response.response() ).thenReturn( new HandshakeResult( 42, 2 ) );
        when( masterClient.handshake( anyLong(), any( StoreId.class ) ) ).thenReturn( response );
        when( masterClient.getProtocolVersion() ).thenReturn( MasterClient214.PROTOCOL_VERSION );

        TransactionIdStore transactionIdStoreMock = mock( TransactionIdStore.class );
        // note that the checksum (the second member of the array) is the same as the one in the handshake mock above
        when( transactionIdStoreMock.getLastCommittedTransaction() ).thenReturn( new TransactionId( 42, 42 ) );

        MasterClientResolver masterClientResolver = mock( MasterClientResolver.class );
        when( masterClientResolver.instantiate( anyString(), anyInt(), any( Monitors.class ), any( StoreId.class ),
                any( LifeSupport.class ) ) ).thenReturn( masterClient );

        return spy( new SwitchToSlave( new File( "" ), NullLogService.getInstance(),
                configMock(), resolver,
                mock( HaIdGeneratorFactory.class ),
                mock( DelegateInvocationHandler.class ),
                mock( ClusterMemberAvailability.class ),
                requestContextFactory,
                pullerFactory, masterClientResolver,
                mock( SwitchToSlave.Monitor.class ),
                storeCopyClient,
                Suppliers.singleton( dataSource ),
                Suppliers.singleton( transactionIdStoreMock ),
                slave -> {
                    SlaveServer server = mock( SlaveServer.class );
                    InetSocketAddress inetSocketAddress = InetSocketAddress.createUnresolved( "localhost", 42 );

                    when( server.getSocketAddress() ).thenReturn( inetSocketAddress );
                    return server;
                }, updatePuller, pageCacheMock, mock( Monitors.class ), transactionCounters ) );
    }

    @SuppressWarnings( "unchecked" )
    private SwitchToSlave newSwitchToSlaveSpy( PageCache pageCacheMock, StoreCopyClient storeCopyClient )
            throws IOException
    {
        ClusterMembers clusterMembers = mock( ClusterMembers.class );
        ClusterMember master = mock( ClusterMember.class );
        when( master.getStoreId() ).thenReturn( storeId );
        when( master.getHARole() ).thenReturn( HighAvailabilityModeSwitcher.MASTER );
        when( master.hasRole( eq( HighAvailabilityModeSwitcher.MASTER ) ) ).thenReturn( true );
        when( master.getInstanceId() ).thenReturn( new InstanceId( 1 ) );
        when( clusterMembers.getMembers() ).thenReturn( asList( master ) );

        Dependencies resolver = new Dependencies();
        resolver.satisfyDependencies( requestContextFactory, clusterMembers,
                mock( TransactionObligationFulfiller.class ),
                mock( OnlineBackupKernelExtension.class ),
                mock( IndexConfigStore.class ),
                mock( TransactionCommittingResponseUnpacker.class ),
                mock( DataSourceManager.class ),
                mock( StoreLockerLifecycleAdapter.class )
                );

        NeoStoreDataSource dataSource = mock( NeoStoreDataSource.class );
        when( dataSource.getStoreId() ).thenReturn( storeId );

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

        Response<HandshakeResult> response = mock( Response.class );
        when( response.response() ).thenReturn( new HandshakeResult( 42, 2 ) );
        when( masterClient.handshake( anyLong(), any( StoreId.class ) ) ).thenReturn( response );
        when( masterClient.getProtocolVersion() ).thenReturn( MasterClient214.PROTOCOL_VERSION );

        TransactionIdStore transactionIdStoreMock = mock( TransactionIdStore.class );
        // note that the checksum (the second member of the array) is the same as the one in the handshake mock above
        when( transactionIdStoreMock.getLastCommittedTransaction() ).thenReturn( new TransactionId( 42, 42 ) );

        MasterClientResolver masterClientResolver = mock( MasterClientResolver.class );
        when( masterClientResolver.instantiate( anyString(), anyInt(), any( Monitors.class ), any( StoreId.class ),
                any( LifeSupport.class ) ) ).thenReturn( masterClient );

        return spy( new SwitchToSlave( new File( "" ), NullLogService.getInstance(),
                configMock(), resolver,
                mock( HaIdGeneratorFactory.class ),
                mock( DelegateInvocationHandler.class ),
                mock( ClusterMemberAvailability.class ),
                requestContextFactory,
                pullerFactory, masterClientResolver,
                mock( SwitchToSlave.Monitor.class ),
                storeCopyClient,
                Suppliers.singleton( dataSource ),
                Suppliers.singleton( transactionIdStoreMock ),
                new Function<Slave,SlaveServer>()
                {
                    @Override
                    public SlaveServer apply( Slave slave ) throws RuntimeException
                    {
                        SlaveServer server = mock( SlaveServer.class );
                        InetSocketAddress inetSocketAddress = InetSocketAddress.createUnresolved( "localhost", 42 );

                        when( server.getSocketAddress() ).thenReturn( inetSocketAddress );
                        return server;
                    }
                }, updatePuller, pageCacheMock, mock( Monitors.class ), transactionCounters ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.SwitchToSlaveTest.newSwitchToSlaveSpy.spy.new SwitchToSlave.new Function<Slave,SlaveServer> with slave -> {SlaveServer server=mock(SlaveServer.class); in method private newSwitchToSlaveSpy(pageCacheMock PageCache, storeCopyClient StoreCopyClient) : SwitchToSlave from class org.neo4j.kernel.ha.cluster.SwitchToSlaveTest


    public static void main( String... args ) throws Exception
    {
        if ( args == null || args.length == 0 )
        {
            System.err.println( "SYNTAX: [file[:id[,id]*]]+" );
            return;
        }
        final DefaultFileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        final DefaultIdGeneratorFactory idGeneratorFactory = new DefaultIdGeneratorFactory( fs );
        try ( PageCache pageCache = createPageCache( fs ) )
        {
            Function<File,StoreFactory> createStoreFactory =
                    file -> new StoreFactory( file.getParentFile(), new Config(), idGeneratorFactory, pageCache, fs,
                            logProvider() );

            for ( String arg : args )
            {
                dumpFile( createStoreFactory, arg );
            }
        }
    }

    public static void main( String... args ) throws Exception
    {
        if ( args == null || args.length == 0 )
        {
            System.err.println( "SYNTAX: [file[:id[,id]*]]+" );
            return;
        }
        final DefaultFileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        final DefaultIdGeneratorFactory idGeneratorFactory = new DefaultIdGeneratorFactory( fs );
        try ( PageCache pageCache = createPageCache( fs ) )
        {
            Function<File,StoreFactory> createStoreFactory = new Function<File,StoreFactory>()
            {
                @Override
                public StoreFactory apply( File file )
                {
                    return new StoreFactory( file.getParentFile(), new Config(), idGeneratorFactory, pageCache, fs,
                            logProvider() );
                }
            };

            for ( String arg : args )
            {
                dumpFile( createStoreFactory, arg );
            }
        }
    }

Replace Anonymous With Lambda org.neo4j.tools.dump.DumpStore.main.createStoreFactory.new Function<File,StoreFactory> with file -> new StoreFactory(file.getParentFile(),new Config(),idGeneratorFactory,pageCache,fs,logProvider()) in method public main(args String...) : void from class org.neo4j.tools.dump.DumpStore


    public static <From, From2, To> BiFunction<? super Function<From,From2>,? super Function<From2,To>,Function<From,To>> compose()
    {
        return ( f1, f2 ) -> new Function<From,To>()
        {
            @Override
            public To apply( From from )
            {
                return f2.apply( f1.apply( from ) );
            }
        };
    }

    public static <From, From2, To> Function2<? super Function<From,From2>,? super Function<From2,To>,Function<From,To>> compose()
    {
        return new Function2<Function<From,From2>,Function<From2,To>,Function<From,To>>()
        {
            @Override
            public Function<From,To> apply( final Function<From,From2> f1, final Function<From2,To> f2 )
            {
                return new Function<From,To>()
                {
                    @Override
                    public To apply( From from )
                    {
                        return f2.apply( f1.apply( from ) );
                    }
                };
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.function.Functions.compose.new Function2<Function<From,From2>,Function<From2,To>,Function<From,To>> with (f1, f2) -> new Function<From,To>(){ in method public compose() : BiFunction<? super Function<From,From2>,? super Function<From2,To>,Function<From,To>> from class org.neo4j.function.Functions


    @Override
    public ResourceIterable<Relationship> getRelationships( final Direction dir )
    {
        assertInUnterminatedTransaction();
        return () -> {
            Statement statement = actions.statement();
            try
            {
                RelationshipConversion result = new RelationshipConversion( actions );
                result.iterator = statement.readOperations().nodeGetRelationships( nodeId, dir );
                result.statement = statement;
                return result;
            }
            catch ( EntityNotFoundException e )
            {
                statement.close();
                throw new NotFoundException( format( "Node %d not found", nodeId ), e );
            }
            catch ( Throwable e )
            {
                statement.close();
                throw e;
            }
        };
    }

    @Override
    public ResourceIterable<Relationship> getRelationships( final Direction dir )
    {
        assertInUnterminatedTransaction();
        return new ResourceIterable<Relationship>()
        {
            @Override
            public ResourceIterator<Relationship> iterator()
            {
                Statement statement = actions.statement();
                try
                {
                    RelationshipConversion result = new RelationshipConversion( actions );
                    result.iterator = statement.readOperations().nodeGetRelationships( nodeId, dir );
                    result.statement = statement;
                    return result;
                }
                catch ( EntityNotFoundException e )
                {
                    statement.close();
                    throw new NotFoundException( format( "Node %d not found", nodeId ), e );
                }
                catch ( Throwable e )
                {
                    statement.close();
                    throw e;
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.core.NodeProxy.getRelationships.new ResourceIterable<Relationship> with () -> {Statement statement=actions.statement(); in method public getRelationships(dir Direction) : ResourceIterable<Relationship> from class org.neo4j.kernel.impl.core.NodeProxy


    private Iterable<RelationshipType> map2relTypes( final Statement statement, PrimitiveIntIterator input )
    {
        return asList( map( id -> {
            try
            {
                return RelationshipType.withName( statement.readOperations().relationshipTypeGetName( id ) );
            }
            catch ( RelationshipTypeIdNotFoundKernelException e )
            {
                throw new ThisShouldNotHappenError( "Jake",
                        "Kernel API returned non-existent relationship type: " + id );
            }
        }, input ) );
    }

    private Iterable<RelationshipType> map2relTypes( final Statement statement, PrimitiveIntIterator input )
    {
        return asList( map( new IntFunction<RelationshipType>()
        {
            @Override
            public RelationshipType apply( int id )
            {
                try
                {
                    return RelationshipType.withName( statement.readOperations().relationshipTypeGetName( id ) );
                }
                catch ( RelationshipTypeIdNotFoundKernelException e )
                {
                    throw new ThisShouldNotHappenError( "Jake",
                            "Kernel API returned non-existent relationship type: " + id );
                }
            }
        }, input ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.core.NodeProxy.map2relTypes.asList.map.new IntFunction<RelationshipType> with id -> {tryreturn RelationshipType.withName(statement.readOperations().relationshipTypeGetName(id)); in method private map2relTypes(statement Statement, input PrimitiveIntIterator) : Iterable<RelationshipType> from class org.neo4j.kernel.impl.core.NodeProxy


        /**
         * @return all started members in this cluster.
         */
        public Iterable<HighlyAvailableGraphDatabase> getAllMembers()
        {
            return Iterables.map( from -> {
                return from.get();
            }, members.values() );
        }

        /**
         * @return all started members in this cluster.
         */
        public Iterable<HighlyAvailableGraphDatabase> getAllMembers()
        {
            return Iterables.map( new Function<HighlyAvailableGraphDatabaseProxy,HighlyAvailableGraphDatabase>()
            {
                @Override
                public HighlyAvailableGraphDatabase apply( HighlyAvailableGraphDatabaseProxy from )
                {
                    return from.get();
                }
            }, members.values() );
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.ManagedCluster.getAllMembers.map.new Function<HighlyAvailableGraphDatabaseProxy,HighlyAvailableGraphDatabase> with from -> {return from.get(); in method public getAllMembers() : Iterable<HighlyAvailableGraphDatabase> from class org.neo4j.kernel.impl.ha.ClusterManager.ManagedCluster


    /**
     * Provider pointing out an XML file to read.
     *
     * @param clustersXml the XML file containing the cluster specifications.
     */
    public static Provider fromXml( final URI clustersXml )
    {
        return () -> {
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document clustersXmlDoc = documentBuilder.parse( clustersXml.toURL().openStream() );
            return new ClustersXMLSerializer( documentBuilder ).read( clustersXmlDoc );
        };
    }

    /**
     * Provider pointing out an XML file to read.
     *
     * @param clustersXml the XML file containing the cluster specifications.
     */
    public static Provider fromXml( final URI clustersXml )
    {
        return new Provider()
        {
            @Override
            public Clusters clusters() throws Exception
            {
                DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document clustersXmlDoc = documentBuilder.parse( clustersXml.toURL().openStream() );
                return new ClustersXMLSerializer( documentBuilder ).read( clustersXmlDoc );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.fromXml.new Provider with () -> {DocumentBuilder documentBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); in method public fromXml(clustersXml URI) : Provider from class org.neo4j.kernel.impl.ha.ClusterManager


            @Override
            public boolean test( ManagedCluster cluster )
            {
                Predicate<HighlyAvailableGraphDatabase> filterMasterPredicate =
                        node -> !excludedNodes.contains( node ) &&
                               node.isAvailable( 0 ) &&
                               node.isMaster();
                return Iterables.filter( filterMasterPredicate, cluster.getAllMembers() ).iterator().hasNext();
            }

            @Override
            public boolean test( ManagedCluster cluster )
            {
                Predicate<HighlyAvailableGraphDatabase> filterMasterPredicate =
                        new Predicate<HighlyAvailableGraphDatabase>()
                        {
                            @Override
                            public boolean test( HighlyAvailableGraphDatabase node )
                            {
                                return !excludedNodes.contains( node ) &&
                                       node.isAvailable( 0 ) &&
                                       node.isMaster();
                            }
                        };
                return Iterables.filter( filterMasterPredicate, cluster.getAllMembers() ).iterator().hasNext();
            }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.masterAvailable.new Predicate<ClusterManager.ManagedCluster>.test.filterMasterPredicate.new Predicate<HighlyAvailableGraphDatabase> with node -> !excludedNodes.contains(node) && node.isAvailable(0) && node.isMaster() in method public test(cluster ManagedCluster) : boolean from class org.neo4j.kernel.impl.ha.ClusterManager.masterAvailable.new Predicate<ClusterManager.ManagedCluster>


    @Override
    public ResourceIterable<Node> getAllNodes()
    {
        threadToTransactionBridge.assertInUnterminatedTransaction();
        return () -> {
            Statement statement = threadToTransactionBridge.get();
            return map2nodes( statement.readOperations().nodesGetAll(), statement );
        };
    }

    @Override
    public ResourceIterable<Node> getAllNodes()
    {
        threadToTransactionBridge.assertInUnterminatedTransaction();
        return new ResourceIterable<Node>()
        {
            @Override
            public ResourceIterator<Node> iterator()
            {
                Statement statement = threadToTransactionBridge.get();
                return map2nodes( statement.readOperations().nodesGetAll(), statement );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.factory.GraphDatabaseFacade.getAllNodes.new ResourceIterable<Node> with () -> {Statement statement=threadToTransactionBridge.get(); in method public getAllNodes() : ResourceIterable<Node> from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    @Override
    public ResourceIterable<Relationship> getAllRelationships()
    {
        threadToTransactionBridge.assertInUnterminatedTransaction();
        return () -> {
            final Statement statement = threadToTransactionBridge.get();
            final PrimitiveLongIterator ids = statement.readOperations().relationshipsGetAll();
            return new PrefetchingResourceIterator<Relationship>()
            {
                @Override
                public void close()
                {
                    statement.close();
                }

                @Override
                protected Relationship fetchNextOrNull()
                {
                    return ids.hasNext() ? nodeManager.newRelationshipProxy( ids.next() ) : null;
                }
            };
        };
    }

    @Override
    public ResourceIterable<Relationship> getAllRelationships()
    {
        threadToTransactionBridge.assertInUnterminatedTransaction();
        return new ResourceIterable<Relationship>()
        {
            @Override
            public ResourceIterator<Relationship> iterator()
            {
                final Statement statement = threadToTransactionBridge.get();
                final PrimitiveLongIterator ids = statement.readOperations().relationshipsGetAll();
                return new PrefetchingResourceIterator<Relationship>()
                {
                    @Override
                    public void close()
                    {
                        statement.close();
                    }

                    @Override
                    protected Relationship fetchNextOrNull()
                    {
                        return ids.hasNext() ? nodeManager.newRelationshipProxy( ids.next() ) : null;
                    }
                };
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.factory.GraphDatabaseFacade.getAllRelationships.new ResourceIterable<Relationship> with () -> {final Statement statement=threadToTransactionBridge.get(); in method public getAllRelationships() : ResourceIterable<Relationship> from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    private void repopulateAllIndexes() throws IOException, IndexCapacityExceededException, IndexEntryConflictException
    {
        if ( !labelsTouched )
        {
            return;
        }

        final IndexRule[] rules = getIndexesNeedingPopulation();
        final IndexPopulator[] populators = new IndexPopulator[rules.length];
        // the store is uncontended at this point, so creating a local LockService is safe.
        LockService locks = new ReentrantLockService();
        IndexStoreView storeView = new NeoStoreIndexStoreView( locks, neoStores );

        final int[] labelIds = new int[rules.length];
        final int[] propertyKeyIds = new int[rules.length];

        for ( int i = 0; i < labelIds.length; i++ )
        {
            IndexRule rule = rules[i];
            int labelId = rule.getLabel();
            int propertyKeyId = rule.getPropertyKey();
            labelIds[i] = labelId;
            propertyKeyIds[i] = propertyKeyId;

            IndexDescriptor descriptor = new IndexDescriptor( labelId, propertyKeyId );
            boolean isConstraint = rule.isConstraintIndex();
            populators[i] = schemaIndexProviders.apply( rule.getProviderDescriptor() )
                                                .getPopulator( rule.getId(),
                                                        descriptor,
                                                        new IndexConfiguration( isConstraint ),
                                                        new IndexSamplingConfig( config ) );
            populators[i].create();
        }

        Visitor<NodePropertyUpdate, IOException> propertyUpdateVisitor = update -> {
            // Do a lookup from which property has changed to a list of indexes worried about that property.
            int propertyKeyInQuestion = update.getPropertyKeyId();
            for ( int i = 0; i < propertyKeyIds.length; i++ )
            {
                if ( propertyKeyIds[i] == propertyKeyInQuestion )
                {
                    if ( update.forLabel( labelIds[i] ) )
                    {
                        try
                        {
                            populators[i].add( update.getNodeId(), update.getValueAfter() );
                        }
                        catch ( IndexEntryConflictException conflict )
                        {
                            throw conflict.notAllowed( rules[i].getLabel(), rules[i].getPropertyKey() );
                        }
                        catch ( IndexCapacityExceededException e )
                        {
                            throw new UnderlyingStorageException( e );
                        }
                    }
                }
            }
            return true;
        };

        InitialNodeLabelCreationVisitor labelUpdateVisitor = new InitialNodeLabelCreationVisitor();
        StoreScan<IOException> storeScan = storeView.visitNodes( labelIds, propertyKeyIds,
                propertyUpdateVisitor, labelUpdateVisitor );
        storeScan.run();

        for ( IndexPopulator populator : populators )
        {
            populator.verifyDeferredConstraints( storeView );
            populator.close( true );
        }
        labelUpdateVisitor.close();
    }

    private void repopulateAllIndexes() throws IOException, IndexCapacityExceededException, IndexEntryConflictException
    {
        if ( !labelsTouched )
        {
            return;
        }

        final IndexRule[] rules = getIndexesNeedingPopulation();
        final IndexPopulator[] populators = new IndexPopulator[rules.length];
        // the store is uncontended at this point, so creating a local LockService is safe.
        LockService locks = new ReentrantLockService();
        IndexStoreView storeView = new NeoStoreIndexStoreView( locks, neoStores );

        final int[] labelIds = new int[rules.length];
        final int[] propertyKeyIds = new int[rules.length];

        for ( int i = 0; i < labelIds.length; i++ )
        {
            IndexRule rule = rules[i];
            int labelId = rule.getLabel();
            int propertyKeyId = rule.getPropertyKey();
            labelIds[i] = labelId;
            propertyKeyIds[i] = propertyKeyId;

            IndexDescriptor descriptor = new IndexDescriptor( labelId, propertyKeyId );
            boolean isConstraint = rule.isConstraintIndex();
            populators[i] = schemaIndexProviders.apply( rule.getProviderDescriptor() )
                                                .getPopulator( rule.getId(),
                                                        descriptor,
                                                        new IndexConfiguration( isConstraint ),
                                                        new IndexSamplingConfig( config ) );
            populators[i].create();
        }

        Visitor<NodePropertyUpdate, IOException> propertyUpdateVisitor = new Visitor<NodePropertyUpdate, IOException>()
        {
            @Override
            public boolean visit( NodePropertyUpdate update ) throws IOException
            {
                // Do a lookup from which property has changed to a list of indexes worried about that property.
                int propertyKeyInQuestion = update.getPropertyKeyId();
                for ( int i = 0; i < propertyKeyIds.length; i++ )
                {
                    if ( propertyKeyIds[i] == propertyKeyInQuestion )
                    {
                        if ( update.forLabel( labelIds[i] ) )
                        {
                            try
                            {
                                populators[i].add( update.getNodeId(), update.getValueAfter() );
                            }
                            catch ( IndexEntryConflictException conflict )
                            {
                                throw conflict.notAllowed( rules[i].getLabel(), rules[i].getPropertyKey() );
                            }
                            catch ( IndexCapacityExceededException e )
                            {
                                throw new UnderlyingStorageException( e );
                            }
                        }
                    }
                }
                return true;
            }
        };

        InitialNodeLabelCreationVisitor labelUpdateVisitor = new InitialNodeLabelCreationVisitor();
        StoreScan<IOException> storeScan = storeView.visitNodes( labelIds, propertyKeyIds,
                propertyUpdateVisitor, labelUpdateVisitor );
        storeScan.run();

        for ( IndexPopulator populator : populators )
        {
            populator.verifyDeferredConstraints( storeView );
            populator.close( true );
        }
        labelUpdateVisitor.close();
    }

Replace Anonymous With Lambda org.neo4j.unsafe.batchinsert.BatchInserterImpl.repopulateAllIndexes.propertyUpdateVisitor.new Visitor<NodePropertyUpdate,IOException> with update -> {int propertyKeyInQuestion=update.getPropertyKeyId(); in method private repopulateAllIndexes() : void from class org.neo4j.unsafe.batchinsert.BatchInserterImpl


    @Override
    public void dumpLocksOnResource( final Object resource, Logger logger )
    {
        final RWLock lock;
        synchronized ( resourceLockMap )
        {
            if ( !resourceLockMap.containsKey( resource ) )
            {
                logger.log( "No locks on " + resource );
                return;
            }
            lock = resourceLockMap.get( resource );
        }
        logger.bulk( bulkLogger -> {
            bulkLogger.log( "Dump locks on resource %s", resource );
            lock.logTo( bulkLogger );
        } );
    }

    @Override
    public void dumpLocksOnResource( final Object resource, Logger logger )
    {
        final RWLock lock;
        synchronized ( resourceLockMap )
        {
            if ( !resourceLockMap.containsKey( resource ) )
            {
                logger.log( "No locks on " + resource );
                return;
            }
            lock = resourceLockMap.get( resource );
        }
        logger.bulk( new Consumer<Logger>()
        {
            @Override
            public void accept( Logger bulkLogger )
            {
                bulkLogger.log( "Dump locks on resource %s", resource );
                lock.logTo( bulkLogger );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.LockManagerImpl.dumpLocksOnResource.bulk.new Consumer<Logger> with bulkLogger -> {bulkLogger.log("Dump locks on resource %s",resource); in method public dumpLocksOnResource(resource Object, logger Logger) : void from class org.neo4j.kernel.impl.locking.community.LockManagerImpl


    public void dumpAll( Log log )
    {
        log.bulk( bulkLog -> {
            for ( DiagnosticsProvider provider : providers )
            {
                dump( provider, DiagnosticsPhase.EXPLICIT, bulkLog );
            }
        } );
    }

    public void dumpAll( Log log )
    {
        log.bulk( new Consumer<Log>()
        {
            @Override
            public void accept( Log bulkLog )
            {
                for ( DiagnosticsProvider provider : providers )
                {
                    dump( provider, DiagnosticsPhase.EXPLICIT, bulkLog );
                }
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.info.DiagnosticsManager.dumpAll.bulk.new Consumer<Log> with bulkLog -> {for(DiagnosticsProvider provider: providers){dump(provider,DiagnosticsPhase.EXPLICIT,bulkLog); in method public dumpAll(log Log) : void from class org.neo4j.kernel.info.DiagnosticsManager


    public void extract( final String identifier, Log log )
    {
        log.bulk( bulkLog -> {
            for ( DiagnosticsProvider provider : providers )
            {
                if ( identifier.equals( provider.getDiagnosticsIdentifier() ) )
                {
                    dump( provider, DiagnosticsPhase.EXPLICIT, bulkLog );
                    return;
                }
            }
        } );
    }

    public void extract( final String identifier, Log log )
    {
        log.bulk( new Consumer<Log>()
        {
            @Override
            public void accept( Log bulkLog )
            {
                for ( DiagnosticsProvider provider : providers )
                {
                    if ( identifier.equals( provider.getDiagnosticsIdentifier() ) )
                    {
                        dump( provider, DiagnosticsPhase.EXPLICIT, bulkLog );
                        return;
                    }
                }
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.info.DiagnosticsManager.extract.bulk.new Consumer<Log> with bulkLog -> {for(DiagnosticsProvider provider: providers){if(identifier.equals(provider.getDiagnosticsIdentifier())){dump(provider,DiagnosticsPhase.EXPLICIT,bulkLog); in method public extract(identifier String, log Log) : void from class org.neo4j.kernel.info.DiagnosticsManager


    private void dumpAll( final DiagnosticsPhase phase, Log log )
    {
        log.bulk( bulkLog -> {
            phase.emitStart( bulkLog );
            for ( DiagnosticsProvider provider : providers )
            {
                dump( provider, phase, bulkLog );
            }
            phase.emitDone( bulkLog );
        } );
    }

    private void dumpAll( final DiagnosticsPhase phase, Log log )
    {
        log.bulk( new Consumer<Log>()
        {
            @Override
            public void accept( Log bulkLog )
            {
                phase.emitStart( bulkLog );
                for ( DiagnosticsProvider provider : providers )
                {
                    dump( provider, phase, bulkLog );
                }
                phase.emitDone( bulkLog );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.info.DiagnosticsManager.dumpAll.bulk.new Consumer<Log> with bulkLog -> {phase.emitStart(bulkLog); in method private dumpAll(phase DiagnosticsPhase, log Log) : void from class org.neo4j.kernel.info.DiagnosticsManager


    public synchronized void dump( Logger logger )
    {
        logger.bulk( bulkLogger -> {
            bulkLogger.log("Lifecycle status: %s", status.name());
            for ( LifecycleInstance instance : instances )
            {
                bulkLogger.log(instance.toString());
            }
        } );
    }

    public synchronized void dump( Logger logger )
    {
        logger.bulk( new Consumer<Logger>()
        {
            @Override
            public void accept( Logger bulkLogger )
            {
                bulkLogger.log("Lifecycle status: %s", status.name());
                for ( LifecycleInstance instance : instances )
                {
                    bulkLogger.log(instance.toString());
                }
            }
        });
    }

Replace Anonymous With Lambda org.neo4j.kernel.lifecycle.LifeSupport.dump.bulk.new Consumer<Logger> with bulkLogger -> {bulkLogger.log("Lifecycle status: %s",status.name()); in method public dump(logger Logger) : void from class org.neo4j.kernel.lifecycle.LifeSupport


    public void assertFacadeMethodsThrowAfterTerminate( Iterable<FacadeMethod<T>> methods )
    {
        for ( final FacadeMethod<T> method : methods )
        {
            obtainEntityInTerminatedTransaction( entity -> {
                try
                {
                    method.call( entity );

                    fail( "Transaction was terminated, yet not exception thrown in: " + method );
                }
                catch ( TransactionTerminatedException e )
                {
                    // awesome
                }
            } );
        }
    }

    public void assertFacadeMethodsThrowAfterTerminate( Iterable<FacadeMethod<T>> methods )
    {
        for ( final FacadeMethod<T> method : methods )
        {
            obtainEntityInTerminatedTransaction(  new Consumer<T>()
            {
                @Override
                public void accept( T entity )
                {
                    try
                    {
                        method.call( entity );

                        fail( "Transaction was terminated, yet not exception thrown in: " + method );
                    }
                    catch ( TransactionTerminatedException e )
                    {
                        // awesome
                    }
                }
            });
        }
    }

Replace Anonymous With Lambda org.neo4j.graphdb.AbstractMandatoryTransactionsTest.assertFacadeMethodsThrowAfterTerminate.obtainEntityInTerminatedTransaction.new Consumer<T> with entity -> {trymethod.call(entity); in method public assertFacadeMethodsThrowAfterTerminate(methods Iterable<FacadeMethod<T>>) : void from class org.neo4j.graphdb.AbstractMandatoryTransactionsTest


    private void writeSomeData( File file, Visitor<Pair<LogEntryWriter,Consumer<LogPositionMarker>>,IOException> visitor ) throws IOException
    {

        try (  LogVersionedStoreChannel versionedStoreChannel =
                       new PhysicalLogVersionedStoreChannel( fs.open( file, "rw" ), logVersion, CURRENT_LOG_VERSION );
              final PhysicalWritableLogChannel writableLogChannel = new PhysicalWritableLogChannel( versionedStoreChannel ) )
        {
            writeLogHeader( writableLogChannel, logVersion, 2l );

            Consumer<LogPositionMarker> consumer = marker -> {
                try
                {
                    writableLogChannel.getCurrentPosition( marker );
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            };
            LogEntryWriter first = new LogEntryWriter( writableLogChannel, CommandHandler.EMPTY );
            visitor.visit( Pair.of( first, consumer ) );
        }
    }

    private void writeSomeData( File file, Visitor<Pair<LogEntryWriter,Consumer<LogPositionMarker>>,IOException> visitor ) throws IOException
    {

        try (  LogVersionedStoreChannel versionedStoreChannel =
                       new PhysicalLogVersionedStoreChannel( fs.open( file, "rw" ), logVersion, CURRENT_LOG_VERSION );
              final PhysicalWritableLogChannel writableLogChannel = new PhysicalWritableLogChannel( versionedStoreChannel ) )
        {
            writeLogHeader( writableLogChannel, logVersion, 2l );

            Consumer<LogPositionMarker> consumer = new Consumer<LogPositionMarker>()
            {
                @Override
                public void accept( LogPositionMarker marker )
                {
                    try
                    {
                        writableLogChannel.getCurrentPosition( marker );
                    }
                    catch ( IOException e )
                    {
                        throw new RuntimeException( e );
                    }
                }
            };
            LogEntryWriter first = new LogEntryWriter( writableLogChannel, CommandHandler.EMPTY );
            visitor.visit( Pair.of( first, consumer ) );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.RecoveryTest.writeSomeData.consumer.new Consumer<LogPositionMarker> with marker -> {trywritableLogChannel.getCurrentPosition(marker); in method private writeSomeData(file File, visitor Visitor<Pair<LogEntryWriter,Consumer<LogPositionMarker>>,IOException>) : void from class org.neo4j.kernel.RecoveryTest


    @Parameterized.Parameters( name = "{2}" )
    public static Collection<Object[]> parameters()
    {
        return Arrays.asList(
                new Object[]{(ThrowingConsumer<KernelTransaction,Exception>) (tx) -> {}, false, "read"},
                new Object[]{(ThrowingConsumer<KernelTransaction,Exception>) kernelTransaction -> {
                    KernelStatement statement = (KernelStatement) kernelTransaction.acquireStatement();
                    statement.txState().nodeDoCreate( 42 );
                }, true, "write"}
        );
    }

    @Parameterized.Parameters( name = "{2}" )
    public static Collection<Object[]> parameters()
    {
        return Arrays.asList(
                new Object[]{Consumers.<KernelTransaction,Exception>throwingNoop(), false, "read"},
                new Object[]{new ThrowingConsumer<KernelTransaction,Exception>()
                {
                    @Override
                    public void accept( KernelTransaction kernelTransaction ) throws Exception
                    {
                        KernelStatement statement = (KernelStatement) kernelTransaction.acquireStatement();
                        statement.txState().nodeDoCreate( 42 );
                    }
                }, true, "write"}
        );
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.KernelTransactionImplementationTest.parameters.asList.new ThrowingConsumer<KernelTransaction,Exception> with kernelTransaction -> {KernelStatement statement=(KernelStatement)kernelTransaction.acquireStatement(); in method public parameters() : Collection<Object[]> from class org.neo4j.kernel.api.KernelTransactionImplementationTest


    @Test
    public void shouldNotCallConsumerProvidingTheDescriptionWhenThresholdIsFalse() throws Throwable
    {
        // Given
        AbstractCheckPointThreshold threshold = new TheAbstractCheckPointThreshold( false, null );

        // When
        threshold.isCheckPointingNeeded( 42, s -> {
            throw new IllegalStateException( "nooooooooo!" );
        } );

        // Then
        // should not throw
    }

    @Test
    public void shouldNotCallConsumerProvidingTheDescriptionWhenThresholdIsFalse() throws Throwable
    {
        // Given
        AbstractCheckPointThreshold threshold = new TheAbstractCheckPointThreshold( false, null );

        // When
        threshold.isCheckPointingNeeded( 42, new Consumer<String>()
        {
            @Override
            public void accept( String s )
            {
                throw new IllegalStateException( "nooooooooo!" );
            }
        } );

        // Then
        // should not throw
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.checkpoint.AbstractCheckPointThresholdTest.shouldNotCallConsumerProvidingTheDescriptionWhenThresholdIsFalse.isCheckPointingNeeded.new Consumer<String> with s -> {throw new IllegalStateException("nooooooooo!"); in method public shouldNotCallConsumerProvidingTheDescriptionWhenThresholdIsFalse() : void from class org.neo4j.kernel.impl.transaction.log.checkpoint.AbstractCheckPointThresholdTest


        @Override
        public void bulk( Consumer<Logger> consumer )
        {
            bulk( new LinkedList<>( loggers ), new ArrayList<>( loggers.size() ), consumer );
        }

        @Override
        public void bulk( Consumer<Logger> consumer )
        {
            bulk( new LinkedList<>( loggers ), new ArrayList<Logger>( loggers.size() ), consumer );
        }

Replace Generic With Diamond ArrayList<Logger> with ArrayList<> in method public bulk(consumer Consumer<Logger>) : void from class org.neo4j.logging.DuplicatingLog.DuplicatingLogger


        private static void bulk( final LinkedList<Logger> remaining, final ArrayList<Logger> bulkLoggers, final Consumer<Logger> finalConsumer )
        {
            if ( !remaining.isEmpty() )
            {
                Logger logger = remaining.pop();
                logger.bulk( bulkLogger -> {
                    bulkLoggers.add( bulkLogger );
                    bulk( remaining, bulkLoggers, finalConsumer );
                } );
            } else
            {
                Logger logger = new DuplicatingLogger( bulkLoggers );
                finalConsumer.accept( logger );
            }
        }

        private static void bulk( final LinkedList<Logger> remaining, final ArrayList<Logger> bulkLoggers, final Consumer<Logger> finalConsumer )
        {
            if ( !remaining.isEmpty() )
            {
                Logger logger = remaining.pop();
                logger.bulk( new Consumer<Logger>()
                {
                    @Override
                    public void accept( Logger bulkLogger )
                    {
                        bulkLoggers.add( bulkLogger );
                        bulk( remaining, bulkLoggers, finalConsumer );
                    }
                } );
            } else
            {
                Logger logger = new DuplicatingLogger( bulkLoggers );
                finalConsumer.accept( logger );
            }
        }

Replace Anonymous With Lambda org.neo4j.logging.DuplicatingLog.DuplicatingLogger.bulk.bulk.new Consumer<Logger> with bulkLogger -> {bulkLoggers.add(bulkLogger); in method private bulk(remaining LinkedList<Logger>, bulkLoggers ArrayList<Logger>, finalConsumer Consumer<Logger>) : void from class org.neo4j.logging.DuplicatingLog.DuplicatingLogger


    @Override
    public void bulk( Consumer<Log> consumer )
    {
        bulk( new LinkedList<>( logs ), new ArrayList<>( logs.size() ), consumer );
    }

    @Override
    public void bulk( Consumer<Log> consumer )
    {
        bulk( new LinkedList<>( logs ), new ArrayList<Log>( logs.size() ), consumer );
    }

Replace Generic With Diamond ArrayList<Log> with ArrayList<> in method public bulk(consumer Consumer<Log>) : void from class org.neo4j.logging.DuplicatingLog


    private static void bulk( final LinkedList<Log> remaining, final ArrayList<Log> bulkLogs, final Consumer<Log> finalConsumer )
    {
        if ( !remaining.isEmpty() )
        {
            Log log = remaining.pop();
            log.bulk( bulkLog -> {
                bulkLogs.add( bulkLog );
                bulk( remaining, bulkLogs, finalConsumer );
            } );
        } else
        {
            Log log = new DuplicatingLog( bulkLogs );
            finalConsumer.accept( log );
        }
    }

    private static void bulk( final LinkedList<Log> remaining, final ArrayList<Log> bulkLogs, final Consumer<Log> finalConsumer )
    {
        if ( !remaining.isEmpty() )
        {
            Log log = remaining.pop();
            log.bulk( new Consumer<Log>()
            {
                @Override
                public void accept( Log bulkLog )
                {
                    bulkLogs.add( bulkLog );
                    bulk( remaining, bulkLogs, finalConsumer );
                }
            } );
        } else
        {
            Log log = new DuplicatingLog( bulkLogs );
            finalConsumer.accept( log );
        }
    }

Replace Anonymous With Lambda org.neo4j.logging.DuplicatingLog.bulk.bulk.new Consumer<Log> with bulkLog -> {bulkLogs.add(bulkLog); in method private bulk(remaining LinkedList<Log>, bulkLogs ArrayList<Log>, finalConsumer Consumer<Log>) : void from class org.neo4j.logging.DuplicatingLog


    @Test( timeout = 10000 )
    public void concurrentlyPublishedEventsMustAllBeProcessed() throws Exception
    {
        EventConsumer consumer = new EventConsumer();
        final CountDownLatch startLatch = new CountDownLatch( 1 );
        final int threads = 10;
        final int iterations = 10_000;
        final AsyncEvents<Event> asyncEvents = new AsyncEvents<>( consumer, AsyncEvents.Monitor.NONE );
        executor.submit( asyncEvents );

        ExecutorService threadPool = Executors.newFixedThreadPool( threads );
        Runnable runner = () -> {
            try
            {
                startLatch.await();
            }
            catch ( InterruptedException e )
            {
                throw new RuntimeException( e );
            }

            for ( int i = 0; i < iterations; i++ )
            {
                asyncEvents.send( new Event() );
            }
        };
        for ( int i = 0; i < threads; i++ )
        {
            threadPool.submit( runner );
        }
        startLatch.countDown();

        Thread thisThread = Thread.currentThread();
        int eventCount = threads * iterations;
        try
        {
            for ( int i = 0; i < eventCount; i++ )
            {
                Event event = consumer.poll( 1, TimeUnit.SECONDS );
                assertThat( event.processedBy, is( not( thisThread ) ) );
            }
        }
        finally
        {
            asyncEvents.shutdown();
        }
    }

    @Test( timeout = 10000 )
    public void concurrentlyPublishedEventsMustAllBeProcessed() throws Exception
    {
        EventConsumer consumer = new EventConsumer();
        final CountDownLatch startLatch = new CountDownLatch( 1 );
        final int threads = 10;
        final int iterations = 10_000;
        final AsyncEvents<Event> asyncEvents = new AsyncEvents<>( consumer, AsyncEvents.Monitor.NONE );
        executor.submit( asyncEvents );

        ExecutorService threadPool = Executors.newFixedThreadPool( threads );
        Runnable runner = new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    startLatch.await();
                }
                catch ( InterruptedException e )
                {
                    throw new RuntimeException( e );
                }

                for ( int i = 0; i < iterations; i++ )
                {
                    asyncEvents.send( new Event() );
                }
            }
        };
        for ( int i = 0; i < threads; i++ )
        {
            threadPool.submit( runner );
        }
        startLatch.countDown();

        Thread thisThread = Thread.currentThread();
        int eventCount = threads * iterations;
        try
        {
            for ( int i = 0; i < eventCount; i++ )
            {
                Event event = consumer.poll( 1, TimeUnit.SECONDS );
                assertThat( event.processedBy, is( not( thisThread ) ) );
            }
        }
        finally
        {
            asyncEvents.shutdown();
        }
    }

Replace Anonymous With Lambda org.neo4j.concurrent.AsyncEventsTest.concurrentlyPublishedEventsMustAllBeProcessed.runner.new Runnable with () -> {trystartLatch.await(); in method public concurrentlyPublishedEventsMustAllBeProcessed() : void from class org.neo4j.concurrent.AsyncEventsTest


    @Test
    public void awaitingShutdownMustBlockUntilAllMessagesHaveBeenProcessed() throws Exception
    {
        final Event specialShutdownObservedEvent = new Event();
        final CountDownLatch awaitStartLatch = new CountDownLatch( 1 );
        final EventConsumer consumer = new EventConsumer();
        final AsyncEvents<Event> asyncEvents = new AsyncEvents<>( consumer, AsyncEvents.Monitor.NONE );
        executor.submit( asyncEvents );

        // Wait for the background thread to start processing events
        do
        {
            asyncEvents.send( new Event() );
        }
        while ( consumer.eventsProcessed.take().processedBy == Thread.currentThread() );

        // Start a thread that awaits the termination
        Future<?> awaitShutdownFuture = executor.submit( (Runnable) () -> {
            awaitStartLatch.countDown();
            try
            {
                asyncEvents.awaitTermination();
            }
            catch ( InterruptedException e )
            {
                throw new RuntimeException( e );
            }
            consumer.eventsProcessed.offer( specialShutdownObservedEvent );
        } );

        awaitStartLatch.await();

        // Send 5 events
        asyncEvents.send( new Event() );
        asyncEvents.send( new Event() );
        asyncEvents.send( new Event() );
        asyncEvents.send( new Event() );
        asyncEvents.send( new Event() );

        // Observe 5 events processed
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );

        // Observe no events left
        assertThat( consumer.eventsProcessed.poll( 20, TimeUnit.MILLISECONDS ), is( nullValue() ) );

        // Shutdown and await termination
        asyncEvents.shutdown();
        awaitShutdownFuture.get();

        // Observe termination
        assertThat( consumer.eventsProcessed.take(), sameInstance( specialShutdownObservedEvent ) );
    }

    @Test
    public void awaitingShutdownMustBlockUntilAllMessagesHaveBeenProcessed() throws Exception
    {
        final Event specialShutdownObservedEvent = new Event();
        final CountDownLatch awaitStartLatch = new CountDownLatch( 1 );
        final EventConsumer consumer = new EventConsumer();
        final AsyncEvents<Event> asyncEvents = new AsyncEvents<>( consumer, AsyncEvents.Monitor.NONE );
        executor.submit( asyncEvents );

        // Wait for the background thread to start processing events
        do
        {
            asyncEvents.send( new Event() );
        }
        while ( consumer.eventsProcessed.take().processedBy == Thread.currentThread() );

        // Start a thread that awaits the termination
        Future<?> awaitShutdownFuture = executor.submit( new Runnable()
        {
            @Override
            public void run()
            {
                awaitStartLatch.countDown();
                try
                {
                    asyncEvents.awaitTermination();
                }
                catch ( InterruptedException e )
                {
                    throw new RuntimeException( e );
                }
                consumer.eventsProcessed.offer( specialShutdownObservedEvent );
            }
        } );

        awaitStartLatch.await();

        // Send 5 events
        asyncEvents.send( new Event() );
        asyncEvents.send( new Event() );
        asyncEvents.send( new Event() );
        asyncEvents.send( new Event() );
        asyncEvents.send( new Event() );

        // Observe 5 events processed
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );
        assertThat( consumer.eventsProcessed.take(), is( notNullValue() ) );

        // Observe no events left
        assertThat( consumer.eventsProcessed.poll( 20, TimeUnit.MILLISECONDS ), is( nullValue() ) );

        // Shutdown and await termination
        asyncEvents.shutdown();
        awaitShutdownFuture.get();

        // Observe termination
        assertThat( consumer.eventsProcessed.take(), sameInstance( specialShutdownObservedEvent ) );
    }

Replace Anonymous With Lambda org.neo4j.concurrent.AsyncEventsTest.awaitingShutdownMustBlockUntilAllMessagesHaveBeenProcessed.awaitShutdownFuture.submit.new Runnable with () -> {awaitStartLatch.countDown(); in method public awaitingShutdownMustBlockUntilAllMessagesHaveBeenProcessed() : void from class org.neo4j.concurrent.AsyncEventsTest


    private void createTransaction( final ManagedCluster cluster, final GraphDatabaseAPI db )
    {
        TransactionTemplate template = new TransactionTemplate()
                .with( db )
                .retries( 10 )
                .backoff( 1, TimeUnit.SECONDS )
                .monitor( new TransactionTemplate.Monitor.Adapter()
                {
                    @Override
                    public void retrying()
                    {
                        System.err.println( "Retrying..." );
                    }

                    @Override
                    public void failure( Throwable ex )
                    {
                        System.err.println( "Attempt failed with " + ex  );

                        // Assume this is because of master switch
                        // Redo the machine id mapping
                        cluster.await( allSeesAllAsAvailable() );
                        mapMachineIds( cluster );
                    }
                } );

        template.execute( transaction -> {
            db.createNode();
        } );
    }

    private void createTransaction( final ManagedCluster cluster, final GraphDatabaseAPI db )
    {
        TransactionTemplate template = new TransactionTemplate()
                .with( db )
                .retries( 10 )
                .backoff( 1, TimeUnit.SECONDS )
                .monitor( new TransactionTemplate.Monitor.Adapter()
                {
                    @Override
                    public void retrying()
                    {
                        System.err.println( "Retrying..." );
                    }

                    @Override
                    public void failure( Throwable ex )
                    {
                        System.err.println( "Attempt failed with " + ex  );

                        // Assume this is because of master switch
                        // Redo the machine id mapping
                        cluster.await( allSeesAllAsAvailable() );
                        mapMachineIds( cluster );
                    }
                } );

        template.execute( new Consumer<Transaction>()
        {
            @Override
            public void accept( Transaction transaction )
            {
                db.createNode();
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.TxPushStrategyConfigIT.createTransaction.execute.new Consumer<Transaction> with transaction -> {db.createNode(); in method private createTransaction(cluster ManagedCluster, db GraphDatabaseAPI) : void from class org.neo4j.kernel.ha.TxPushStrategyConfigIT


    @Override
    public void start() throws Exception
    {
        state = State.STARTING;

        applyRecoveredUpdates();
        IndexMap indexMap = indexMapRef.indexMapSnapshot();

        final Map<Long,RebuildingIndexDescriptor> rebuildingDescriptors = new HashMap<>();

        // Find all indexes that are not already online, do not require rebuilding, and create them
        indexMap.foreachIndexProxy( ( indexId, proxy ) -> {
            InternalIndexState state1 = proxy.getState();
            IndexDescriptor descriptor = proxy.getDescriptor();
            log.info( proxySetup.indexStateInfo( "start", indexId, state1, descriptor ) );
            switch ( state1 )
            {
                case ONLINE:
                    // Don't do anything, index is ok.
                    break;
                case POPULATING:
                    // Remember for rebuilding
                    rebuildingDescriptors.put( indexId, new RebuildingIndexDescriptor(
                            descriptor, proxy.getProviderDescriptor(), proxy.config() ) );
                    break;
                case FAILED:
                    // Don't do anything, the user needs to drop the index and re-create
                    break;
            }
        } );

        // Drop placeholder proxies for indexes that need to be rebuilt
        dropRecoveringIndexes( indexMap, rebuildingDescriptors.keySet() );

        // Rebuild indexes by recreating and repopulating them
        for ( Map.Entry<Long,RebuildingIndexDescriptor> entry : rebuildingDescriptors.entrySet() )
        {
            long indexId = entry.getKey();
            RebuildingIndexDescriptor descriptors = entry.getValue();

            /*
             * Passing in "false" for unique here may seem surprising, and.. well, yes, it is, I was surprised too.
             * However, it is actually perfectly safe, because whenever we have constraint indexes here, they will
             * be in a state where they didn't finish populating, and despite the fact that we re-create them here,
             * they will get dropped as soon as recovery is completed by the constraint system.
             */
            IndexProxy proxy = proxySetup.createPopulatingIndexProxy(
                    indexId, descriptors.getIndexDescriptor(), descriptors.getProviderDescriptor(), false, monitor );
            proxy.start();
            indexMap.putIndexProxy( indexId, proxy );
        }

        indexMapRef.setIndexMap( indexMap );

        samplingController.recoverIndexSamples();
        samplingController.start();

        // So at this point we've started population of indexes that needs to be rebuilt in the background.
        // Indexes backing uniqueness constraints are normally built within the transaction creating the constraint
        // and so we shouldn't leave such indexes in a populating state after recovery.
        // This is why we now go and wait for those indexes to be fully populated.
        for ( Map.Entry<Long,RebuildingIndexDescriptor> entry : rebuildingDescriptors.entrySet() )
        {
            if ( !entry.getValue().getConfiguration().isUnique() )
            {
                // It's not a uniqueness constraint, so don't wait for it to be rebuilt
                continue;
            }

            IndexProxy proxy;
            try
            {
                proxy = getIndexProxy( entry.getKey().longValue() );
            }
            catch ( IndexNotFoundKernelException e )
            {
                throw new ThisShouldNotHappenError( "Mattias",
                        "What? This index was seen during recovery just now, why isn't it available now?" );
            }

            monitor.awaitingPopulationOfRecoveredIndex( entry.getKey(), entry.getValue().getIndexDescriptor() );
            awaitOnline( proxy );
        }

        state = State.RUNNING;
    }

    @Override
    public void start() throws Exception
    {
        state = State.STARTING;

        applyRecoveredUpdates();
        IndexMap indexMap = indexMapRef.indexMapSnapshot();

        final Map<Long,RebuildingIndexDescriptor> rebuildingDescriptors = new HashMap<>();

        // Find all indexes that are not already online, do not require rebuilding, and create them
        indexMap.foreachIndexProxy( new BiConsumer<Long, IndexProxy>()
        {
            @Override
            public void accept( Long indexId, IndexProxy proxy )
            {
                InternalIndexState state = proxy.getState();
                IndexDescriptor descriptor = proxy.getDescriptor();
                log.info( proxySetup.indexStateInfo( "start", indexId, state, descriptor ) );
                switch ( state )
                {
                    case ONLINE:
                        // Don't do anything, index is ok.
                        break;
                    case POPULATING:
                        // Remember for rebuilding
                        rebuildingDescriptors.put( indexId, new RebuildingIndexDescriptor(
                                descriptor, proxy.getProviderDescriptor(), proxy.config() ) );
                        break;
                    case FAILED:
                        // Don't do anything, the user needs to drop the index and re-create
                        break;
                }
            }
        } );

        // Drop placeholder proxies for indexes that need to be rebuilt
        dropRecoveringIndexes( indexMap, rebuildingDescriptors.keySet() );

        // Rebuild indexes by recreating and repopulating them
        for ( Map.Entry<Long,RebuildingIndexDescriptor> entry : rebuildingDescriptors.entrySet() )
        {
            long indexId = entry.getKey();
            RebuildingIndexDescriptor descriptors = entry.getValue();

            /*
             * Passing in "false" for unique here may seem surprising, and.. well, yes, it is, I was surprised too.
             * However, it is actually perfectly safe, because whenever we have constraint indexes here, they will
             * be in a state where they didn't finish populating, and despite the fact that we re-create them here,
             * they will get dropped as soon as recovery is completed by the constraint system.
             */
            IndexProxy proxy = proxySetup.createPopulatingIndexProxy(
                    indexId, descriptors.getIndexDescriptor(), descriptors.getProviderDescriptor(), false, monitor );
            proxy.start();
            indexMap.putIndexProxy( indexId, proxy );
        }

        indexMapRef.setIndexMap( indexMap );

        samplingController.recoverIndexSamples();
        samplingController.start();

        // So at this point we've started population of indexes that needs to be rebuilt in the background.
        // Indexes backing uniqueness constraints are normally built within the transaction creating the constraint
        // and so we shouldn't leave such indexes in a populating state after recovery.
        // This is why we now go and wait for those indexes to be fully populated.
        for ( Map.Entry<Long,RebuildingIndexDescriptor> entry : rebuildingDescriptors.entrySet() )
        {
            if ( !entry.getValue().getConfiguration().isUnique() )
            {
                // It's not a uniqueness constraint, so don't wait for it to be rebuilt
                continue;
            }

            IndexProxy proxy;
            try
            {
                proxy = getIndexProxy( entry.getKey().longValue() );
            }
            catch ( IndexNotFoundKernelException e )
            {
                throw new ThisShouldNotHappenError( "Mattias",
                        "What? This index was seen during recovery just now, why isn't it available now?" );
            }

            monitor.awaitingPopulationOfRecoveredIndex( entry.getKey(), entry.getValue().getIndexDescriptor() );
            awaitOnline( proxy );
        }

        state = State.RUNNING;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.index.IndexingService.start.foreachIndexProxy.new BiConsumer<Long,IndexProxy> with (indexId, proxy) -> {InternalIndexState state1=proxy.getState(); in method public start() : void from class org.neo4j.kernel.impl.api.index.IndexingService


    @Override
    public Traverser traverse( final Iterable<Node> startNodes, final Iterable<Node> endNodes )
    {
        return new DefaultTraverser( () -> new BidirectionalTraverserIterator(
                statementFactory.get(),
                start, end, sideSelector, collisionPolicy, collisionEvaluator, maxDepth, startNodes, endNodes) );
    }

    @Override
    public Traverser traverse( final Iterable<Node> startNodes, final Iterable<Node> endNodes )
    {
        return new DefaultTraverser( new Factory<TraverserIterator>(){
            @Override
            public TraverserIterator newInstance()
            {
                return new BidirectionalTraverserIterator(
                        statementFactory.get(),
                        start, end, sideSelector, collisionPolicy, collisionEvaluator, maxDepth, startNodes, endNodes);
            }
        });
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.traversal.BidirectionalTraversalDescriptionImpl.traverse.new DefaultTraverser.new Factory<TraverserIterator> with () -> new BidirectionalTraverserIterator(statementFactory.get(),start,end,sideSelector,collisionPolicy,collisionEvaluator,maxDepth,startNodes,endNodes) in method public traverse(startNodes Iterable<Node>, endNodes Iterable<Node>) : Traverser from class org.neo4j.kernel.impl.traversal.BidirectionalTraversalDescriptionImpl


    public Traverser traverse( final Iterable<Node> iterableStartNodes )
    {
        return new DefaultTraverser( () -> {
            Resource statement = statementSupplier.get();
            MonoDirectionalTraverserIterator iterator = new MonoDirectionalTraverserIterator(
                    statement,
                    uniqueness.create( uniquenessParameter ),
                    expander, branchOrdering, evaluator,
                    iterableStartNodes, initialState, uniqueness );
            return sorting != null ? new SortingTraverserIterator( statement, sorting, iterator ) : iterator;
        } );
    }

    public Traverser traverse( final Iterable<Node> iterableStartNodes )
    {
        return new DefaultTraverser( new Factory<TraverserIterator>()
        {
            @Override
            public TraverserIterator newInstance()
            {
                Resource statement = statementSupplier.get();
                MonoDirectionalTraverserIterator iterator = new MonoDirectionalTraverserIterator(
                        statement,
                        uniqueness.create( uniquenessParameter ),
                        expander, branchOrdering, evaluator,
                        iterableStartNodes, initialState, uniqueness );
                return sorting != null ? new SortingTraverserIterator( statement, sorting, iterator ) : iterator;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.traversal.MonoDirectionalTraversalDescription.traverse.new DefaultTraverser.new Factory<TraverserIterator> with () -> {Resource statement=statementSupplier.get(); in method public traverse(iterableStartNodes Iterable<Node>) : Traverser from class org.neo4j.kernel.impl.traversal.MonoDirectionalTraversalDescription


    @Test
    public void shouldImportMultipleInputsWithAddedLabelsAndDefaultRelationshipType() throws Exception
    {
        // GIVEN
        List<String> nodeIds = nodeIds();
        Configuration config = Configuration.COMMAS;
        final String[] firstLabels = {"AddedOne", "AddedTwo"};
        final String[] secondLabels = {"AddedThree"};
        final String firstType = "TYPE_1";
        final String secondType = "TYPE_2";

        // WHEN
        importTool(
                "--into", dbRule.getStoreDirAbsolutePath(),
                "--nodes:" + join( firstLabels, ":" ),
                nodeData( true, config, nodeIds, lines( 0, NODE_COUNT / 2 ) ).getAbsolutePath(),
                "--nodes:" + join( secondLabels, ":" ),
                nodeData( true, config, nodeIds, lines( NODE_COUNT / 2, NODE_COUNT ) ).getAbsolutePath(),
                "--relationships:" + firstType,
                relationshipData( true, config, nodeIds, lines( 0, RELATIONSHIP_COUNT / 2 ), false ).getAbsolutePath(),
                "--relationships:" + secondType,
                relationshipData( true, config, nodeIds,
                        lines( RELATIONSHIP_COUNT / 2, RELATIONSHIP_COUNT ), false ).getAbsolutePath() );

        // THEN
        verifyData(
                node -> {
                    if ( node.getId() < NODE_COUNT / 2 )
                    {
                        assertNodeHasLabels( node, firstLabels );
                    }
                    else
                    {
                        assertNodeHasLabels( node, secondLabels );
                    }
                },
                relationship -> {
                    if ( relationship.getId() < RELATIONSHIP_COUNT / 2 )
                    {
                        assertEquals( firstType, relationship.getType().name() );
                    }
                    else
                    {
                        assertEquals( secondType, relationship.getType().name() );
                    }
                } );
    }

    @Test
    public void shouldImportMultipleInputsWithAddedLabelsAndDefaultRelationshipType() throws Exception
    {
        // GIVEN
        List<String> nodeIds = nodeIds();
        Configuration config = Configuration.COMMAS;
        final String[] firstLabels = {"AddedOne", "AddedTwo"};
        final String[] secondLabels = {"AddedThree"};
        final String firstType = "TYPE_1";
        final String secondType = "TYPE_2";

        // WHEN
        importTool(
                "--into", dbRule.getStoreDirAbsolutePath(),
                "--nodes:" + join( firstLabels, ":" ),
                nodeData( true, config, nodeIds, lines( 0, NODE_COUNT / 2 ) ).getAbsolutePath(),
                "--nodes:" + join( secondLabels, ":" ),
                nodeData( true, config, nodeIds, lines( NODE_COUNT / 2, NODE_COUNT ) ).getAbsolutePath(),
                "--relationships:" + firstType,
                relationshipData( true, config, nodeIds, lines( 0, RELATIONSHIP_COUNT / 2 ), false ).getAbsolutePath(),
                "--relationships:" + secondType,
                relationshipData( true, config, nodeIds,
                        lines( RELATIONSHIP_COUNT / 2, RELATIONSHIP_COUNT ), false ).getAbsolutePath() );

        // THEN
        verifyData(
                new Validator<Node>()
                {
                    @Override
                    public void validate( Node node )
                    {
                        if ( node.getId() < NODE_COUNT / 2 )
                        {
                            assertNodeHasLabels( node, firstLabels );
                        }
                        else
                        {
                            assertNodeHasLabels( node, secondLabels );
                        }
                    }
                },
                new Validator<Relationship>()
                {
                    @Override
                    public void validate( Relationship relationship )
                    {
                        if ( relationship.getId() < RELATIONSHIP_COUNT / 2 )
                        {
                            assertEquals( firstType, relationship.getType().name() );
                        }
                        else
                        {
                            assertEquals( secondType, relationship.getType().name() );
                        }
                    }
                } );
    }

Replace Anonymous With Lambda org.neo4j.tooling.ImportToolTest.shouldImportMultipleInputsWithAddedLabelsAndDefaultRelationshipType.verifyData.new Validator<Node> with node -> {if(node.getId() < NODE_COUNT / 2){assertNodeHasLabels(node,firstLabels); in method public shouldImportMultipleInputsWithAddedLabelsAndDefaultRelationshipType() : void from class org.neo4j.tooling.ImportToolTest


    @Test
    public void shouldHandleAdditiveLabelsWithSpaces() throws Exception
    {
        // GIVEN
        List<String> nodeIds = nodeIds();
        Configuration config = Configuration.COMMAS;
        final Label label1 = label( "My First Label" );
        final Label label2 = label( "My Other Label" );

        // WHEN
        importTool(
                "--into", dbRule.getStoreDirAbsolutePath(),
                "--nodes:My First Label:My Other Label",
                nodeData( true, config, nodeIds, alwaysTrue() ).getAbsolutePath(),
                "--relationships", relationshipData( true, config, nodeIds, alwaysTrue(), true ).getAbsolutePath() );

        // THEN
        verifyData( node -> {
            assertTrue( node.hasLabel( label1 ) );
            assertTrue( node.hasLabel( label2 ) );
        }, Validators.<Relationship>emptyValidator() );
    }

    @Test
    public void shouldHandleAdditiveLabelsWithSpaces() throws Exception
    {
        // GIVEN
        List<String> nodeIds = nodeIds();
        Configuration config = Configuration.COMMAS;
        final Label label1 = label( "My First Label" );
        final Label label2 = label( "My Other Label" );

        // WHEN
        importTool(
                "--into", dbRule.getStoreDirAbsolutePath(),
                "--nodes:My First Label:My Other Label",
                nodeData( true, config, nodeIds, alwaysTrue() ).getAbsolutePath(),
                "--relationships", relationshipData( true, config, nodeIds, alwaysTrue(), true ).getAbsolutePath() );

        // THEN
        verifyData( new Validator<Node>()
        {
            @Override
            public void validate( Node node )
            {
                assertTrue( node.hasLabel( label1 ) );
                assertTrue( node.hasLabel( label2 ) );
            }
        }, Validators.<Relationship>emptyValidator() );
    }

Replace Anonymous With Lambda org.neo4j.tooling.ImportToolTest.shouldHandleAdditiveLabelsWithSpaces.verifyData.new Validator<Node> with node -> {assertTrue(node.hasLabel(label1)); in method public shouldHandleAdditiveLabelsWithSpaces() : void from class org.neo4j.tooling.ImportToolTest


    public static <T> Predicate<T> all( final Iterable<Predicate<T>> predicates )
    {
        return item -> {
            for ( Predicate<T> predicate : predicates )
            {
                if ( !predicate.test( item ) )
                {
                    return false;
                }
            }
            return true;
        };
    }

    public static <T> Predicate<T> all( final Iterable<Predicate<T>> predicates )
    {
        return new Predicate<T>()
        {
            @Override
            public boolean test( T item )
            {
                for ( Predicate<T> predicate : predicates )
                {
                    if ( !predicate.test( item ) )
                    {
                        return false;
                    }
                }
                return true;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.function.Predicates.all.new Predicate<T> with item -> {for(Predicate<T> predicate: predicates){if(!predicate.test(item)){return false; in method public all(predicates Iterable<Predicate<T>>) : Predicate<T> from class org.neo4j.function.Predicates


    public static <T> Predicate<T> any( final Iterable<Predicate<T>> predicates )
    {
        return item -> {
            for ( Predicate<T> predicate : predicates )
            {
                if ( predicate.test( item ) )
                {
                    return true;
                }
            }
            return false;
        };
    }

    public static <T> Predicate<T> any( final Iterable<Predicate<T>> predicates )
    {
        return new Predicate<T>()
        {
            @Override
            public boolean test( T item )
            {
                for ( Predicate<T> predicate : predicates )
                {
                    if ( predicate.test( item ) )
                    {
                        return true;
                    }
                }
                return false;
            }
        };
    }

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


    public static <T> Predicate<T> instanceOfAny( final Class... classes )
    {
        return item -> {
            if ( item != null )
            {
                for ( Class clazz : classes )
                {
                    if ( clazz.isInstance( item ) )
                    {
                        return true;
                    }
                }
            }
            return false;
        };
    }

    public static <T> Predicate<T> instanceOfAny( final Class... classes )
    {
        return new Predicate<T>()
        {
            @Override
            public boolean test( T item )
            {
                if ( item != null )
                {
                    for ( Class clazz : classes )
                    {
                        if ( clazz.isInstance( item ) )
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.function.Predicates.instanceOfAny.new Predicate<T> with item -> {if(item != null){for(Class clazz: classes){if(clazz.isInstance(item)){return true; in method public instanceOfAny(classes Class...) : Predicate<T> from class org.neo4j.function.Predicates


    @Test
    public void testSimplestGraph()
    {
        // Layout:
        //    __
        //   /  \
        // (s)  (t)
        //   \__/
        graph.makeEdge( "s", "t" );
        graph.makeEdge( "s", "t" );
        testShortestPathFinder( finder -> {
            final Iterable<Path> paths = finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) );
            assertPaths( paths, "s,t", "s,t" );
            assertPaths( asList( finder.findSinglePath( graph.getNode( "s" ), graph.getNode( "t" ) ) ), "s,t" );
        }, PathExpanders.forTypeAndDirection( R1, BOTH ), 1 );
    }

    @Test
    public void testSimplestGraph()
    {
        // Layout:
        //    __
        //   /  \
        // (s)  (t)
        //   \__/
        graph.makeEdge( "s", "t" );
        graph.makeEdge( "s", "t" );
        testShortestPathFinder( new PathFinderTester()
        {
            @Override
            public void test( PathFinder<Path> finder )
            {
                final Iterable<Path> paths = finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) );
                assertPaths( paths, "s,t", "s,t" );
                assertPaths( asList( finder.findSinglePath( graph.getNode( "s" ), graph.getNode( "t" ) ) ), "s,t" );
            }
        }, PathExpanders.forTypeAndDirection( R1, BOTH ), 1 );
    }

Replace Anonymous With Lambda org.neo4j.graphalgo.impl.path.TestShortestPath.testSimplestGraph.testShortestPathFinder.new PathFinderTester with finder -> {final Iterable<Path> paths=finder.findAllPaths(graph.getNode("s"),graph.getNode("t")); in method public testSimplestGraph() : void from class org.neo4j.graphalgo.impl.path.TestShortestPath


    @Test
    public void testAnotherSimpleGraph()
    {
        // Layout:
        //   (m)
        //   /  \
        // (s)  (o)---(t)
        //   \  /       \
        //   (n)---(p)---(q)
        graph.makeEdge( "s", "m" );
        graph.makeEdge( "m", "o" );
        graph.makeEdge( "s", "n" );
        graph.makeEdge( "n", "p" );
        graph.makeEdge( "p", "q" );
        graph.makeEdge( "q", "t" );
        graph.makeEdge( "n", "o" );
        graph.makeEdge( "o", "t" );
        testShortestPathFinder( finder -> {
            final Iterable<Path> paths = finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) );
            assertPaths( paths, "s,m,o,t", "s,n,o,t" );
        }, PathExpanders.forTypeAndDirection( R1, BOTH ), 6 );
    }

    @Test
    public void testAnotherSimpleGraph()
    {
        // Layout:
        //   (m)
        //   /  \
        // (s)  (o)---(t)
        //   \  /       \
        //   (n)---(p)---(q)
        graph.makeEdge( "s", "m" );
        graph.makeEdge( "m", "o" );
        graph.makeEdge( "s", "n" );
        graph.makeEdge( "n", "p" );
        graph.makeEdge( "p", "q" );
        graph.makeEdge( "q", "t" );
        graph.makeEdge( "n", "o" );
        graph.makeEdge( "o", "t" );
        testShortestPathFinder( new PathFinderTester()
        {
            @Override
            public void test( PathFinder<Path> finder )
            {
                final Iterable<Path> paths = finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) );
                assertPaths( paths, "s,m,o,t", "s,n,o,t" );
            }
        }, PathExpanders.forTypeAndDirection( R1, BOTH ), 6 );
    }

Replace Anonymous With Lambda org.neo4j.graphalgo.impl.path.TestShortestPath.testAnotherSimpleGraph.testShortestPathFinder.new PathFinderTester with finder -> {final Iterable<Path> paths=finder.findAllPaths(graph.getNode("s"),graph.getNode("t")); in method public testAnotherSimpleGraph() : void from class org.neo4j.graphalgo.impl.path.TestShortestPath


    @Test
    public void makeSureShortestPathsReturnsNoLoops()
    {
        // Layout:
        //
        // (a)-->(b)==>(c)-->(e)
        //        ^    /
        //         \  v
        //         (d)
        //
        graph.makeEdgeChain( "a,b,c,d,b,c,e" );
        testShortestPathFinder( finder -> {
            final Node a = graph.getNode( "a" );
            final Node e = graph.getNode( "e" );
            assertPaths( finder.findAllPaths( a, e ), "a,b,c,e", "a,b,c,e" );
        }, PathExpanders.forTypeAndDirection( R1, BOTH ), 6 );
    }

    @Test
    public void makeSureShortestPathsReturnsNoLoops()
    {
        // Layout:
        //
        // (a)-->(b)==>(c)-->(e)
        //        ^    /
        //         \  v
        //         (d)
        //
        graph.makeEdgeChain( "a,b,c,d,b,c,e" );
        testShortestPathFinder( new PathFinderTester()
        {
            @Override
            public void test( PathFinder<Path> finder )
            {
                final Node a = graph.getNode( "a" );
                final Node e = graph.getNode( "e" );
                assertPaths( finder.findAllPaths( a, e ), "a,b,c,e", "a,b,c,e" );
            }
        }, PathExpanders.forTypeAndDirection( R1, BOTH ), 6 );
    }

Replace Anonymous With Lambda org.neo4j.graphalgo.impl.path.TestShortestPath.makeSureShortestPathsReturnsNoLoops.testShortestPathFinder.new PathFinderTester with finder -> {final Node a=graph.getNode("a"); in method public makeSureShortestPathsReturnsNoLoops() : void from class org.neo4j.graphalgo.impl.path.TestShortestPath


    @Test
    public void makeSureDescentStopsWhenPathIsFound() throws Exception
    {
        /*
         * (a)==>(b)==>(c)==>(d)==>(e)
         *   \
         *    v
         *    (f)-->(g)-->(h)-->(i)
         */
        graph.makeEdgeChain( "a,b,c,d,e" );
        graph.makeEdgeChain( "a,b,c,d,e" );
        graph.makeEdgeChain( "a,f,g,h,i" );
        final Node a = graph.getNode( "a" );
        final Node b = graph.getNode( "b" );
        final Node c = graph.getNode( "c" );
        final Set<Node> allowedNodes = new HashSet<>( Arrays.asList( a, b, c ) );
        final PathFinder<Path> finder = new ShortestPath( 100, Traversal.expanderForAllTypes( Direction.OUTGOING ) )
        {
            @Override
            protected Node filterNextLevelNodes( Node nextNode )
            {
                if ( !allowedNodes.contains( nextNode ) )
                {
                    return null;
                }
                return nextNode;
            }
        };
        Iterator<Path> paths = finder.findAllPaths( a, c ).iterator();
        for ( int i = 0; i < 4; i++ )
        {
            Path aToBToC = paths.next();
            assertPath( aToBToC, a, b, c );
        }
        assertFalse( "should only have contained four paths", paths.hasNext() );
    }

    @Test
    public void makeSureDescentStopsWhenPathIsFound() throws Exception
    {
        /*
         * (a)==>(b)==>(c)==>(d)==>(e)
         *   \
         *    v
         *    (f)-->(g)-->(h)-->(i)
         */
        graph.makeEdgeChain( "a,b,c,d,e" );
        graph.makeEdgeChain( "a,b,c,d,e" );
        graph.makeEdgeChain( "a,f,g,h,i" );
        final Node a = graph.getNode( "a" );
        final Node b = graph.getNode( "b" );
        final Node c = graph.getNode( "c" );
        final Set<Node> allowedNodes = new HashSet<Node>( Arrays.asList( a, b, c ) );
        final PathFinder<Path> finder = new ShortestPath( 100, Traversal.expanderForAllTypes( Direction.OUTGOING ) )
        {
            @Override
            protected Node filterNextLevelNodes( Node nextNode )
            {
                if ( !allowedNodes.contains( nextNode ) )
                {
                    return null;
                }
                return nextNode;
            }
        };
        Iterator<Path> paths = finder.findAllPaths( a, c ).iterator();
        for ( int i = 0; i < 4; i++ )
        {
            Path aToBToC = paths.next();
            assertPath( aToBToC, a, b, c );
        }
        assertFalse( "should only have contained four paths", paths.hasNext() );
    }

Replace Generic With Diamond HashSet<Node> with HashSet<> in method public makeSureDescentStopsWhenPathIsFound() : void from class org.neo4j.graphalgo.impl.path.TestShortestPath


    @Test
    public void makeSureRelationshipNotConnectedIssueNotThere() throws Exception
    {
        /*
         *                                  (g)
         *                                  / ^
         *                                 v   \
         * (a)<--(b)<--(c)<--(d)<--(e)<--(f)   (i)
         *                                 ^   /
         *                                  \ v
         *                                  (h)
         */
        graph.makeEdgeChain( "i,g,f,e,d,c,b,a" );
        graph.makeEdgeChain( "i,h,f" );
        testShortestPathFinder( finder -> {
            final Node start = graph.getNode( "a" );
            final Node end = graph.getNode( "i" );
            assertPaths( finder.findAllPaths( start, end ), "a,b,c,d,e,f,g,i", "a,b,c,d,e,f,h,i" );
        }, PathExpanders.forTypeAndDirection( R1, INCOMING ), 10 );
    }

    @Test
    public void makeSureRelationshipNotConnectedIssueNotThere() throws Exception
    {
        /*
         *                                  (g)
         *                                  / ^
         *                                 v   \
         * (a)<--(b)<--(c)<--(d)<--(e)<--(f)   (i)
         *                                 ^   /
         *                                  \ v
         *                                  (h)
         */
        graph.makeEdgeChain( "i,g,f,e,d,c,b,a" );
        graph.makeEdgeChain( "i,h,f" );
        testShortestPathFinder( new PathFinderTester()
        {
            @Override
            public void test( PathFinder<Path> finder )
            {
                final Node start = graph.getNode( "a" );
                final Node end = graph.getNode( "i" );
                assertPaths( finder.findAllPaths( start, end ), "a,b,c,d,e,f,g,i", "a,b,c,d,e,f,h,i" );
            }
        }, PathExpanders.forTypeAndDirection( R1, INCOMING ), 10 );
    }

Replace Anonymous With Lambda org.neo4j.graphalgo.impl.path.TestShortestPath.makeSureRelationshipNotConnectedIssueNotThere.testShortestPathFinder.new PathFinderTester with finder -> {final Node start=graph.getNode("a"); in method public makeSureRelationshipNotConnectedIssueNotThere() : void from class org.neo4j.graphalgo.impl.path.TestShortestPath


        public FilteredPatternFinder( Iterable<PatternMatch> source,
            final Map<String, PatternNode> objectVariables )
        {
            super( source, item -> {
                Set<PatternGroup> calculatedGroups = new HashSet<>();
                for ( PatternElement element : item.getElements() )
                {
                    PatternNode node = element.getPatternNode();
                    PatternGroup group = node.getGroup();
                    if ( calculatedGroups.add( group ) )
                    {
                        FilterValueGetter valueGetter = new SimpleRegexValueGetter(
                            objectVariables, item, group.getFilters() );
                        for ( FilterExpression expression : group.getFilters() )
                        {
                            if ( !expression.matches( valueGetter ) )
                            {
                                return false;
                            }
                        }
                    }
                }
                return true;
            } );
        }

        public FilteredPatternFinder( Iterable<PatternMatch> source,
            final Map<String, PatternNode> objectVariables )
        {
            super( source, new Predicate<PatternMatch>()
            {
                public boolean test( PatternMatch item )
                {
                    Set<PatternGroup> calculatedGroups = new HashSet<PatternGroup>();
                    for ( PatternElement element : item.getElements() )
                    {
                        PatternNode node = element.getPatternNode();
                        PatternGroup group = node.getGroup();
                        if ( calculatedGroups.add( group ) )
                        {
                            FilterValueGetter valueGetter = new SimpleRegexValueGetter(
                                objectVariables, item, group.getFilters() );
                            for ( FilterExpression expression : group.getFilters() )
                            {
                                if ( !expression.matches( valueGetter ) )
                                {
                                    return false;
                                }
                            }
                        }
                    }
                    return true;
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.graphmatching.PatternMatcher.FilteredPatternFinder.FilteredPatternFinder.new Predicate<PatternMatch> with item -> {Set<PatternGroup> calculatedGroups=new HashSet<>(); in method public FilteredPatternFinder(source Iterable<PatternMatch>, objectVariables Map<String,PatternNode>) from class org.neo4j.graphmatching.PatternMatcher.FilteredPatternFinder


		public final void configure( StyleConfiguration configuration )
		{
			ParameterGetter<Relationship> getter = ( relationship, key ) -> {
				if ( key.equals( "color" ) )
				{
					return getColor( relationship );
				}
				else
				{
					return getFontColor( relationship );
				}
			};
			configuration.setRelationshipParameterGetter( "color", getter );
            configuration.setRelationshipParameterGetter( "fontcolor", getter );
		}

		public final void configure( StyleConfiguration configuration )
		{
			ParameterGetter<Relationship> getter = new ParameterGetter<Relationship>()
			{
				public String getParameterValue( Relationship relationship,
				    String key )
				{
                    if ( key.equals( "color" ) )
                    {
                        return getColor( relationship );
                    }
                    else
                    {
                        return getFontColor( relationship );
                    }
				}
			};
            configuration.setRelationshipParameterGetter( "color", getter );
            configuration.setRelationshipParameterGetter( "fontcolor", getter );
		}

Replace Anonymous With Lambda org.neo4j.visualization.graphviz.StyleParameter.RelationshipColor.configure.getter.new ParameterGetter<Relationship> with (relationship, key) -> {if(key.equals("color")){return getColor(relationship); in method public configure(configuration StyleConfiguration) : void from class org.neo4j.visualization.graphviz.StyleParameter.RelationshipColor


		public final void configure( StyleConfiguration configuration )
		{
			ParameterGetter<Node> getter = ( node, key ) -> {
				if ( key.equals( "color" ) )
				{
					return getColor( node );
				}
				else if ( key.equals( "fontcolor" ) )
				{
					return getFontColor( node );
				}
				else
				{
					return getFillColor( node );
				}
			};
			configuration.setDefaultNodeProperty( "style", "filled" );
			configuration.setNodeParameterGetter( "color", getter );
			configuration.setNodeParameterGetter( "fillcolor", getter );
			configuration.setNodeParameterGetter( "fontcolor", getter );
		}

		public final void configure( StyleConfiguration configuration )
		{
			ParameterGetter<Node> getter = new ParameterGetter<Node>()
			{
				public String getParameterValue( Node node, String key )
				{
					if ( key.equals( "color" ) )
					{
						return getColor( node );
					}
					else if ( key.equals( "fontcolor" ) )
					{
						return getFontColor( node );
					}
					else
					{
						return getFillColor( node );
					}
				}
			};
			configuration.setDefaultNodeProperty( "style", "filled" );
			configuration.setNodeParameterGetter( "color", getter );
			configuration.setNodeParameterGetter( "fillcolor", getter );
			configuration.setNodeParameterGetter( "fontcolor", getter );
		}

Replace Anonymous With Lambda org.neo4j.visualization.graphviz.StyleParameter.NodeColor.configure.getter.new ParameterGetter<Node> with (node, key) -> {if(key.equals("color")){return getColor(node); in method public configure(configuration StyleConfiguration) : void from class org.neo4j.visualization.graphviz.StyleParameter.NodeColor