    public static Predicate<ClusterManager.ManagedCluster> instanceEvicted( final HighlyAvailableGraphDatabase instance )
    {
        return managedCluster ->
        {
            InstanceId instanceId = managedCluster.getServerId( instance );

            Iterable<HighlyAvailableGraphDatabase> members = managedCluster.getAllMembers();
            for ( HighlyAvailableGraphDatabase member : members )
            {
                if ( instanceId.equals( managedCluster.getServerId( member ) ) )
                {
                    if ( member.role().equals( "UNKNOWN" ) )
                    {
                        return true;
                    }
                }
            }
            return false;
        };
    }

    public static Predicate<ClusterManager.ManagedCluster> instanceEvicted( final HighlyAvailableGraphDatabase instance )
    {
        return new Predicate<ClusterManager.ManagedCluster>()
        {
            @Override
            public boolean test( ClusterManager.ManagedCluster managedCluster )
            {
                InstanceId instanceId = managedCluster.getServerId( instance );

                Iterable<HighlyAvailableGraphDatabase> members = managedCluster.getAllMembers();
                for ( HighlyAvailableGraphDatabase member : members )
                {
                    if ( instanceId.equals( managedCluster.getServerId( member ) ) )
                    {
                        if ( member.role().equals( "UNKNOWN" ) )
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.ha.ClusterManager.instanceEvicted.new Predicate<ClusterManager.ManagedCluster> with managedCluster -> {InstanceId instanceId=managedCluster.getServerId(instance); in method public instanceEvicted(instance HighlyAvailableGraphDatabase) : Predicate<ClusterManager.ManagedCluster> from class org.neo4j.kernel.impl.ha.ClusterManager


    @Test
    public void shouldSendRequestsToNewlyAddedReadReplicas() throws Throwable
    {
        // given
        cluster = clusterRule.withNumberOfReadReplicas( 1 )
                .withSharedCoreParams( stringMap( CausalClusteringSettings.cluster_routing_ttl.name(), "1s" ) )
                .startCluster();

        CoreClusterMember leader = cluster.awaitLeader();
        Driver driver = GraphDatabase.driver( leader.routingURI(), AuthTokens.basic( "neo4j", "neo4j" ) );

        String bookmark = inExpirableSession( driver, ( d ) -> d.session( AccessMode.WRITE ), ( session ) ->
        {
            try ( Transaction tx = session.beginTransaction() )
            {
                tx.run( "CREATE (p:Person {name: {name} })", Values.parameters( "name", "Jim" ) );
                tx.success();
            }

            return session.lastBookmark();
        } );

        // when
        Set<String> readReplicas = new HashSet<>();

        for ( ReadReplica readReplica : cluster.readReplicas() )
        {
            readReplicas.add( readReplica.boltAdvertisedAddress() );
        }

        for ( int i = 10; i <= 13; i++ )
        {
            ReadReplica newReadReplica = cluster.addReadReplicaWithId( i );
            readReplicas.add( newReadReplica.boltAdvertisedAddress() );
            newReadReplica.start();
        }

        assertEventually( "Failed to send requests to all servers", () ->
        {
            for ( int i = 0; i < cluster.readReplicas().size(); i++ ) // don't care about cores
            {
                try ( Session session = driver.session( AccessMode.READ, bookmark ) )
                {
                    executeReadQuery( bookmark, session );

                    session.readTransaction( (TransactionWork<Void>) tx ->
                    {
                        StatementResult result = tx.run( "MATCH (n:Person) RETURN COUNT(*) AS count" );

                        assertEquals( 1, result.next().get( "count" ).asInt() );

                        readReplicas.remove( result.summary().server().address() );

                        return null;
                    } );

                }
                catch ( Throwable throwable )
                {
                    return false;
                }
            }

            return readReplicas.size() == 0; // have sent something to all replicas
        }, is( true ), 30, SECONDS );
    }

    @Test
    public void shouldSendRequestsToNewlyAddedReadReplicas() throws Throwable
    {
        // given
        cluster = clusterRule.withNumberOfReadReplicas( 1 )
                .withSharedCoreParams( stringMap( CausalClusteringSettings.cluster_routing_ttl.name(), "1s" ) )
                .startCluster();

        CoreClusterMember leader = cluster.awaitLeader();
        Driver driver = GraphDatabase.driver( leader.routingURI(), AuthTokens.basic( "neo4j", "neo4j" ) );

        String bookmark = inExpirableSession( driver, ( d ) -> d.session( AccessMode.WRITE ), ( session ) ->
        {
            try ( Transaction tx = session.beginTransaction() )
            {
                tx.run( "CREATE (p:Person {name: {name} })", Values.parameters( "name", "Jim" ) );
                tx.success();
            }

            return session.lastBookmark();
        } );

        // when
        Set<String> readReplicas = new HashSet<>();

        for ( ReadReplica readReplica : cluster.readReplicas() )
        {
            readReplicas.add( readReplica.boltAdvertisedAddress() );
        }

        for ( int i = 10; i <= 13; i++ )
        {
            ReadReplica newReadReplica = cluster.addReadReplicaWithId( i );
            readReplicas.add( newReadReplica.boltAdvertisedAddress() );
            newReadReplica.start();
        }

        assertEventually( "Failed to send requests to all servers", () ->
        {
            for ( int i = 0; i < cluster.readReplicas().size(); i++ ) // don't care about cores
            {
                try ( Session session = driver.session( AccessMode.READ, bookmark ) )
                {
                    executeReadQuery( bookmark, session );

                    session.readTransaction( new TransactionWork<Void>()
                    {
                        @Override
                        public Void execute( Transaction tx )
                        {
                            StatementResult result = tx.run( "MATCH (n:Person) RETURN COUNT(*) AS count" );

                            assertEquals( 1, result.next().get( "count" ).asInt() );

                            readReplicas.remove( result.summary().server().address() );

                            return null;
                        }
                    } );

                }
                catch ( Throwable throwable )
                {
                    return false;
                }
            }

            return readReplicas.size() == 0; // have sent something to all replicas
        }, is( true ), 30, SECONDS );
    }

Replace Anonymous With Lambda org.neo4j.causalclustering.scenarios.BoltCausalClusteringIT.shouldSendRequestsToNewlyAddedReadReplicas.assertEventually.readTransaction.new TransactionWork<Void> with tx -> {StatementResult result=tx.run("MATCH (n:Person) RETURN COUNT(*) AS count"); in method public shouldSendRequestsToNewlyAddedReadReplicas() : void from class org.neo4j.causalclustering.scenarios.BoltCausalClusteringIT


    private void blockUntilServerAvailable( final URL url ) throws Exception
    {
        final CountDownLatch latch = new CountDownLatch( 1 );
        final PointerTo<Boolean> flag = new PointerTo<>( false );

        Thread t = new Thread( () ->
        {
            while ( !flag.getValue() )
            {
                try
                {
                    HttpGet httpget = new HttpGet( url.toURI() );
                    httpget.addHeader( "Accept", "application/json" );
                    DefaultHttpClient client = new DefaultHttpClient();
                    client.execute( httpget );

                    // If we get here, the server's ready
                    flag.setValue( true );
                    latch.countDown();
                }
                catch ( Exception e )
                {
                    throw new RuntimeException( e );
                }
            }
        } );

        t.run();

        assertTrue( latch.await( 1000, TimeUnit.MILLISECONDS ) );

        t.join();
    }

    private void blockUntilServerAvailable( final URL url ) throws Exception
    {
        final CountDownLatch latch = new CountDownLatch( 1 );
        final PointerTo<Boolean> flag = new PointerTo<>( false );

        Thread t = new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                while ( !flag.getValue() )
                {
                    try
                    {
                        HttpGet httpget = new HttpGet( url.toURI() );
                        httpget.addHeader( "Accept", "application/json" );
                        DefaultHttpClient client = new DefaultHttpClient();
                        client.execute( httpget );

                        // If we get here, the server's ready
                        flag.setValue( true );
                        latch.countDown();
                    }
                    catch ( Exception e )
                    {
                        throw new RuntimeException( e );
                    }
                }
            }
        } );

        t.run();

        assertTrue( latch.await( 1000, TimeUnit.MILLISECONDS ) );

        t.join();
    }

Replace Anonymous With Lambda org.neo4j.ext.udc.impl.UdcExtensionImplTest.blockUntilServerAvailable.t.new Thread.new Runnable with () -> {while(!flag.getValue()){tryHttpGet httpget=new HttpGet(url.toURI()); in method private blockUntilServerAvailable(url URL) : void from class org.neo4j.ext.udc.impl.UdcExtensionImplTest


    @Test
    public void shouldIncludePrefixedSystemProperties() throws Exception
    {
        withSystemProperty( UdcConstants.UDC_PROPERTY_PREFIX + ".test", "udc-property", () ->
        {
            withSystemProperty( "os.test", "os-property", () ->
            {
                graphdb = createDatabase( config );
                assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO );
                assertEquals( "udc-property", handler.getQueryMap().get( "test" ) );
                assertEquals( "os-property", handler.getQueryMap().get( "os.test" ) );
                return null;
            } );
            return null;
        } );
    }

    @Test
    public void shouldIncludePrefixedSystemProperties() throws Exception
    {
        withSystemProperty( UdcConstants.UDC_PROPERTY_PREFIX + ".test", "udc-property", new Callable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                withSystemProperty( "os.test", "os-property", new Callable<Void>()
                {
                    @Override
                    public Void call() throws Exception
                    {
                        graphdb = createDatabase( config );
                        assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO );
                        assertEquals( "udc-property", handler.getQueryMap().get( "test" ) );
                        assertEquals( "os-property", handler.getQueryMap().get( "os.test" ) );
                        return null;
                    }
                } );
                return null;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.ext.udc.impl.UdcExtensionImplTest.shouldIncludePrefixedSystemProperties.withSystemProperty.new Callable<Void> with () -> {withSystemProperty("os.test","os-property",() -> { in method public shouldIncludePrefixedSystemProperties() : void from class org.neo4j.ext.udc.impl.UdcExtensionImplTest


    @Test
    public void shouldNotIncludeDistributionForWindows() throws Exception
    {
        withSystemProperty( "os.name", "Windows", () ->
        {
            graphdb = createDatabase( config );
            assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO );
            assertEquals( UdcConstants.UNKNOWN_DIST, handler.getQueryMap().get( "dist" ) );
            return null;
        } );
    }

    @Test
    public void shouldNotIncludeDistributionForWindows() throws Exception
    {
        withSystemProperty( "os.name", "Windows", new Callable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                graphdb = createDatabase( config );
                assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO );
                assertEquals( UdcConstants.UNKNOWN_DIST, handler.getQueryMap().get( "dist" ) );
                return null;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.ext.udc.impl.UdcExtensionImplTest.shouldNotIncludeDistributionForWindows.withSystemProperty.new Callable<Void> with () -> {graphdb=createDatabase(config); in method public shouldNotIncludeDistributionForWindows() : void from class org.neo4j.ext.udc.impl.UdcExtensionImplTest


    @Test
    public void shouldNotIncludeDistributionForMacOS() throws Exception
    {
        withSystemProperty( "os.name", "Mac OS X", () ->
        {
            graphdb = createDatabase( config );
            assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO );
            assertEquals( UdcConstants.UNKNOWN_DIST, handler.getQueryMap().get( "dist" ) );
            return null;
        } );
    }

    @Test
    public void shouldNotIncludeDistributionForMacOS() throws Exception
    {
        withSystemProperty( "os.name", "Mac OS X", new Callable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                graphdb = createDatabase( config );
                assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO );
                assertEquals( UdcConstants.UNKNOWN_DIST, handler.getQueryMap().get( "dist" ) );
                return null;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.ext.udc.impl.UdcExtensionImplTest.shouldNotIncludeDistributionForMacOS.withSystemProperty.new Callable<Void> with () -> {graphdb=createDatabase(config); in method public shouldNotIncludeDistributionForMacOS() : void from class org.neo4j.ext.udc.impl.UdcExtensionImplTest


    public Template( InputStream templateFile )
    {
        this.templateFile = templateFile;
        substitutor = new VariableSubstitutor();
        substitutionFunction = name ->
        {
            String var = System.getenv( name );
            return var == null ? "" : var;
        };
    }

    public Template( InputStream templateFile )
    {
        this.templateFile = templateFile;
        substitutor = new VariableSubstitutor();
        substitutionFunction = new Function<String, String>()
        {
            @Override
            public String apply( String name )
            {
                String var = System.getenv( name );
                return var == null ? "" : var;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.desktop.config.portable.Template.Template.new Function<String,String> with name -> {String var=System.getenv(name); in method public Template(templateFile InputStream) from class org.neo4j.desktop.config.portable.Template


    private JButton createOptionsButton()
    {
        return Components.createTextButton( ellipsis( "Options" ), e ->
        {
            JDialog settingsDialog = new SettingsDialog( MainWindow.this, model );
            settingsDialog.setLocationRelativeTo( null );
            settingsDialog.setVisible( true );
        } );
    }

    private JButton createOptionsButton()
    {
        return Components.createTextButton( ellipsis( "Options" ), new ActionListener()
        {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                JDialog settingsDialog = new SettingsDialog( MainWindow.this, model );
                settingsDialog.setLocationRelativeTo( null );
                settingsDialog.setVisible( true );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.desktop.ui.MainWindow.createOptionsButton.createTextButton.new ActionListener with e -> {JDialog settingsDialog=new SettingsDialog(MainWindow.this,model); in method private createOptionsButton() : JButton from class org.neo4j.desktop.ui.MainWindow


    private JButton createStopButton()
    {
        return Components.createTextButton( "Stop", e ->
        {
            updateStatus( DatabaseStatus.STOPPING );

            invokeLater( () ->
            {
                databaseActions.stop();
                updateStatus( STOPPED );
            } );
        } );
    }

    private JButton createStopButton()
    {
        return Components.createTextButton( "Stop", new ActionListener()
        {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                updateStatus( DatabaseStatus.STOPPING );

                invokeLater( new Runnable()
                {
                    @Override
                    public void run()
                    {
                        databaseActions.stop();
                        updateStatus( STOPPED );
                    }
                } );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.desktop.ui.MainWindow.createStopButton.createTextButton.new ActionListener with e -> {updateStatus(DatabaseStatus.STOPPING); in method private createStopButton() : JButton from class org.neo4j.desktop.ui.MainWindow


    /**
     * This is deprecated. Use {@link TestGraphDatabaseFactory} instead
     */
    @Deprecated
    public ImpermanentGraphDatabase()
    {
        this( new HashMap<>() );
    }

    /**
     * This is deprecated. Use {@link TestGraphDatabaseFactory} instead
     */
    @Deprecated
    public ImpermanentGraphDatabase()
    {
        this( new HashMap<String, String>() );
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public ImpermanentGraphDatabase() from class org.neo4j.test.ImpermanentGraphDatabase


    public ImpermanentGraphDatabase( File storeDir )
    {
        this( storeDir, new HashMap<>() );
    }

    public ImpermanentGraphDatabase( File storeDir )
    {
        this( storeDir, new HashMap<String, String>() );
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public ImpermanentGraphDatabase(storeDir File) from class org.neo4j.test.ImpermanentGraphDatabase


    void compareTo( TransactionData data )
    {
        Set<Node> expectedCreatedNodes = new HashSet<>( this.expectedCreatedNodes );
        Set<Relationship> expectedCreatedRelationships = new HashSet<>( this.expectedCreatedRelationships );
        Set<Node> expectedDeletedNodes = new HashSet<>( this.expectedDeletedNodes );
        Set<Relationship> expectedDeletedRelationships = new HashSet<>( this.expectedDeletedRelationships );
        Map<Node, Map<String, PropertyEntryImpl<Node>>> expectedAssignedNodeProperties =
                clone( this.expectedAssignedNodeProperties );
        Map<Relationship, Map<String, PropertyEntryImpl<Relationship>>> expectedAssignedRelationshipProperties =
                clone( this.expectedAssignedRelationshipProperties );
        Map<Node, Map<String, PropertyEntryImpl<Node>>> expectedRemovedNodeProperties =
                clone( this.expectedRemovedNodeProperties );
        Map<Relationship, Map<String, PropertyEntryImpl<Relationship>>> expectedRemovedRelationshipProperties =
                clone( this.expectedRemovedRelationshipProperties );
        Map<Node,Set<String>> expectedAssignedLabels = cloneLabelData( this.expectedAssignedLabels );
        Map<Node,Set<String>> expectedRemovedLabels = cloneLabelData( this.expectedRemovedLabels );

        for ( Node node : data.createdNodes() )
        {
            assertTrue( expectedCreatedNodes.remove( node ) );
            assertFalse( data.isDeleted( node ) );
        }
        assertTrue( "Expected some created nodes that weren't seen: " + expectedCreatedNodes,
                expectedCreatedNodes.isEmpty() );

        for ( Relationship rel : data.createdRelationships() )
        {
            assertTrue( expectedCreatedRelationships.remove( rel ) );
            assertFalse( data.isDeleted( rel ) );
        }
        assertTrue( "Expected created relationships not encountered " + expectedCreatedRelationships,
                expectedCreatedRelationships.isEmpty() );

        for ( Node node : data.deletedNodes() )
        {
            assertTrue( "Unexpected deleted node " + node, expectedDeletedNodes.remove( node ) );
            assertTrue( data.isDeleted( node ) );
        }
        assertTrue( "Expected deleted nodes: " + expectedDeletedNodes, expectedDeletedNodes.isEmpty() );

        for ( Relationship rel : data.deletedRelationships() )
        {
            assertTrue( expectedDeletedRelationships.remove( rel ) );
            assertTrue( data.isDeleted( rel ) );
        }
        assertTrue( "Expected deleted relationships not encountered " + expectedDeletedRelationships,
                expectedDeletedRelationships.isEmpty() );

        for ( PropertyEntry<Node> entry : data.assignedNodeProperties() )
        {
            checkAssigned( expectedAssignedNodeProperties, entry );
            assertFalse( data.isDeleted( entry.entity() ) );
        }
        assertTrue( "Expected assigned node properties not encountered " + expectedAssignedNodeProperties,
                expectedAssignedNodeProperties.isEmpty() );

        for ( PropertyEntry<Relationship> entry : data.assignedRelationshipProperties() )
        {
            checkAssigned( expectedAssignedRelationshipProperties, entry );
            assertFalse( data.isDeleted( entry.entity() ) );
        }
        assertTrue( "Expected assigned relationship properties not encountered " + expectedAssignedRelationshipProperties,
                expectedAssignedRelationshipProperties.isEmpty() );

        for ( PropertyEntry<Node> entry : data.removedNodeProperties() )
        {
            checkRemoved( expectedRemovedNodeProperties, entry );
        }
        assertTrue( "Expected removed node properties not encountered " + expectedRemovedNodeProperties,
                expectedRemovedNodeProperties.isEmpty() );

        for ( PropertyEntry<Relationship> entry : data.removedRelationshipProperties() )
        {
            checkRemoved( expectedRemovedRelationshipProperties, entry );
        }
        assertTrue( "Expected removed relationship properties not encountered " + expectedRemovedRelationshipProperties,
                expectedRemovedRelationshipProperties.isEmpty() );

        for ( LabelEntry entry : data.assignedLabels() )
        {
            check( expectedAssignedLabels, entry );
        }
        assertTrue( "Expected assigned labels not encountered " + expectedAssignedLabels,
                expectedAssignedLabels.isEmpty() );

        for ( LabelEntry entry : data.removedLabels() )
        {
            check( expectedRemovedLabels, entry );
        }
        assertTrue( "Expected removed labels not encountered " + expectedRemovedLabels,
                expectedRemovedLabels.isEmpty() );
    }

    void compareTo( TransactionData data )
    {
        Set<Node> expectedCreatedNodes = new HashSet<>( this.expectedCreatedNodes );
        Set<Relationship> expectedCreatedRelationships = new HashSet<>( this.expectedCreatedRelationships );
        Set<Node> expectedDeletedNodes = new HashSet<Node>( this.expectedDeletedNodes );
        Set<Relationship> expectedDeletedRelationships = new HashSet<>( this.expectedDeletedRelationships );
        Map<Node, Map<String, PropertyEntryImpl<Node>>> expectedAssignedNodeProperties =
                clone( this.expectedAssignedNodeProperties );
        Map<Relationship, Map<String, PropertyEntryImpl<Relationship>>> expectedAssignedRelationshipProperties =
                clone( this.expectedAssignedRelationshipProperties );
        Map<Node, Map<String, PropertyEntryImpl<Node>>> expectedRemovedNodeProperties =
                clone( this.expectedRemovedNodeProperties );
        Map<Relationship, Map<String, PropertyEntryImpl<Relationship>>> expectedRemovedRelationshipProperties =
                clone( this.expectedRemovedRelationshipProperties );
        Map<Node,Set<String>> expectedAssignedLabels = cloneLabelData( this.expectedAssignedLabels );
        Map<Node,Set<String>> expectedRemovedLabels = cloneLabelData( this.expectedRemovedLabels );

        for ( Node node : data.createdNodes() )
        {
            assertTrue( expectedCreatedNodes.remove( node ) );
            assertFalse( data.isDeleted( node ) );
        }
        assertTrue( "Expected some created nodes that weren't seen: " + expectedCreatedNodes,
                expectedCreatedNodes.isEmpty() );

        for ( Relationship rel : data.createdRelationships() )
        {
            assertTrue( expectedCreatedRelationships.remove( rel ) );
            assertFalse( data.isDeleted( rel ) );
        }
        assertTrue( "Expected created relationships not encountered " + expectedCreatedRelationships,
                expectedCreatedRelationships.isEmpty() );

        for ( Node node : data.deletedNodes() )
        {
            assertTrue( "Unexpected deleted node " + node, expectedDeletedNodes.remove( node ) );
            assertTrue( data.isDeleted( node ) );
        }
        assertTrue( "Expected deleted nodes: " + expectedDeletedNodes, expectedDeletedNodes.isEmpty() );

        for ( Relationship rel : data.deletedRelationships() )
        {
            assertTrue( expectedDeletedRelationships.remove( rel ) );
            assertTrue( data.isDeleted( rel ) );
        }
        assertTrue( "Expected deleted relationships not encountered " + expectedDeletedRelationships,
                expectedDeletedRelationships.isEmpty() );

        for ( PropertyEntry<Node> entry : data.assignedNodeProperties() )
        {
            checkAssigned( expectedAssignedNodeProperties, entry );
            assertFalse( data.isDeleted( entry.entity() ) );
        }
        assertTrue( "Expected assigned node properties not encountered " + expectedAssignedNodeProperties,
                expectedAssignedNodeProperties.isEmpty() );

        for ( PropertyEntry<Relationship> entry : data.assignedRelationshipProperties() )
        {
            checkAssigned( expectedAssignedRelationshipProperties, entry );
            assertFalse( data.isDeleted( entry.entity() ) );
        }
        assertTrue( "Expected assigned relationship properties not encountered " + expectedAssignedRelationshipProperties,
                expectedAssignedRelationshipProperties.isEmpty() );

        for ( PropertyEntry<Node> entry : data.removedNodeProperties() )
        {
            checkRemoved( expectedRemovedNodeProperties, entry );
        }
        assertTrue( "Expected removed node properties not encountered " + expectedRemovedNodeProperties,
                expectedRemovedNodeProperties.isEmpty() );

        for ( PropertyEntry<Relationship> entry : data.removedRelationshipProperties() )
        {
            checkRemoved( expectedRemovedRelationshipProperties, entry );
        }
        assertTrue( "Expected removed relationship properties not encountered " + expectedRemovedRelationshipProperties,
                expectedRemovedRelationshipProperties.isEmpty() );

        for ( LabelEntry entry : data.assignedLabels() )
        {
            check( expectedAssignedLabels, entry );
        }
        assertTrue( "Expected assigned labels not encountered " + expectedAssignedLabels,
                expectedAssignedLabels.isEmpty() );

        for ( LabelEntry entry : data.removedLabels() )
        {
            check( expectedRemovedLabels, entry );
        }
        assertTrue( "Expected removed labels not encountered " + expectedRemovedLabels,
                expectedRemovedLabels.isEmpty() );
    }

Replace Generic With Diamond HashSet<Node> with HashSet<> in method package compareTo(data TransactionData) : void from class org.neo4j.kernel.impl.event.ExpectedTransactionData


        void beginTx() throws Exception
        {
            execute( (WorkerCommand<State,Void>) state ->
            {
                state.tx = state.graphDb.beginTx();
                return null;
            } );
        }

        void beginTx() throws Exception
        {
            execute( new WorkerCommand<State, Void>()
            {
                @Override
                public Void doWork( State state )
                {
                    state.tx = state.graphDb.beginTx();
                    return null;
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.ManualAcquireLockTest.Worker.beginTx.execute.new WorkerCommand<State,Void> with state -> {state.tx=state.graphDb.beginTx(); in method package beginTx() : void from class org.neo4j.kernel.impl.transaction.ManualAcquireLockTest.Worker


        void finishTx() throws Exception
        {
            execute( (WorkerCommand<State,Void>) state ->
            {
                state.tx.success();
                state.tx.close();
                return null;
            } );
        }

        void finishTx() throws Exception
        {
            execute( new WorkerCommand<State, Void>()
            {
                @Override
                public Void doWork( State state )
                {
                    state.tx.success();
                    state.tx.close();
                    return null;
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.ManualAcquireLockTest.Worker.finishTx.execute.new WorkerCommand<State,Void> with state -> {state.tx.success(); in method package finishTx() : void from class org.neo4j.kernel.impl.transaction.ManualAcquireLockTest.Worker


        void setProperty( final Node node, final String key, final Object value ) throws Exception
        {
            execute( state ->
            {
                node.setProperty( key, value );
                return null;
            }, 200, MILLISECONDS );
        }

        void setProperty( final Node node, final String key, final Object value ) throws Exception
        {
            execute( new WorkerCommand<State, Object>()
            {
                @Override
                public Object doWork( State state )
                {
                    node.setProperty( key, value );
                    return null;
                }
            }, 200, MILLISECONDS );
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.ManualAcquireLockTest.Worker.setProperty.execute.new WorkerCommand<State,Object> with state -> {node.setProperty(key,value); in method package setProperty(node Node, key String, value Object) : void from class org.neo4j.kernel.impl.transaction.ManualAcquireLockTest.Worker


    private Runnable createRelationship(
            final EmbeddedGraphDatabase db,
            final Node x,
            final Node y,
            final CountDownLatch latch )
    {
        return () ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                x.createRelationshipTo( y, RelationshipType.withName( "r" ) );
                tx.success();
                latch.await();
                db.getDependencyResolver().resolveDependency( LogRotation.class ).rotateLogFile();
                db.getDependencyResolver().resolveDependency( CheckPointer.class ).forceCheckPoint(
                        new SimpleTriggerInfo( "test" )
                );
            }
            catch ( Exception ignore )
            {
                // We don't care about our transactions failing, as long as we
                // can recover our database to a consistent state.
            }
        };
    }

    private Runnable createRelationship(
            final EmbeddedGraphDatabase db,
            final Node x,
            final Node y,
            final CountDownLatch latch )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                try ( Transaction tx = db.beginTx() )
                {
                    x.createRelationshipTo( y, RelationshipType.withName( "r" ) );
                    tx.success();
                    latch.await();
                    db.getDependencyResolver().resolveDependency( LogRotation.class ).rotateLogFile();
                    db.getDependencyResolver().resolveDependency( CheckPointer.class ).forceCheckPoint(
                            new SimpleTriggerInfo( "test" )
                    );
                }
                catch ( Exception ignore )
                {
                    // We don't care about our transactions failing, as long as we
                    // can recover our database to a consistent state.
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.PartialTransactionFailureIT.createRelationship.new Runnable with () -> {try(Transaction tx=db.beginTx())x.createRelationshipTo(y,RelationshipType.withName("r")); in method private createRelationship(db EmbeddedGraphDatabase, x Node, y Node, latch CountDownLatch) : Runnable from class org.neo4j.kernel.impl.transaction.PartialTransactionFailureIT


    @Test
    public void shouldReadFromSingleChannel() throws Exception
    {
        // GIVEN
        File file = file( 0 );
        final byte byteValue = (byte) 5;
        final short shortValue = (short) 56;
        final int intValue = 32145;
        final long longValue = 5689456895869L;
        final float floatValue = 12.12345f;
        final double doubleValue = 3548.45748D;
        final byte[] byteArrayValue = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
        writeSomeData( file, element ->
        {
            element.put( byteValue );
            element.putShort( shortValue );
            element.putInt( intValue );
            element.putLong( longValue );
            element.putFloat( floatValue );
            element.putDouble( doubleValue );
            element.put( byteArrayValue );
            return true;
        } );

        StoreChannel storeChannel = fileSystemRule.get().open( file, "r" );
        PhysicalLogVersionedStoreChannel versionedStoreChannel =
                new PhysicalLogVersionedStoreChannel( storeChannel, -1 /* ignored */, (byte) -1 /* ignored */ );
        try ( ReadAheadLogChannel channel = new ReadAheadLogChannel( versionedStoreChannel, NO_MORE_CHANNELS, 16 ) )
        {
            // THEN
            assertEquals( byteValue, channel.get() );
            assertEquals( shortValue, channel.getShort() );
            assertEquals( intValue, channel.getInt() );
            assertEquals( longValue, channel.getLong() );
            assertEquals( floatValue, channel.getFloat(), 0.1f );
            assertEquals( doubleValue, channel.getDouble(), 0.1d );

            byte[] bytes = new byte[byteArrayValue.length];
            channel.get( bytes, byteArrayValue.length );
            assertArrayEquals( byteArrayValue, bytes );
        }
    }

    @Test
    public void shouldReadFromSingleChannel() throws Exception
    {
        // GIVEN
        File file = file( 0 );
        final byte byteValue = (byte) 5;
        final short shortValue = (short) 56;
        final int intValue = 32145;
        final long longValue = 5689456895869L;
        final float floatValue = 12.12345f;
        final double doubleValue = 3548.45748D;
        final byte[] byteArrayValue = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
        writeSomeData( file, new Visitor<ByteBuffer, IOException>()
        {
            @Override
            public boolean visit( ByteBuffer element ) throws IOException
            {
                element.put( byteValue );
                element.putShort( shortValue );
                element.putInt( intValue );
                element.putLong( longValue );
                element.putFloat( floatValue );
                element.putDouble( doubleValue );
                element.put( byteArrayValue );
                return true;
            }
        } );

        StoreChannel storeChannel = fileSystemRule.get().open( file, "r" );
        PhysicalLogVersionedStoreChannel versionedStoreChannel =
                new PhysicalLogVersionedStoreChannel( storeChannel, -1 /* ignored */, (byte) -1 /* ignored */ );
        try ( ReadAheadLogChannel channel = new ReadAheadLogChannel( versionedStoreChannel, NO_MORE_CHANNELS, 16 ) )
        {
            // THEN
            assertEquals( byteValue, channel.get() );
            assertEquals( shortValue, channel.getShort() );
            assertEquals( intValue, channel.getInt() );
            assertEquals( longValue, channel.getLong() );
            assertEquals( floatValue, channel.getFloat(), 0.1f );
            assertEquals( doubleValue, channel.getDouble(), 0.1d );

            byte[] bytes = new byte[byteArrayValue.length];
            channel.get( bytes, byteArrayValue.length );
            assertArrayEquals( byteArrayValue, bytes );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.ReadAheadLogChannelTest.shouldReadFromSingleChannel.writeSomeData.new Visitor<ByteBuffer,IOException> with element -> {element.put(byteValue); in method public shouldReadFromSingleChannel() : void from class org.neo4j.kernel.impl.transaction.ReadAheadLogChannelTest


    @Test
    public void shouldReadFromMultipleChannels() throws Exception
    {
        // GIVEN
        writeSomeData( file( 0 ), element ->
        {
            for ( int i = 0; i < 10; i++ )
            {
                element.putLong( i );
            }
            return true;
        } );
        writeSomeData( file( 1 ), element ->
        {
            for ( int i = 10; i < 20; i++ )
            {
                element.putLong( i );
            }
            return true;
        } );

        StoreChannel storeChannel = fileSystemRule.get().open( file( 0 ), "r" );
        PhysicalLogVersionedStoreChannel versionedStoreChannel =
                new PhysicalLogVersionedStoreChannel( storeChannel, -1 /* ignored */, (byte) -1 /* ignored */ );
        try ( ReadAheadLogChannel channel = new ReadAheadLogChannel( versionedStoreChannel, new LogVersionBridge()
        {
            private boolean returned;

            @Override
            public LogVersionedStoreChannel next( LogVersionedStoreChannel channel ) throws IOException
            {
                if ( !returned )
                {
                    returned = true;
                    channel.close();
                    return new PhysicalLogVersionedStoreChannel( fileSystemRule.get().open( file( 1 ), "r" ),
                            -1 /* ignored */, (byte) -1 /* ignored */ );
                }
                return channel;
            }
        }, 10 ) )
        {
            // THEN
            for ( long i = 0; i < 20; i++ )
            {
                assertEquals( i, channel.getLong() );
            }
        }
    }

    @Test
    public void shouldReadFromMultipleChannels() throws Exception
    {
        // GIVEN
        writeSomeData( file( 0 ), new Visitor<ByteBuffer, IOException>()
        {
            @Override
            public boolean visit( ByteBuffer element ) throws IOException
            {
                for ( int i = 0; i < 10; i++ )
                {
                    element.putLong( i );
                }
                return true;
            }
        } );
        writeSomeData( file( 1 ), new Visitor<ByteBuffer, IOException>()
        {
            @Override
            public boolean visit( ByteBuffer element ) throws IOException
            {
                for ( int i = 10; i < 20; i++ )
                {
                    element.putLong( i );
                }
                return true;
            }
        } );

        StoreChannel storeChannel = fileSystemRule.get().open( file( 0 ), "r" );
        PhysicalLogVersionedStoreChannel versionedStoreChannel =
                new PhysicalLogVersionedStoreChannel( storeChannel, -1 /* ignored */, (byte) -1 /* ignored */ );
        try ( ReadAheadLogChannel channel = new ReadAheadLogChannel( versionedStoreChannel, new LogVersionBridge()
        {
            private boolean returned;

            @Override
            public LogVersionedStoreChannel next( LogVersionedStoreChannel channel ) throws IOException
            {
                if ( !returned )
                {
                    returned = true;
                    channel.close();
                    return new PhysicalLogVersionedStoreChannel( fileSystemRule.get().open( file( 1 ), "r" ),
                            -1 /* ignored */, (byte) -1 /* ignored */ );
                }
                return channel;
            }
        }, 10 ) )
        {
            // THEN
            for ( long i = 0; i < 20; i++ )
            {
                assertEquals( i, channel.getLong() );
            }
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.ReadAheadLogChannelTest.shouldReadFromMultipleChannels.writeSomeData.new Visitor<ByteBuffer,IOException> with element -> {for(int i=0; i < 10; i++){element.putLong(i); in method public shouldReadFromMultipleChannels() : void from class org.neo4j.kernel.impl.transaction.ReadAheadLogChannelTest


    @Test
    public void shouldOpenTheNextChannelWhenItExists() throws IOException
    {
        // given
        final StoreChannel newStoreChannel = mock( StoreChannel.class );
        final ReaderLogVersionBridge bridge = new ReaderLogVersionBridge( fs, logFiles );

        when( channel.getVersion() ).thenReturn( version );
        when( channel.getLogFormatVersion() ).thenReturn( CURRENT_LOG_VERSION );
        when( logFiles.getLogFileForVersion( version + 1 ) ).thenReturn( file );
        when( fs.fileExists( file ) ).thenReturn( true );
        when( fs.open( file, "r" ) ).thenReturn( newStoreChannel );
        when( newStoreChannel.read( Matchers.<ByteBuffer>any() ) ).then( invocationOnMock ->
        {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            buffer.putLong( encodeLogVersion( version + 1 ) );
            buffer.putLong( 42 );
            return LOG_HEADER_SIZE;
        } );

        // when
        final LogVersionedStoreChannel result = bridge.next( channel );

        // then
        PhysicalLogVersionedStoreChannel expected =
                new PhysicalLogVersionedStoreChannel( newStoreChannel, version + 1, CURRENT_LOG_VERSION );
        assertEquals( expected, result );
        verify( channel, times( 1 ) ).close();
    }

    @Test
    public void shouldOpenTheNextChannelWhenItExists() throws IOException
    {
        // given
        final StoreChannel newStoreChannel = mock( StoreChannel.class );
        final ReaderLogVersionBridge bridge = new ReaderLogVersionBridge( fs, logFiles );

        when( channel.getVersion() ).thenReturn( version );
        when( channel.getLogFormatVersion() ).thenReturn( CURRENT_LOG_VERSION );
        when( logFiles.getLogFileForVersion( version + 1 ) ).thenReturn( file );
        when( fs.fileExists( file ) ).thenReturn( true );
        when( fs.open( file, "r" ) ).thenReturn( newStoreChannel );
        when( newStoreChannel.read( Matchers.<ByteBuffer>any() ) ).then( new Answer<Integer>()
        {
            @Override
            public Integer answer( InvocationOnMock invocationOnMock ) throws Throwable
            {
                ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
                buffer.putLong( encodeLogVersion( version + 1 ) );
                buffer.putLong( 42 );
                return LOG_HEADER_SIZE;
            }
        } );

        // when
        final LogVersionedStoreChannel result = bridge.next( channel );

        // then
        PhysicalLogVersionedStoreChannel expected =
                new PhysicalLogVersionedStoreChannel( newStoreChannel, version + 1, CURRENT_LOG_VERSION );
        assertEquals( expected, result );
        verify( channel, times( 1 ) ).close();
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.ReaderLogVersionBridgeTest.shouldOpenTheNextChannelWhenItExists.then.new Answer<Integer> with invocationOnMock -> {ByteBuffer buffer=(ByteBuffer)invocationOnMock.getArguments()[0]; in method public shouldOpenTheNextChannelWhenItExists() : void from class org.neo4j.kernel.impl.transaction.ReaderLogVersionBridgeTest


    private WorkerCommand<Void, Object> awaitHead( final IdOrderingQueue queue, final long id )
    {
        return state ->
        {
            queue.waitFor( id );
            return null;
        };
    }

    private WorkerCommand<Void, Object> awaitHead( final IdOrderingQueue queue, final long id )
    {
        return new WorkerCommand<Void, Object>()
        {
            @Override
            public Object doWork( Void state ) throws Exception
            {
                queue.waitFor( id );
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.SynchronizedArrayIdOrderingQueueTest.awaitHead.new WorkerCommand<Void,Object> with state -> {queue.waitFor(id); in method private awaitHead(queue IdOrderingQueue, id long) : WorkerCommand<Void,Object> from class org.neo4j.kernel.impl.transaction.SynchronizedArrayIdOrderingQueueTest


    private Runnable createForceAfterAppendRunnable( final BatchingTransactionAppender appender )
    {
        return () ->
        {
            try
            {
                appender.forceAfterAppend( logAppendEvent );
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
        };
    }

    private Runnable createForceAfterAppendRunnable( final BatchingTransactionAppender appender )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    appender.forceAfterAppend( logAppendEvent );
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.BatchingTransactionAppenderConcurrencyTest.createForceAfterAppendRunnable.new Runnable with () -> {tryappender.forceAfterAppend(logAppendEvent); in method private createForceAfterAppendRunnable(appender BatchingTransactionAppender) : Runnable from class org.neo4j.kernel.impl.transaction.log.BatchingTransactionAppenderConcurrencyTest


    @Test
    public void shouldNotCallTransactionClosedOnFailedForceLogToDisk() throws Exception
    {
        // GIVEN
        long txId = 3;
        String failureMessage = "Forces a failure";
        FlushablePositionAwareChannel channel = spy( new InMemoryClosableChannel() );
        IOException failure = new IOException( failureMessage );
        final Flushable flushable = mock( Flushable.class );
        doAnswer( invocation ->
        {
            invocation.callRealMethod();
            return flushable;
        } ).when( channel ).prepareForFlush();
        doThrow( failure ).when( flushable ).flush();
        LogFile logFile = mock( LogFile.class );
        when( logFile.getWriter() ).thenReturn( channel );
        TransactionMetadataCache metadataCache = new TransactionMetadataCache( 10 );
        TransactionIdStore transactionIdStore = mock( TransactionIdStore.class );
        when( transactionIdStore.nextCommittingTransactionId() ).thenReturn( txId );
        Mockito.reset( databaseHealth );
        TransactionAppender appender = life.add( new BatchingTransactionAppender( logFile, NO_ROTATION,
                metadataCache, transactionIdStore, BYPASS, databaseHealth ) );

        // WHEN
        TransactionRepresentation transaction = mock( TransactionRepresentation.class );
        when( transaction.additionalHeader() ).thenReturn( new byte[0] );
        try
        {
            appender.append( new TransactionToApply( transaction ), logAppendEvent );
            fail( "Expected append to fail. Something is wrong with the test itself" );
        }
        catch ( IOException e )
        {
            // THEN
            assertSame( failure, e );
            verify( transactionIdStore, times( 1 ) ).nextCommittingTransactionId();
            verify( transactionIdStore, times( 0 ) ).transactionClosed( eq( txId ), anyLong(), anyLong() );
            verify( databaseHealth ).panic( failure );
        }
    }

    @Test
    public void shouldNotCallTransactionClosedOnFailedForceLogToDisk() throws Exception
    {
        // GIVEN
        long txId = 3;
        String failureMessage = "Forces a failure";
        FlushablePositionAwareChannel channel = spy( new InMemoryClosableChannel() );
        IOException failure = new IOException( failureMessage );
        final Flushable flushable = mock( Flushable.class );
        doAnswer( new Answer<Flushable>()
        {
            @Override
            public Flushable answer( InvocationOnMock invocation ) throws Throwable
            {
                invocation.callRealMethod();
                return flushable;
            }
        } ).when( channel ).prepareForFlush();
        doThrow( failure ).when( flushable ).flush();
        LogFile logFile = mock( LogFile.class );
        when( logFile.getWriter() ).thenReturn( channel );
        TransactionMetadataCache metadataCache = new TransactionMetadataCache( 10 );
        TransactionIdStore transactionIdStore = mock( TransactionIdStore.class );
        when( transactionIdStore.nextCommittingTransactionId() ).thenReturn( txId );
        Mockito.reset( databaseHealth );
        TransactionAppender appender = life.add( new BatchingTransactionAppender( logFile, NO_ROTATION,
                metadataCache, transactionIdStore, BYPASS, databaseHealth ) );

        // WHEN
        TransactionRepresentation transaction = mock( TransactionRepresentation.class );
        when( transaction.additionalHeader() ).thenReturn( new byte[0] );
        try
        {
            appender.append( new TransactionToApply( transaction ), logAppendEvent );
            fail( "Expected append to fail. Something is wrong with the test itself" );
        }
        catch ( IOException e )
        {
            // THEN
            assertSame( failure, e );
            verify( transactionIdStore, times( 1 ) ).nextCommittingTransactionId();
            verify( transactionIdStore, times( 0 ) ).transactionClosed( eq( txId ), anyLong(), anyLong() );
            verify( databaseHealth ).panic( failure );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.BatchingTransactionAppenderTest.shouldNotCallTransactionClosedOnFailedForceLogToDisk.prepareForFlush.when.doAnswer.new Answer<Flushable> with invocation -> {invocation.callRealMethod(); in method public shouldNotCallTransactionClosedOnFailedForceLogToDisk() : void from class org.neo4j.kernel.impl.transaction.log.BatchingTransactionAppenderTest


    @Test
    public void shouldKeepTransactionsIntactWhenConcurrentlyRotationAndAppending() throws Throwable
    {
        // GIVEN
        PhysicalLogFiles logFiles = new PhysicalLogFiles( directory.directory().getAbsoluteFile(), fileSystemRule.get() );
        long rotationThreshold = mebiBytes( 1 );
        LogVersionRepository logVersionRepository = new DeadSimpleLogVersionRepository( 0 );
        final AtomicBoolean end = new AtomicBoolean();
        AllTheMonitoring monitoring = new AllTheMonitoring( end, 100 );
        TransactionIdStore txIdStore = new DeadSimpleTransactionIdStore();
        TransactionMetadataCache metadataCache = new TransactionMetadataCache( 100 );
        LogHeaderCache logHeaderCache = new LogHeaderCache( 10 );
        LogFile logFile = life.add( new PhysicalLogFile( fileSystemRule.get(), logFiles, rotationThreshold,
                txIdStore::getLastCommittedTransactionId, logVersionRepository, monitoring, logHeaderCache ) );
        monitoring.setLogFile( logFile );
        DatabaseHealth health = new DatabaseHealth( mock( DatabasePanicEventGenerator.class ), NullLog.getInstance() );
        LogRotation rotation = new LogRotationImpl( monitoring, logFile, health );
        final TransactionAppender appender = life.add( new BatchingTransactionAppender( logFile, rotation, metadataCache,
                txIdStore, BYPASS, health ) );

        // WHEN
        Race race = new Race();
        for ( int i = 0; i < 10; i++ )
        {
            race.addContestant( () ->
            {
                while ( !end.get() )
                {
                    try
                    {
                        appender.append( new TransactionToApply( sillyTransaction( 1_000 ) ), NULL );
                    }
                    catch ( Exception e )
                    {
                        e.printStackTrace( System.out );
                        end.set( true );
                        fail( e.getMessage() );
                    }
                }
            } );
        }
        race.addContestant( endAfterMax( 10, SECONDS, end ) );
        race.go();

        // THEN
        assertTrue( monitoring.numberOfRotations() > 0 );
    }

    @Test
    public void shouldKeepTransactionsIntactWhenConcurrentlyRotationAndAppending() throws Throwable
    {
        // GIVEN
        PhysicalLogFiles logFiles = new PhysicalLogFiles( directory.directory().getAbsoluteFile(), fileSystemRule.get() );
        long rotationThreshold = mebiBytes( 1 );
        LogVersionRepository logVersionRepository = new DeadSimpleLogVersionRepository( 0 );
        final AtomicBoolean end = new AtomicBoolean();
        AllTheMonitoring monitoring = new AllTheMonitoring( end, 100 );
        TransactionIdStore txIdStore = new DeadSimpleTransactionIdStore();
        TransactionMetadataCache metadataCache = new TransactionMetadataCache( 100 );
        LogHeaderCache logHeaderCache = new LogHeaderCache( 10 );
        LogFile logFile = life.add( new PhysicalLogFile( fileSystemRule.get(), logFiles, rotationThreshold,
                () -> txIdStore.getLastCommittedTransactionId(), logVersionRepository, monitoring, logHeaderCache ) );
        monitoring.setLogFile( logFile );
        DatabaseHealth health = new DatabaseHealth( mock( DatabasePanicEventGenerator.class ), NullLog.getInstance() );
        LogRotation rotation = new LogRotationImpl( monitoring, logFile, health );
        final TransactionAppender appender = life.add( new BatchingTransactionAppender( logFile, rotation, metadataCache,
                txIdStore, BYPASS, health ) );

        // WHEN
        Race race = new Race();
        for ( int i = 0; i < 10; i++ )
        {
            race.addContestant( new Runnable()
            {
                @Override
                public void run()
                {
                    while ( !end.get() )
                    {
                        try
                        {
                            appender.append( new TransactionToApply( sillyTransaction( 1_000 ) ), NULL );
                        }
                        catch ( Exception e )
                        {
                            e.printStackTrace( System.out );
                            end.set( true );
                            fail( e.getMessage() );
                        }
                    }
                }
            } );
        }
        race.addContestant( endAfterMax( 10, SECONDS, end ) );
        race.go();

        // THEN
        assertTrue( monitoring.numberOfRotations() > 0 );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.TransactionLogAppendAndRotateIT.shouldKeepTransactionsIntactWhenConcurrentlyRotationAndAppending.addContestant.new Runnable with () -> {while(!end.get()){tryappender.append(new TransactionToApply(sillyTransaction(1_000)),NULL); in method public shouldKeepTransactionsIntactWhenConcurrentlyRotationAndAppending() : void from class org.neo4j.kernel.impl.transaction.log.TransactionLogAppendAndRotateIT


    private Runnable endAfterMax( final int time, final TimeUnit unit, final AtomicBoolean end )
    {
        return () ->
        {
            long endTime = currentTimeMillis() + unit.toMillis( time );
            while ( currentTimeMillis() < endTime && !end.get() )
            {
                parkNanos( MILLISECONDS.toNanos( 50 ) );
            }
            end.set( true );
        };
    }

    private Runnable endAfterMax( final int time, final TimeUnit unit, final AtomicBoolean end )
    {
        return new Runnable()
        {

            @Override
            public void run()
            {
                long endTime = currentTimeMillis() + unit.toMillis( time );
                while ( currentTimeMillis() < endTime && !end.get() )
                {
                    parkNanos( MILLISECONDS.toNanos( 50 ) );
                }
                end.set( true );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.TransactionLogAppendAndRotateIT.endAfterMax.new Runnable with () -> {long endTime=currentTimeMillis() + unit.toMillis(time); in method private endAfterMax(time int, unit TimeUnit, end AtomicBoolean) : Runnable from class org.neo4j.kernel.impl.transaction.log.TransactionLogAppendAndRotateIT


    @Test
    public void shouldWaitOnStopUntilTheRunningCheckpointIsDone() throws Throwable
    {
        // given
        final AtomicReference<Throwable> ex = new AtomicReference<>();
        final AtomicBoolean stoppedCompleted = new AtomicBoolean();
        final DoubleLatch checkPointerLatch = new DoubleLatch( 1 );
        CheckPointer checkPointer = new CheckPointer()
        {
            @Override
            public long checkPointIfNeeded( TriggerInfo triggerInfo ) throws IOException
            {
                checkPointerLatch.startAndWaitForAllToStart();
                checkPointerLatch.waitForAllToFinish();
                return 42;
            }

            @Override
            public long tryCheckPoint( TriggerInfo triggerInfo ) throws IOException
            {
                throw new RuntimeException( "this should have not been called" );
            }

            @Override
            public long forceCheckPoint( TriggerInfo triggerInfo ) throws IOException
            {
                throw new RuntimeException( "this should have not been called" );
            }

            @Override
            public long lastCheckPointedTransactionId()
            {
                return 42;
            }
        };

        final CheckPointScheduler scheduler = new CheckPointScheduler( checkPointer, ioLimiter, jobScheduler, 20L, health );

        // when
        scheduler.start();

        Thread runCheckPointer = new Thread( jobScheduler::runJob );
        runCheckPointer.start();

        checkPointerLatch.waitForAllToStart();

        Thread stopper = new Thread( () ->
        {
            try
            {
                scheduler.stop();
                stoppedCompleted.set( true );
            }
            catch ( Throwable throwable )
            {
                ex.set( throwable );
            }
        } );

        stopper.start();

        Thread.sleep( 10 );

        // then
        assertFalse( stoppedCompleted.get() );

        checkPointerLatch.finish();
        runCheckPointer.join();

        Thread.sleep( 150 );

        assertTrue( stoppedCompleted.get() );
        stopper.join(); // just in case

        assertNull( ex.get() );
    }

    @Test
    public void shouldWaitOnStopUntilTheRunningCheckpointIsDone() throws Throwable
    {
        // given
        final AtomicReference<Throwable> ex = new AtomicReference<>();
        final AtomicBoolean stoppedCompleted = new AtomicBoolean();
        final DoubleLatch checkPointerLatch = new DoubleLatch( 1 );
        CheckPointer checkPointer = new CheckPointer()
        {
            @Override
            public long checkPointIfNeeded( TriggerInfo triggerInfo ) throws IOException
            {
                checkPointerLatch.startAndWaitForAllToStart();
                checkPointerLatch.waitForAllToFinish();
                return 42;
            }

            @Override
            public long tryCheckPoint( TriggerInfo triggerInfo ) throws IOException
            {
                throw new RuntimeException( "this should have not been called" );
            }

            @Override
            public long forceCheckPoint( TriggerInfo triggerInfo ) throws IOException
            {
                throw new RuntimeException( "this should have not been called" );
            }

            @Override
            public long lastCheckPointedTransactionId()
            {
                return 42;
            }
        };

        final CheckPointScheduler scheduler = new CheckPointScheduler( checkPointer, ioLimiter, jobScheduler, 20L, health );

        // when
        scheduler.start();

        Thread runCheckPointer = new Thread()
        {
            @Override
            public void run()
            {
                jobScheduler.runJob();
            }
        };
        runCheckPointer.start();

        checkPointerLatch.waitForAllToStart();

        Thread stopper = new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    scheduler.stop();
                    stoppedCompleted.set( true );
                }
                catch ( Throwable throwable )
                {
                    ex.set( throwable );
                }
            }
        };

        stopper.start();

        Thread.sleep( 10 );

        // then
        assertFalse( stoppedCompleted.get() );

        checkPointerLatch.finish();
        runCheckPointer.join();

        Thread.sleep( 150 );

        assertTrue( stoppedCompleted.get() );
        stopper.join(); // just in case

        assertNull( ex.get() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointSchedulerTest.shouldWaitOnStopUntilTheRunningCheckpointIsDone.stopper.new Thread with () -> {tryscheduler.stop(); in method public shouldWaitOnStopUntilTheRunningCheckpointIsDone() : void from class org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointSchedulerTest


    @Test
    public void forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() throws Throwable
    {
        // Given
        Lock lock = new ReentrantLock();
        final Lock spyLock = spy( lock );

        doAnswer( invocation ->
        {
            verify( appender ).checkPoint( any( LogPosition.class ), any( LogCheckPointEvent.class ) );
            reset( appender );
            invocation.callRealMethod();
            return null;
        } ).when( spyLock ).unlock();

        final CheckPointerImpl checkPointing = checkPointer( mutex( spyLock ) );
        mockTxIdStore();

        final CountDownLatch startSignal = new CountDownLatch( 2 );
        final CountDownLatch completed = new CountDownLatch( 2 );

        checkPointing.start();

        Thread checkPointerThread = new CheckPointerThread( checkPointing, startSignal, completed );

        Thread forceCheckPointThread = new Thread( () ->
        {
            try
            {
                startSignal.countDown();
                startSignal.await();
                checkPointing.forceCheckPoint( INFO );

                completed.countDown();
            }
            catch ( Throwable e )
            {
                throw new RuntimeException( e );
            }
        } );

        // when
        checkPointerThread.start();
        forceCheckPointThread.start();

        completed.await();

        verify( spyLock, times( 2 ) ).lock();
        verify( spyLock, times( 2 ) ).unlock();
    }

    @Test
    public void forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() throws Throwable
    {
        // Given
        Lock lock = new ReentrantLock();
        final Lock spyLock = spy( lock );

        doAnswer( invocation ->
        {
            verify( appender ).checkPoint( any( LogPosition.class ), any( LogCheckPointEvent.class ) );
            reset( appender );
            invocation.callRealMethod();
            return null;
        } ).when( spyLock ).unlock();

        final CheckPointerImpl checkPointing = checkPointer( mutex( spyLock ) );
        mockTxIdStore();

        final CountDownLatch startSignal = new CountDownLatch( 2 );
        final CountDownLatch completed = new CountDownLatch( 2 );

        checkPointing.start();

        Thread checkPointerThread = new CheckPointerThread( checkPointing, startSignal, completed );

        Thread forceCheckPointThread = new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    startSignal.countDown();
                    startSignal.await();
                    checkPointing.forceCheckPoint( INFO );

                    completed.countDown();
                }
                catch ( Throwable e )
                {
                    throw new RuntimeException( e );
                }
            }
        };

        // when
        checkPointerThread.start();
        forceCheckPointThread.start();

        completed.await();

        verify( spyLock, times( 2 ) ).lock();
        verify( spyLock, times( 2 ) ).unlock();
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointerImplTest.forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning.forceCheckPointThread.new Thread with () -> {trystartSignal.countDown(); in method public forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() : void from class org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointerImplTest


    @Test
    public void shouldPropagateStoreCopyActionFailureToOtherStoreCopyRequests() throws Exception
    {
        // GIVEN
        Barrier.Control barrier = new Barrier.Control();
        IOException controlledFailure = new IOException( "My own fault" );
        AtomicReference<Future<Object>> secondRequest = new AtomicReference<>();
        ThrowingAction<IOException> controllableAndFailingAction = () ->
        {
            // Now that we know we're first, start the second request...
            secondRequest.set( t3.execute( state -> mutex.storeCopy( ASSERT_NOT_CALLED ) ) );
            // ...and wait for it to reach its destination
            barrier.awaitUninterruptibly();
            try
            {
                // OK, second request has made progress into the request, so we can now produce our failure
                throw controlledFailure;
            }
            finally
            {
                barrier.release();
            }
        };

        Future<Object> firstRequest = t2.execute( state -> mutex.storeCopy( controllableAndFailingAction ) );
        while ( secondRequest.get() == null )
        {
            parkARandomWhile();
        }
        t3.get().waitUntilWaiting( details -> details.isAt( StoreCopyCheckPointMutex.class,
                "waitForFirstStoreCopyActionToComplete" ) );

        // WHEN
        barrier.reached();

        // THEN
        try
        {
            firstRequest.get();
        }
        catch ( ExecutionException e )
        {
            assertSame( controlledFailure, e.getCause() );
        }
        try
        {
            secondRequest.get().get();
        }
        catch ( ExecutionException e )
        {
            Throwable cooperativeActionFailure = e.getCause();
            assertThat( cooperativeActionFailure.getMessage(), containsString( "Co-operative" ) );
            assertSame( controlledFailure, cooperativeActionFailure.getCause() );
        }

        // WHEN afterwards trying another store-copy
        CountingAction action = new CountingAction();
        try ( Resource lock = mutex.storeCopy( action ) )
        {
            // THEN
            assertEquals( 1, action.count() );
        }
    }

    @Test
    public void shouldPropagateStoreCopyActionFailureToOtherStoreCopyRequests() throws Exception
    {
        // GIVEN
        Barrier.Control barrier = new Barrier.Control();
        IOException controlledFailure = new IOException( "My own fault" );
        AtomicReference<Future<Object>> secondRequest = new AtomicReference<>();
        ThrowingAction<IOException> controllableAndFailingAction = new ThrowingAction<IOException>()
        {
            @Override
            public void apply() throws IOException
            {
                // Now that we know we're first, start the second request...
                secondRequest.set( t3.execute( state -> mutex.storeCopy( ASSERT_NOT_CALLED ) ) );
                // ...and wait for it to reach its destination
                barrier.awaitUninterruptibly();
                try
                {
                    // OK, second request has made progress into the request, so we can now produce our failure
                    throw controlledFailure;
                }
                finally
                {
                    barrier.release();
                }
            }
        };

        Future<Object> firstRequest = t2.execute( state -> mutex.storeCopy( controllableAndFailingAction ) );
        while ( secondRequest.get() == null )
        {
            parkARandomWhile();
        }
        t3.get().waitUntilWaiting( details -> details.isAt( StoreCopyCheckPointMutex.class,
                "waitForFirstStoreCopyActionToComplete" ) );

        // WHEN
        barrier.reached();

        // THEN
        try
        {
            firstRequest.get();
        }
        catch ( ExecutionException e )
        {
            assertSame( controlledFailure, e.getCause() );
        }
        try
        {
            secondRequest.get().get();
        }
        catch ( ExecutionException e )
        {
            Throwable cooperativeActionFailure = e.getCause();
            assertThat( cooperativeActionFailure.getMessage(), containsString( "Co-operative" ) );
            assertSame( controlledFailure, cooperativeActionFailure.getCause() );
        }

        // WHEN afterwards trying another store-copy
        CountingAction action = new CountingAction();
        try ( Resource lock = mutex.storeCopy( action ) )
        {
            // THEN
            assertEquals( 1, action.count() );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.checkpoint.StoreCopyCheckPointMutexTest.shouldPropagateStoreCopyActionFailureToOtherStoreCopyRequests.controllableAndFailingAction.new ThrowingAction<IOException> with () -> {secondRequest.set(t3.execute(state -> mutex.storeCopy(ASSERT_NOT_CALLED))); in method public shouldPropagateStoreCopyActionFailureToOtherStoreCopyRequests() : void from class org.neo4j.kernel.impl.transaction.log.checkpoint.StoreCopyCheckPointMutexTest


    @Test
    public void shouldReadALogHeaderFromAByteChannel() throws IOException
    {
        // given
        final ByteBuffer buffer = ByteBuffer.allocate( LOG_HEADER_SIZE );
        final ReadableByteChannel channel = mock( ReadableByteChannel.class );

        when( channel.read( buffer ) ).thenAnswer( invocation ->
        {
            buffer.putLong( encodeLogVersion( expectedLogVersion ) );
            buffer.putLong( expectedTxId );
            return 8 + 8;
        } );

        // when
        final LogHeader result = readLogHeader( buffer, channel, true, null );

        // then
        assertEquals( new LogHeader( CURRENT_LOG_VERSION, expectedLogVersion, expectedTxId ), result );
    }

    @Test
    public void shouldReadALogHeaderFromAByteChannel() throws IOException
    {
        // given
        final ByteBuffer buffer = ByteBuffer.allocate( LOG_HEADER_SIZE );
        final ReadableByteChannel channel = mock( ReadableByteChannel.class );

        when( channel.read( buffer ) ).thenAnswer( new Answer<Integer>()
        {
            @Override
            public Integer answer( InvocationOnMock invocation ) throws Throwable
            {
                buffer.putLong( encodeLogVersion( expectedLogVersion ) );
                buffer.putLong( expectedTxId );
                return 8 + 8;
            }
        } );

        // when
        final LogHeader result = readLogHeader( buffer, channel, true, null );

        // then
        assertEquals( new LogHeader( CURRENT_LOG_VERSION, expectedLogVersion, expectedTxId ), result );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.entry.LogHeaderReaderTest.shouldReadALogHeaderFromAByteChannel.thenAnswer.new Answer<Integer> with invocation -> {buffer.putLong(encodeLogVersion(expectedLogVersion)); in method public shouldReadALogHeaderFromAByteChannel() : void from class org.neo4j.kernel.impl.transaction.log.entry.LogHeaderReaderTest


    private int transactionCount() throws IOException
    {
        return aggregateLogData( version ->
        {
            int counter = 0;
            LogVersionBridge bridge = channel -> channel;
            LogVersionedStoreChannel versionedStoreChannel =
                    PhysicalLogFile.openForVersion( files, fs, version, false );
            try ( ReadableLogChannel channel =
                          new ReadAheadLogChannel( versionedStoreChannel, bridge, 1000 ) )
            {
                try ( PhysicalTransactionCursor<ReadableLogChannel> physicalTransactionCursor =
                        new PhysicalTransactionCursor<>( channel, new VersionAwareLogEntryReader<>() ) )
                {
                    while ( physicalTransactionCursor.next() )
                    {
                        counter++;
                    }
                }
            }
            return counter;
        } );
    }

    private int transactionCount() throws IOException
    {
        return aggregateLogData( new Extractor()
        {
            @Override
            public int extract( long version ) throws IOException
            {
                int counter = 0;
                LogVersionBridge bridge = new LogVersionBridge()
                {
                    @Override
                    public LogVersionedStoreChannel next( LogVersionedStoreChannel channel ) throws IOException
                    {
                        return channel;
                    }
                };
                StoreChannel storeChannel = fs.open( files.getLogFileForVersion( version ), "r" );
                LogVersionedStoreChannel versionedStoreChannel =
                        PhysicalLogFile.openForVersion( files, fs, version, false );
                try ( ReadableLogChannel channel =
                              new ReadAheadLogChannel( versionedStoreChannel, bridge, 1000 ) )
                {
                    try ( PhysicalTransactionCursor<ReadableLogChannel> physicalTransactionCursor =
                            new PhysicalTransactionCursor<>( channel, new VersionAwareLogEntryReader<>() ) )
                    {
                        while ( physicalTransactionCursor.next() )
                        {
                            counter++;
                        }
                    }
                }
                return counter;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.pruning.TestLogPruning.transactionCount.aggregateLogData.new Extractor with version -> {int counter=0; in method private transactionCount() : int from class org.neo4j.kernel.impl.transaction.log.pruning.TestLogPruning


    @Test
    public void twoDynamicRecordsShouldShrinkToOneWhenRemoving() throws Exception
    {
        // GIVEN
        // will occupy 61B of data, i.e. just two dynamic records
        NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, oneByteLongs( 57 ) );
        Collection<DynamicRecord> initialRecords = node.getDynamicLabelRecords();
        NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node );

        // WHEN
        List<DynamicRecord> changedDynamicRecords = Iterables.addToCollection(
                nodeLabels.remove( 255 /*Initial labels go from 255 and down to 255-58*/, nodeStore ),
                new ArrayList<>() );

        // THEN
        assertEquals( initialRecords, changedDynamicRecords );
        assertTrue( changedDynamicRecords.get( 0 ).inUse() );
        assertFalse( changedDynamicRecords.get( 1 ).inUse() );
    }

    @Test
    public void twoDynamicRecordsShouldShrinkToOneWhenRemoving() throws Exception
    {
        // GIVEN
        // will occupy 61B of data, i.e. just two dynamic records
        NodeRecord node = nodeRecordWithDynamicLabels( nodeStore, oneByteLongs( 57 ) );
        Collection<DynamicRecord> initialRecords = node.getDynamicLabelRecords();
        NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node );

        // WHEN
        List<DynamicRecord> changedDynamicRecords = Iterables.addToCollection(
                nodeLabels.remove( 255 /*Initial labels go from 255 and down to 255-58*/, nodeStore ),
                new ArrayList<DynamicRecord>() );

        // THEN
        assertEquals( initialRecords, changedDynamicRecords );
        assertTrue( changedDynamicRecords.get( 0 ).inUse() );
        assertFalse( changedDynamicRecords.get( 1 ).inUse() );
    }

Replace Generic With Diamond ArrayList<DynamicRecord> with ArrayList<> in method public twoDynamicRecordsShouldShrinkToOneWhenRemoving() : void from class org.neo4j.kernel.impl.transaction.state.NodeLabelsFieldTest


    @Test
    public void twoDynamicRecordsShouldShrinkToOneWhenRemovingWithoutChangingItsOwner() throws Exception
    {
        // GIVEN
        // will occupy 61B of data, i.e. just two dynamic records
        Long nodeId = 42L;
        NodeRecord node = nodeRecordWithDynamicLabels( nodeId, nodeStore, oneByteLongs( 57 ) );
        NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node );

        List<DynamicRecord> changedDynamicRecords = Iterables.addToCollection(
                nodeLabels.remove( 255 /*Initial labels go from 255 and down to 255-58*/, nodeStore ),
                new ArrayList<>() );

        // WHEN
        Pair<Long,long[]> changedPair = DynamicNodeLabels.getDynamicLabelsArrayAndOwner( changedDynamicRecords,
                nodeStore.getDynamicLabelStore() );

        // THEN
        assertEquals( nodeId,  changedPair.first() );
    }

    @Test
    public void twoDynamicRecordsShouldShrinkToOneWhenRemovingWithoutChangingItsOwner() throws Exception
    {
        // GIVEN
        // will occupy 61B of data, i.e. just two dynamic records
        Long nodeId = 42L;
        NodeRecord node = nodeRecordWithDynamicLabels( nodeId, nodeStore, oneByteLongs( 57 ) );
        NodeLabels nodeLabels = NodeLabelsField.parseLabelsField( node );

        List<DynamicRecord> changedDynamicRecords = Iterables.addToCollection(
                nodeLabels.remove( 255 /*Initial labels go from 255 and down to 255-58*/, nodeStore ),
                new ArrayList<DynamicRecord>() );

        // WHEN
        Pair<Long,long[]> changedPair = DynamicNodeLabels.getDynamicLabelsArrayAndOwner( changedDynamicRecords,
                nodeStore.getDynamicLabelStore() );

        // THEN
        assertEquals( nodeId,  changedPair.first() );
    }

Replace Generic With Diamond ArrayList<DynamicRecord> with ArrayList<> in method public twoDynamicRecordsShouldShrinkToOneWhenRemovingWithoutChangingItsOwner() : void from class org.neo4j.kernel.impl.transaction.state.NodeLabelsFieldTest


    private LinkedQueuePool<Object> getLinkedQueuePool( StatefulMonitor stateMonitor, FakeClock clock, int minSize )
    {
        return new LinkedQueuePool<>( minSize, Object::new,
            new LinkedQueuePool.CheckStrategy.TimeoutCheckStrategy( 100, clock ), stateMonitor );
    }

    private LinkedQueuePool<Object> getLinkedQueuePool( StatefulMonitor stateMonitor, FakeClock clock, int minSize )
    {
        return new LinkedQueuePool<Object>( minSize,
                new LinkedQueuePool.CheckStrategy.TimeoutCheckStrategy( 100, clock ), stateMonitor )
        {
            @Override
            protected Object create()
            {
                return new Object();
            }
        };
    }

Replace Generic With Diamond LinkedQueuePool<Object> with LinkedQueuePool<> in method private getLinkedQueuePool(stateMonitor StatefulMonitor, clock FakeClock, minSize int) : LinkedQueuePool<Object> from class org.neo4j.collection.pool.LinkedQueuePoolTest


    @Override
    public RelationshipType getRelationshipTypeById( int type )
    {
        try ( Statement statement = statement() )
        {
            return RelationshipType.withName( statement.readOperations().relationshipTypeGetName( type ) );
        }
        catch ( RelationshipTypeIdNotFoundKernelException e )
        {
            throw new IllegalStateException( "Kernel API returned non-existent relationship type: " + type );
        }
    }

    @Override
    public RelationshipType getRelationshipTypeById( int type )
    {
        try
        {
            return RelationshipType.withName( statement().readOperations().relationshipTypeGetName( type ) );
        }
        catch ( RelationshipTypeIdNotFoundKernelException e )
        {
            throw new IllegalStateException( "Kernel API returned non-existent relationship type: " + type );
        }
    }

Try With Resources try(Statement statement=statement()) in method public getRelationshipTypeById(type int) : RelationshipType from class org.neo4j.kernel.impl.coreapi.StandardRelationshipActions


    @Test
    public void shouldRunWithDelay() throws Throwable
    {
        // Given
        life.start();

        final AtomicLong runTime = new AtomicLong();
        final CountDownLatch latch = new CountDownLatch( 1 );

        long time = System.nanoTime();

        scheduler.schedule( new JobScheduler.Group( "group" ), () ->
        {
            runTime.set( System.nanoTime() );
            latch.countDown();
        }, 100, TimeUnit.MILLISECONDS );

        latch.await();

        assertTrue( time + TimeUnit.MILLISECONDS.toNanos( 100 ) <= runTime.get() );
    }

    @Test
    public void shouldRunWithDelay() throws Throwable
    {
        // Given
        life.start();

        final AtomicLong runTime = new AtomicLong();
        final CountDownLatch latch = new CountDownLatch( 1 );

        long time = System.nanoTime();

        scheduler.schedule( new JobScheduler.Group( "group", POOLED ), new Runnable()
        {
            @Override
            public void run()
            {
                runTime.set( System.nanoTime() );
                latch.countDown();
            }
        }, 100, TimeUnit.MILLISECONDS );

        latch.await();

        assertTrue( time + TimeUnit.MILLISECONDS.toNanos( 100 ) <= runTime.get() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.util.Neo4jJobSchedulerTest.shouldRunWithDelay.schedule.new Runnable with () -> {runTime.set(System.nanoTime()); in method public shouldRunWithDelay() : void from class org.neo4j.kernel.impl.util.Neo4jJobSchedulerTest


    private Runnable readContestant( final ReadContestantActions action, final long entityId,
            final HighlyAvailableGraphDatabase slave, final AtomicBoolean end )
    {
        return () ->
        {
            while ( !end.get() )
            {
                try ( Transaction tx = slave.beginTx() )
                {
                    for ( int i = 0; i < 10; i++ )
                    {
                        action.verifyProperties( slave, entityId );
                    }

                    tx.success();
                }
                catch ( TransactionTerminatedException | TransientTransactionFailureException ignored )
                {
                }
            }
        };
    }

    private Runnable readContestant( final ReadContestantActions action, final long entityId,
            final HighlyAvailableGraphDatabase slave, final AtomicBoolean end )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                while ( !end.get() )
                {
                    try ( Transaction tx = slave.beginTx() )
                    {
                        for ( int i = 0; i < 10; i++ )
                        {
                            action.verifyProperties( slave, entityId );
                        }

                        tx.success();
                    }
                    catch ( TransactionTerminatedException | TransientTransactionFailureException ignored )
                    {
                    }
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.TerminationOfSlavesDuringPullUpdatesTest.readContestant.new Runnable with () -> {while(!end.get()){try(Transaction tx=slave.beginTx())for(int i=0; i < 10; i++){action.verifyProperties(slave,entityId); in method private readContestant(action ReadContestantActions, entityId long, slave HighlyAvailableGraphDatabase, end AtomicBoolean) : Runnable from class org.neo4j.kernel.ha.cluster.TerminationOfSlavesDuringPullUpdatesTest


    private Runnable pullUpdatesContestant( final HighlyAvailableGraphDatabase slave, final AtomicBoolean end )
    {
        return () ->
        {
            try
            {
                Random rnd = new Random();
                Thread.sleep( rnd.nextInt( 100 ) );
                slave.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();
            }
            catch ( InterruptedException e )
            {
                throw new RuntimeException( e );
            }
            finally
            {
                end.set( true );
            }

        };
    }

    private Runnable pullUpdatesContestant( final HighlyAvailableGraphDatabase slave, final AtomicBoolean end )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    Random rnd = new Random();
                    Thread.sleep( rnd.nextInt( 100 ) );
                    slave.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();
                }
                catch ( InterruptedException e )
                {
                    throw new RuntimeException( e );
                }
                finally
                {
                    end.set( true );
                }

            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.TerminationOfSlavesDuringPullUpdatesTest.pullUpdatesContestant.new Runnable with () -> {tryRandom rnd=new Random(); in method private pullUpdatesContestant(slave HighlyAvailableGraphDatabase, end AtomicBoolean) : Runnable from class org.neo4j.kernel.ha.cluster.TerminationOfSlavesDuringPullUpdatesTest


    @Test
    public void shouldOverrideSourceWithSystemProperty() throws Exception
    {
        withSystemProperty( UdcSettings.udc_source.name(), "overridden", () ->
        {
            graphdb = createDatabase( path.directory( "db-with-property" ), config );
            assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO );
            String source = handler.getQueryMap().get( SOURCE );
            assertEquals( "overridden", source );
            return null;
        } );
    }

    @Test
    public void shouldOverrideSourceWithSystemProperty() throws Exception
    {
        withSystemProperty( UdcSettings.udc_source.name(), "overridden", new Callable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                graphdb = createDatabase( config );
                assertGotSuccessWithRetry( IS_GREATER_THAN_ZERO );
                String source = handler.getQueryMap().get( SOURCE );
                assertEquals( "overridden", source );
                return null;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.ext.udc.impl.UdcExtensionImplTest.shouldOverrideSourceWithSystemProperty.withSystemProperty.new Callable<Void> with () -> {graphdb=createDatabase(path.directory("db-with-property"),config); in method public shouldOverrideSourceWithSystemProperty() : void from class org.neo4j.ext.udc.impl.UdcExtensionImplTest


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

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

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


    @Override
    public void visitDeletedRelationship( long id )
    {
        try ( Cursor<RelationshipItem> cursor = storeLayer.relationshipCursor( statement, id, null ) )
        {
            if ( !cursor.next() )
            {
                throw new IllegalStateException( "Relationship being deleted should exist along with its nodes." );
            }

            RelationshipItem relationship = cursor.get();
            updateRelationshipCount( relationship.startNode(), relationship.type(), relationship.endNode(), -1 );
        }
        super.visitDeletedRelationship( id );
    }

    @Override
    public void visitDeletedRelationship( long id )
    {
        try
        {
            storeLayer.relationshipVisit( id, edge );
            updateRelationshipCount( edge.startNode(), edge.type(), edge.endNode(), -1 );
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( "Relationship being deleted should exist along with its nodes.", e );
        }
        super.visitDeletedRelationship( id );
    }

Try With Resources try(Cursor<RelationshipItem> cursor=storeLayer.relationshipCursor(statement,id,null)) in method public visitDeletedRelationship(id long) : void from class org.neo4j.kernel.api.txstate.TransactionCountingStateVisitor


    @Override
    public Relationship getRelationshipById( long id )
    {
        if ( id < 0 )
        {
            throw new NotFoundException( format( "Relationship %d not found", id ),
                    new EntityNotFoundException( EntityType.RELATIONSHIP, id ) );
        }
        try ( Statement statement = spi.currentStatement() )
        {
            try ( Cursor<RelationshipItem> cursor = statement.readOperations().relationshipCursorById( id ) )
            {
                RelationshipItem rel = cursor.get();
                return new RelationshipProxy( relActions, rel.id(), rel.startNode(), rel.type(), rel.endNode() );
            }
            catch ( EntityNotFoundException e )
            {
                throw new NotFoundException( format( "Relationship %d not found", id ), e );
            }
        }
    }

    @Override
    public Relationship getRelationshipById( long id )
    {
        if ( id < 0 )
        {
            throw new NotFoundException( format( "Relationship %d not found", id ),
                    new EntityNotFoundException( EntityType.RELATIONSHIP, id ) );
        }
        try ( Statement statement = spi.currentStatement() )
        {
            try
            {
                RelationshipProxy relationship = new RelationshipProxy( relActions, id );
                statement.readOperations().relationshipVisit( id, relationship );
                return relationship;
            }
            catch ( EntityNotFoundException e )
            {
                throw new NotFoundException( format( "Relationship %d not found", id ), e );
            }
        }
    }

Try With Resources try(Cursor<RelationshipItem> cursor=statement.readOperations().relationshipCursorById(id)) in method public getRelationshipById(id long) : Relationship from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    /**
     * @see SingleSourceShortestPath
     */
    public List<Node> getPredecessorNodes( Node node )
    {
        List<Node> result = new LinkedList<>();
        List<Relationship> predecessorRelationShips = predecessors.get( node );
        if ( predecessorRelationShips == null
            || predecessorRelationShips.size() == 0 )
        {
            return null;
        }
        for ( Relationship relationship : predecessorRelationShips )
        {
            result.add( relationship.getOtherNode( node ) );
        }
        return result;
    }

    /**
     * @see SingleSourceShortestPath
     */
    public List<Node> getPredecessorNodes( Node node )
    {
        List<Node> result = new LinkedList<Node>();
        List<Relationship> predecessorRelationShips = predecessors.get( node );
        if ( predecessorRelationShips == null
            || predecessorRelationShips.size() == 0 )
        {
            return null;
        }
        for ( Relationship relationship : predecessorRelationShips )
        {
            result.add( relationship.getOtherNode( node ) );
        }
        return result;
    }

Replace Generic With Diamond LinkedList<Node> with LinkedList<> in method public getPredecessorNodes(node Node) : List<Node> from class org.neo4j.graphalgo.impl.shortestpath.SingleSourceShortestPathBFS


    public static UnsatisfiedDependencyStrategy fail()
    {
        return ( kernelExtensionFactory, e ) ->
        {
            throw e;
        };
    }

    public static UnsatisfiedDependencyStrategy fail()
    {
        return new UnsatisfiedDependencyStrategy()
        {
            @Override
            public void handle( KernelExtensionFactory kernelExtensionFactory, UnsatisfiedDependencyException e )
            {
                throw e;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.extension.UnsatisfiedDependencyStrategies.fail.new UnsatisfiedDependencyStrategy with (kernelExtensionFactory, e) -> {throw e; in method public fail() : UnsatisfiedDependencyStrategy from class org.neo4j.kernel.extension.UnsatisfiedDependencyStrategies


    public static URLAccessRule combined( final Map<String,URLAccessRule> urlAccessRules )
    {
        return ( config, url ) ->
        {
            String protocol = url.getProtocol();
            URLAccessRule protocolRule = urlAccessRules.get( protocol );
            if ( protocolRule == null )
            {
                throw new URLAccessValidationError( "loading resources via protocol '" + protocol +
                        "' is not permitted" );
            }
            return protocolRule.validate( config, url );
        };
    }

    public static URLAccessRule combined( final Map<String,URLAccessRule> urlAccessRules )
    {
        return new URLAccessRule()
        {
            @Override
            public URL validate( Configuration config, URL url ) throws URLAccessValidationError
            {
                String protocol = url.getProtocol();
                URLAccessRule protocolRule = urlAccessRules.get( protocol );
                if ( protocolRule == null )
                {
                    throw new URLAccessValidationError( "loading resources via protocol '" + protocol +
                            "' is not permitted" );
                }
                return protocolRule.validate( config, url );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.security.URLAccessRules.combined.new URLAccessRule with (config, url) -> {String protocol=url.getProtocol(); in method public combined(urlAccessRules Map<String,URLAccessRule>) : URLAccessRule from class org.neo4j.kernel.impl.security.URLAccessRules


    /**
     * @return {@link TrackerFactory} creating different {@link Tracker} instances depending on size.
     */
    public static TrackerFactory dynamic()
    {
        return ( arrayFactory, size ) -> size > Integer.MAX_VALUE
                ? new LongTracker( arrayFactory.newLongArray( size, DEFAULT_VALUE ) )
                : new IntTracker( arrayFactory.newIntArray( size, DEFAULT_VALUE ) );
    }

    /**
     * @return {@link TrackerFactory} creating different {@link Tracker} instances depending on size.
     */
    public static TrackerFactory dynamic()
    {
        return new TrackerFactory()
        {
            @Override
            public Tracker create( NumberArrayFactory arrayFactory, long size )
            {
                return size > Integer.MAX_VALUE
                        ? new LongTracker( arrayFactory.newLongArray( size, DEFAULT_VALUE ) )
                        : new IntTracker( arrayFactory.newIntArray( size, DEFAULT_VALUE ) );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.cache.idmapping.string.TrackerFactories.dynamic.new TrackerFactory with (arrayFactory, size) -> size > Integer.MAX_VALUE ? new LongTracker(arrayFactory.newLongArray(size,DEFAULT_VALUE)) : new IntTracker(arrayFactory.newIntArray(size,DEFAULT_VALUE)) in method public dynamic() : TrackerFactory from class org.neo4j.unsafe.impl.batchimport.cache.idmapping.string.TrackerFactories


    public InMemoryAcceptorInstanceStore()
    {
        this( new HashMap<>(), new ArrayBlockingQueue<>( 1000 ), -1 );
    }

    public InMemoryAcceptorInstanceStore()
    {
        this(new HashMap<InstanceId, AcceptorInstance>(), new ArrayBlockingQueue<InstanceId>( 1000 ), -1);
    }

Replace Generic With Diamond HashMap<InstanceId,AcceptorInstance> with HashMap<> in method public InMemoryAcceptorInstanceStore() from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.InMemoryAcceptorInstanceStore