    @Test
    public void shouldSortLazyStringAndNonLazyStringPropertiesByValue()
    {
        DefinedProperty p1 = lazyStringProperty( 1, () -> "x" );
        DefinedProperty p2 = stringProperty( 1, "y" );

        assertThat( compare( p1, p2 ), lessThan( 0 ) );
    }

    @Test
    public void shouldSortLazyStringAndNonLazyStringPropertiesByValue()
    {
        DefinedProperty p1 = lazyStringProperty( 1, new Callable<String>(){
            @Override
            public String call() throws Exception
            {
                return "x";
            }
        } );
        DefinedProperty p2 = stringProperty( 1, "y" );

        assertThat( compare( p1, p2 ), lessThan( 0 ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.properties.DefinedPropertyTest.shouldSortLazyStringAndNonLazyStringPropertiesByValue.p1.lazyStringProperty.new Callable<String> with () -> "x" in method public shouldSortLazyStringAndNonLazyStringPropertiesByValue() : void from class org.neo4j.kernel.api.properties.DefinedPropertyTest


    @Test
    public void periodicCommitTest() throws Exception
    {
        ServerTestUtils.withCSVFile(2, url ->
        {
            // begin
            HTTP.Response begin = http.POST(
                    "/db/data/cypher",
                    quotedJson( "{ 'query': 'USING PERIODIC COMMIT 100 LOAD CSV FROM \\\"" + url + "\\\" AS line CREATE ();' }" )
            );
            assertThat( begin.status(), equalTo( 200 ) );
        } );
    }

    @Test
    public void periodicCommitTest() throws Exception
    {
        ServerTestUtils.withCSVFile(2, new ServerTestUtils.BlockWithCSVFileURL() {
            @Override
            public void execute( String url )
            {
                // begin
                HTTP.Response begin = http.POST(
                        "/db/data/cypher",
                        quotedJson( "{ 'query': 'USING PERIODIC COMMIT 100 LOAD CSV FROM \\\"" + url + "\\\" AS line CREATE ();' }" )
                );
                assertThat( begin.status(), equalTo( 200 ) );
            }
        });
    }

Replace Anonymous With Lambda org.neo4j.server.rest.web.integration.CypherOldEndpointIT.periodicCommitTest.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {HTTP.Response begin=http.POST("/db/data/cypher",quotedJson("{ 'query': 'USING PERIODIC COMMIT 100 LOAD CSV FROM \\\"" + url + "\\\" AS line CREATE ();' }")); in method public periodicCommitTest() : void from class org.neo4j.server.rest.web.integration.CypherOldEndpointIT


    @Override
    public void execute( String[] args ) throws IncorrectUsage, CommandFailed
    {
        try
        {
            Config config = loadNeo4jConfig( homeDir, configDir, arguments.parse( "database", args ) );
            File dataDirectory = config.get( DatabaseManagementSystemSettings.data_directory );
            Path pathToSpecificDatabase = config.get( DatabaseManagementSystemSettings.database_path ).toPath();

            Validators.CONTAINS_EXISTING_DATABASE.validate( pathToSpecificDatabase.toFile() );

            confirmTargetDirectoryIsWritable( pathToSpecificDatabase );

            ClusterStateDirectory clusterStateDirectory = new ClusterStateDirectory( dataDirectory );
            clusterStateDirectory.initialize( outsideWorld.fileSystem() );

            deleteClusterStateIn( clusterStateDirectory.get().toPath() );
        }
        catch ( StoreLockException e )
        {
            throw new CommandFailed( "Database is currently locked. Please shutdown Neo4j.", e );
        }
        catch ( IllegalArgumentException e )
        {
            throw new IncorrectUsage( e.getMessage() );
        }
        catch ( UnbindFailureException | CannotWriteException | IOException | ClusterStateException e )
        {
            throw new CommandFailed( e.getMessage(), e );
        }
    }

    @Override
    public void execute( String[] args ) throws IncorrectUsage, CommandFailed
    {
        try
        {
            Config config = loadNeo4jConfig( homeDir, configDir, arguments.parse( "database", args ) );
            File dataDirectory = config.get( DatabaseManagementSystemSettings.data_directory );
            Path pathToSpecificDatabase = config.get( DatabaseManagementSystemSettings.database_path ).toPath();

            Validators.CONTAINS_EXISTING_DATABASE.validate( pathToSpecificDatabase.toFile() );

            confirmTargetDirectoryIsWritable( pathToSpecificDatabase );

            ClusterStateDirectory clusterStateDirectory = new ClusterStateDirectory( dataDirectory );
            clusterStateDirectory.initialize( outsideWorld.fileSystem() );

            deleteClusterStateIn( clusterStateDirectory.get().toPath() );
        }
        catch ( StoreLockException e )
        {
            throw new CommandFailed( "Database is currently locked. Please shutdown Neo4j.", e );
        }
        catch ( IllegalArgumentException e )
        {
            throw new IncorrectUsage( e.getMessage() );
        }
        catch ( UnbindFailureException | CannotWriteException | IOException e )
        {
            throw new CommandFailed( "Unbind failed: " + e.getMessage(), e );
        }
        catch ( ClusterStateException e )
        {
            throw new CommandFailed( e );
        }
    }

Merge Catch [catch(UnbindFailureException|CannotWriteException|IOException e), catch(ClusterStateException e)] to catch(UnbindFailureException|CannotWriteException|IOException|ClusterStateException e) in method public execute(args String[]) : void from class org.neo4j.commandline.dbms.UnbindFromClusterCommand


    private Process run( int machineId ) throws IOException
    {
        List<String> allArgs = new ArrayList<>( Arrays.asList( "java", "-cp",
                System.getProperty( "java.class.path" ), "-Djava.awt.headless=true", HardKillIT.class.getName() ) );
        allArgs.add( "" + machineId );
        allArgs.add( path( machineId ).getAbsolutePath() );

        Process process = Runtime.getRuntime().exec( allArgs.toArray( new String[allArgs.size()] ) );
        processHandler = new ProcessStreamHandler( process, false );
        processHandler.launch();
        return process;
    }

    private Process run( int machineId ) throws IOException
    {
        List<String> allArgs = new ArrayList<String>( Arrays.asList( "java", "-cp",
                System.getProperty( "java.class.path" ), "-Djava.awt.headless=true", HardKillIT.class.getName() ) );
        allArgs.add( "" + machineId );
        allArgs.add( path( machineId ).getAbsolutePath() );

        Process process = Runtime.getRuntime().exec( allArgs.toArray( new String[allArgs.size()] ) );
        processHandler = new ProcessStreamHandler( process, false );
        processHandler.launch();
        return process;
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method private run(machineId int) : Process from class org.neo4j.kernel.ha.HardKillIT


    public static KernelStatement mockedState( final TransactionState txState )
    {
        KernelStatement state = mock( KernelStatement.class );
        Locks.Client locks = mock( Locks.Client.class );
        try
        {
            IndexReader indexReader = mock( IndexReader.class );
            when( indexReader.query( Matchers.isA( IndexQuery.ExactPredicate.class ) ) ).thenReturn( PrimitiveLongCollections.emptyIterator() );
            StorageStatement storageStatement = mock( StorageStatement.class );
            when( storageStatement.getIndexReader( Matchers.any() ) ).thenReturn( indexReader );
            when( state.getStoreStatement() ).thenReturn( storageStatement );
        }
        catch ( IndexNotFoundKernelException e )
        {
            throw new Error( e );
        }
        when( state.txState() ).thenReturn( txState );
        when( state.hasTxStateWithChanges() ).thenAnswer( invocation -> txState.hasChanges() );
        when( state.locks() ).thenReturn( new SimpleStatementLocks( locks ) );
        when( state.readOperations() ).thenReturn( mock( ReadOperations.class ) );
        return state;
    }

    public static KernelStatement mockedState( final TransactionState txState )
    {
        KernelStatement state = mock( KernelStatement.class );
        Locks.Client locks = mock( Locks.Client.class );
        try
        {
            IndexReader indexReader = mock( IndexReader.class );
            when( indexReader.query( Matchers.isA( IndexQuery.ExactPredicate.class ) ) ).thenReturn( PrimitiveLongCollections.emptyIterator() );
            StorageStatement storageStatement = mock( StorageStatement.class );
            when( storageStatement.getIndexReader( Matchers.any() ) ).thenReturn( indexReader );
            when( state.getStoreStatement() ).thenReturn( storageStatement );
        }
        catch ( IndexNotFoundKernelException e )
        {
            throw new Error( e );
        }
        when( state.txState() ).thenReturn( txState );
        when( state.hasTxStateWithChanges() ).thenAnswer( new Answer<Boolean>() {
            @Override
            public Boolean answer( InvocationOnMock invocation ) throws Throwable
            {
                return txState.hasChanges();
            }
        } );
        when( state.locks() ).thenReturn( new SimpleStatementLocks( locks ) );
        when( state.readOperations() ).thenReturn( mock( ReadOperations.class ) );
        return state;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.StatementOperationsTestHelper.mockedState.thenAnswer.new Answer<Boolean> with invocation -> txState.hasChanges() in method public mockedState(txState TransactionState) : KernelStatement from class org.neo4j.kernel.impl.api.StatementOperationsTestHelper


    @Test
    public void testCircularBug()
    {
        final long timestamp = 3;
        try ( Transaction tx = beginTx() )
        {
            getNodeWithName( "2" ).setProperty( "timestamp", 1L );
            getNodeWithName( "3" ).setProperty( "timestamp", 2L );
            tx.success();
        }

        try ( Transaction tx2 = beginTx() )
        {
            final RelationshipType type = RelationshipType.withName( "TO" );
            Iterator<Node> nodes = getGraphDb().traversalDescription()
                    .depthFirst()
                    .relationships( type, Direction.OUTGOING )
                    .evaluator( path ->
                    {
                        Relationship rel = path.lastRelationship();
                        boolean relIsOfType = rel != null && rel.isType( type );
                        boolean prune =
                                relIsOfType && (Long) path.endNode().getProperty( "timestamp" ) >= timestamp;
                        return Evaluation.of( relIsOfType, !prune );
                    } )
                    .traverse( node( "1" ) )
                    .nodes().iterator();

            assertEquals( "2", nodes.next().getProperty( "name" ) );
            assertEquals( "3", nodes.next().getProperty( "name" ) );
            assertFalse( nodes.hasNext() );
        }
    }

    @Test
    public void testCircularBug()
    {
        final long timestamp = 3;
        try ( Transaction tx = beginTx() )
        {
            getNodeWithName( "2" ).setProperty( "timestamp", 1L );
            getNodeWithName( "3" ).setProperty( "timestamp", 2L );
            tx.success();
        }

        try ( Transaction tx2 = beginTx() )
        {
            final RelationshipType type = RelationshipType.withName( "TO" );
            Iterator<Node> nodes = getGraphDb().traversalDescription()
                    .depthFirst()
                    .relationships( type, Direction.OUTGOING )
                    .evaluator( new Evaluator()
                    {
                        @Override
                        public Evaluation evaluate( Path path )
                        {
                            Relationship rel = path.lastRelationship();
                            boolean relIsOfType = rel != null && rel.isType( type );
                            boolean prune = relIsOfType &&
                                    ((Long)path.endNode().getProperty( "timestamp" )).longValue() >= timestamp;
                            return Evaluation.of( relIsOfType, !prune );
                        }
                    } )
                    .traverse( node( "1" ) )
                    .nodes().iterator();

            assertEquals( "2", nodes.next().getProperty( "name" ) );
            assertEquals( "3", nodes.next().getProperty( "name" ) );
            assertFalse( nodes.hasNext() );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.traversal.CircularGraphTest.testCircularBug.nodes.iterator.nodes.traverse.evaluator.new Evaluator with path -> {Relationship rel=path.lastRelationship(); in method public testCircularBug() : void from class org.neo4j.kernel.impl.traversal.CircularGraphTest


    @Test
    public void shouldBeAbleToShutdownWhenTheLeaderIsTryingToReplicateTransaction() throws Exception
    {
        // given
        cluster.coreTx( ( db, tx ) ->
        {
            Node node = db.createNode( label( "boo" ) );
            node.setProperty( "foobar", "baz_bat" );
            tx.success();
        } );

        CountDownLatch latch = new CountDownLatch( 1 );

        // when
        Thread thread = new Thread( () ->
        {
            try
            {
                cluster.coreTx( ( db, tx ) ->
                {
                    db.createNode();
                    tx.success();

                    cluster.removeCoreMember( cluster.getDbWithAnyRole( Role.FOLLOWER, Role.CANDIDATE ) );
                    cluster.removeCoreMember( cluster.getDbWithAnyRole( Role.FOLLOWER, Role.CANDIDATE ) );
                    latch.countDown();
                } );
            }
            catch ( Exception e )
            {
                throw new RuntimeException( e );
            }
        } );

        thread.start();

        latch.await();

        // then the cluster can shutdown...
        cluster.shutdown();
        // ... and the thread running the tx does not get stuck
        thread.join( TimeUnit.MINUTES.toMillis( 1 ) );
    }

    @Test
    public void shouldBeAbleToShutdownWhenTheLeaderIsTryingToReplicateTransaction() throws Exception
    {
        // given
        cluster.coreTx( ( db, tx ) ->
        {
            Node node = db.createNode( label( "boo" ) );
            node.setProperty( "foobar", "baz_bat" );
            tx.success();
        } );

        CountDownLatch latch = new CountDownLatch( 1 );

        // when
        Thread thread = new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    cluster.coreTx( ( db, tx ) ->
                    {
                        db.createNode();
                        tx.success();

                        cluster.removeCoreMember( cluster.getDbWithAnyRole( Role.FOLLOWER, Role.CANDIDATE ) );
                        cluster.removeCoreMember( cluster.getDbWithAnyRole( Role.FOLLOWER, Role.CANDIDATE ) );
                        latch.countDown();
                    } );
                }
                catch ( Exception e )
                {
                    throw new RuntimeException( e );
                }
            }
        };

        thread.start();

        latch.await();

        // then the cluster can shutdown...
        cluster.shutdown();
        // ... and the thread running the tx does not get stuck
        thread.join( TimeUnit.MINUTES.toMillis( 1 ) );
    }

Replace Anonymous With Lambda org.neo4j.causalclustering.scenarios.CoreReplicationIT.shouldBeAbleToShutdownWhenTheLeaderIsTryingToReplicateTransaction.thread.new Thread with () -> {trycluster.coreTx((db,tx) -> { in method public shouldBeAbleToShutdownWhenTheLeaderIsTryingToReplicateTransaction() : void from class org.neo4j.causalclustering.scenarios.CoreReplicationIT


    private Map<String, Map<String, String>> readMap( StoreChannel channel,
            Map<String, Map<String, String>> map, Integer sizeOrTillEof ) throws IOException
    {
        for ( int i = 0; sizeOrTillEof == null || i < sizeOrTillEof; i++ )
        {
            String indexName = readNextString( channel );
            if ( indexName == null )
            {
                break;
            }
            Integer propertyCount = readNextInt( channel );
            if ( propertyCount == null )
            {
                break;
            }
            Map<String, String> properties = new HashMap<>();
            for ( int p = 0; p < propertyCount; p++ )
            {
                String key = readNextString( channel );
                if ( key == null )
                {
                    break;
                }
                String value = readNextString( channel );
                if ( value == null )
                {
                    break;
                }
                properties.put( key, value );
            }
            map.put( indexName, properties );
        }
        return Collections.unmodifiableMap( map );
    }

    private Map<String, Map<String, String>> readMap( StoreChannel channel,
            Map<String, Map<String, String>> map, Integer sizeOrTillEof ) throws IOException
    {
        for ( int i = 0; sizeOrTillEof == null || i < sizeOrTillEof; i++ )
        {
            String indexName = readNextString( channel );
            if ( indexName == null )
            {
                break;
            }
            Integer propertyCount = readNextInt( channel );
            if ( propertyCount == null )
            {
                break;
            }
            Map<String, String> properties = new HashMap<String, String>();
            for ( int p = 0; p < propertyCount; p++ )
            {
                String key = readNextString( channel );
                if ( key == null )
                {
                    break;
                }
                String value = readNextString( channel );
                if ( value == null )
                {
                    break;
                }
                properties.put( key, value );
            }
            map.put( indexName, properties );
        }
        return Collections.unmodifiableMap( map );
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method private readMap(channel StoreChannel, map Map<String,Map<String,String>>, sizeOrTillEof Integer) : Map<String,Map<String,String>> from class org.neo4j.kernel.impl.index.IndexConfigStore


    private static Runnable slowRunnable( final Runnable target )
    {
        return () ->
        {
            LockSupport.parkNanos( 100_000_000 );
            target.run();
        };
    }

    private static Runnable slowRunnable( final Runnable target )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                LockSupport.parkNanos( 100_000_000 );
                target.run();
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.index.impl.lucene.legacy.NonUniqueIndexTests.slowRunnable.new Runnable with () -> {LockSupport.parkNanos(100_000_000); in method private slowRunnable(target Runnable) : Runnable from class org.neo4j.index.impl.lucene.legacy.NonUniqueIndexTests


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

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

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

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

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

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

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

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

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


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

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

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


    private NodeProxy mockNodeWithRels( final long ... relIds) throws EntityNotFoundException
    {
        NodeProxy.NodeActions nodeActions = mock( NodeProxy.NodeActions.class );
        final RelationshipProxy.RelationshipActions relActions = mock( RelationshipProxy.RelationshipActions.class );
        when( nodeActions.newRelationshipProxy( anyLong(), anyLong(), anyInt(), anyLong() ) ).then( invocation ->
        {
            Long id = (Long) invocation.getArguments()[0];
            Long startNode = (Long) invocation.getArguments()[1];
            Integer type = (Integer) invocation.getArguments()[2];
            Long endNode = (Long) invocation.getArguments()[3];
            return new RelationshipProxy( relActions, id, startNode, type, endNode );
        } );

        GraphDatabaseService gds = mock( GraphDatabaseService.class );

        when(gds.getRelationshipById( REL_ID )).thenReturn( mock( Relationship.class ) );
        when(gds.getRelationshipById( REL_ID + 1)).thenReturn( mock(Relationship.class) );
        when( nodeActions.getGraphDatabase() ).thenReturn( gds );

        NodeProxy nodeImpl = new NodeProxy( nodeActions, 1 );

        Statement stmt = mock( Statement.class );
        ReadOperations readOps = mock( ReadOperations.class );

        when( stmt.readOperations() ).thenReturn( readOps );
        when( nodeActions.statement() ).thenReturn( stmt );
        when( readOps.relationshipTypeGetForName( loves.name() ) ).thenReturn( 2 );

        when( readOps.nodeGetRelationships( eq( 1L ), eq( Direction.OUTGOING ), eq( new int[]{2} ) ) ).thenAnswer(
                invocation -> new RelationshipIterator.BaseIterator()
                {
                    int pos;
                    long relId;

                    @Override
                    protected boolean fetchNext()
                    {
                        if ( pos < relIds.length )
                        {
                            relId = relIds[pos++];
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }

                    @Override
                    public <EXCEPTION extends Exception> boolean relationshipVisit( long relationshipId,
                            RelationshipVisitor<EXCEPTION> visitor ) throws EXCEPTION
                    {
                        visitor.visit( relId, 2, 1, 10 * relId + 2 );
                        return false;
                    }
                } );
        return nodeImpl;
    }

    private NodeProxy mockNodeWithRels( final long ... relIds) throws EntityNotFoundException
    {
        NodeProxy.NodeActions nodeActions = mock( NodeProxy.NodeActions.class );
        final RelationshipProxy.RelationshipActions relActions = mock( RelationshipProxy.RelationshipActions.class );
        when( nodeActions.newRelationshipProxy( anyLong(), anyLong(), anyInt(), anyLong() ) ).then(
                new Answer<Relationship>()
                {
                    @Override
                    public Relationship answer( InvocationOnMock invocation ) throws Throwable
                    {
                        Long id = (Long) invocation.getArguments()[0];
                        Long startNode = (Long) invocation.getArguments()[1];
                        Integer type = (Integer) invocation.getArguments()[2];
                        Long endNode = (Long) invocation.getArguments()[3];
                        return new RelationshipProxy( relActions, id, startNode, type, endNode );
                    }
                } );

        GraphDatabaseService gds = mock( GraphDatabaseService.class );

        when(gds.getRelationshipById( REL_ID )).thenReturn( mock( Relationship.class ) );
        when(gds.getRelationshipById( REL_ID + 1)).thenReturn( mock(Relationship.class) );
        when( nodeActions.getGraphDatabase() ).thenReturn( gds );

        NodeProxy nodeImpl = new NodeProxy( nodeActions, 1 );

        Statement stmt = mock( Statement.class );
        ReadOperations readOps = mock( ReadOperations.class );

        when( stmt.readOperations() ).thenReturn( readOps );
        when( nodeActions.statement() ).thenReturn( stmt );
        when( readOps.relationshipTypeGetForName( loves.name() ) ).thenReturn( 2 );

        when( readOps.nodeGetRelationships( eq( 1L ), eq( Direction.OUTGOING ), eq( 2 ) ) ).thenAnswer( new Answer<RelationshipIterator>()
        {
            @Override
            public RelationshipIterator answer( InvocationOnMock invocation ) throws Throwable
            {
                return new RelationshipIterator.BaseIterator()
                {
                    int pos;
                    long relId;

                    @Override
                    protected boolean fetchNext()
                    {
                        if ( pos < relIds.length )
                        {
                            relId = relIds[pos++];
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }

                    @Override
                    public <EXCEPTION extends Exception> boolean relationshipVisit( long relationshipId,
                            RelationshipVisitor<EXCEPTION> visitor ) throws EXCEPTION
                    {
                        visitor.visit( relId, 2, 1, 10 * relId + 2 );
                        return false;
                    }
                };
            }
        } );
        return nodeImpl;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.core.NodeProxySingleRelationshipTest.mockNodeWithRels.thenAnswer.new Answer<RelationshipIterator> with invocation -> new RelationshipIterator.BaseIterator(){ in method private mockNodeWithRels(relIds long...) : NodeProxy from class org.neo4j.kernel.impl.core.NodeProxySingleRelationshipTest


    public void run( long memoryWeCanHoldForCertain, BatchingNeoStores neoStore, long highNodeId )
    {
        try ( RelationshipGroupCache groupCache =
                new RelationshipGroupCache( AUTO, memoryWeCanHoldForCertain, highNodeId ) )
        {
            // Read from the temporary relationship group store...
            RecordStore<RelationshipGroupRecord> fromStore = neoStore.getTemporaryRelationshipGroupStore();
            // and write into the main relationship group store
            RecordStore<RelationshipGroupRecord> toStore = neoStore.getRelationshipGroupStore();

            // Count all nodes, how many groups each node has each
            Configuration groupConfig =
                    withBatchSize( config, neoStore.getRelationshipGroupStore().getRecordsPerPage() );
            executeStage( new CountGroupsStage( groupConfig, fromStore, groupCache ) );
            long fromNodeId = 0;
            long toNodeId = 0;
            while ( fromNodeId < highNodeId )
            {
                // See how many nodes' groups we can fit into the cache this iteration of the loop.
                // Groups that doesn't fit in this round will be included in consecutive rounds.
                toNodeId = groupCache.prepare( fromNodeId );
                // Cache those groups
                executeStage( new ScanAndCacheGroupsStage( groupConfig, fromStore, groupCache ) );
                // And write them in sequential order in the store
                executeStage( new WriteGroupsStage( groupConfig, groupCache, toStore ) );

                // Make adjustments for the next iteration
                fromNodeId = toNodeId;
            }

            // Now update nodes to point to the new groups
            ByteArray groupCountCache = groupCache.getGroupCountCache();
            groupCountCache.clear();
            Configuration nodeConfig = withBatchSize( config, neoStore.getNodeStore().getRecordsPerPage() );
            executeStage( new NodeFirstGroupStage( nodeConfig, toStore, neoStore.getNodeStore(), groupCountCache ) );
        }
    }

    public void run( long memoryWeCanHoldForCertain, BatchingNeoStores neoStore, long highNodeId )
    {
        try ( RelationshipGroupCache groupCache =
                new RelationshipGroupCache( AUTO, memoryWeCanHoldForCertain, highNodeId ) )
        {
            try
            {
                // Read from the temporary relationship group store...
                RecordStore<RelationshipGroupRecord> fromStore = neoStore.getTemporaryRelationshipGroupStore();
                // and write into the main relationship group store
                RecordStore<RelationshipGroupRecord> toStore = neoStore.getRelationshipGroupStore();

                // Count all nodes, how many groups each node has each
                Configuration groupConfig =
                        withBatchSize( config, neoStore.getRelationshipGroupStore().getRecordsPerPage() );
                executeStage( new CountGroupsStage( groupConfig, fromStore, groupCache ) );
                long fromNodeId = 0;
                long toNodeId = 0;
                while ( fromNodeId < highNodeId )
                {
                    // See how many nodes' groups we can fit into the cache this iteration of the loop.
                    // Groups that doesn't fit in this round will be included in consecutive rounds.
                    toNodeId = groupCache.prepare( fromNodeId );
                    // Cache those groups
                    executeStage( new ScanAndCacheGroupsStage( groupConfig, fromStore, groupCache ) );
                    // And write them in sequential order in the store
                    executeStage( new WriteGroupsStage( groupConfig, groupCache, toStore ) );

                    // Make adjustments for the next iteration
                    fromNodeId = toNodeId;
                }

                // Now update nodes to point to the new groups
                ByteArray groupCountCache = groupCache.getGroupCountCache();
                groupCountCache.clear();
                Configuration nodeConfig = withBatchSize( config, neoStore.getNodeStore().getRecordsPerPage() );
                executeStage( new NodeFirstGroupStage( nodeConfig, toStore, neoStore.getNodeStore(), groupCountCache ) );
            }
            catch ( Throwable t )
            {
                t.printStackTrace();
                throw t;
            }
        }
    }

Try With Resources try(RelationshipGroupCache groupCache=new RelationshipGroupCache(AUTO,memoryWeCanHoldForCertain,highNodeId)) in method public run(memoryWeCanHoldForCertain long, neoStore BatchingNeoStores, highNodeId long) : void from class org.neo4j.unsafe.impl.batchimport.RelationshipGroupDefragmenter


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

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

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


    private void assertRelsInSeparateTx( final long refNode, final Direction both, final long ... longs ) throws
            InterruptedException, ExecutionException, TimeoutException
    {
        assertTrue( otherThread.execute( state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                ReadOperations stmt = statementContextSupplier.get().readOperations();
                assertRels( stmt.nodeGetRelationships( refNode, both ), longs );
            }
            return true;
        } ).get( 10, TimeUnit.SECONDS ) );
    }

    private void assertRelsInSeparateTx( final long refNode, final Direction both, final long ... longs ) throws
            InterruptedException, ExecutionException, TimeoutException
    {
        assertTrue( otherThread.execute( new OtherThreadExecutor.WorkerCommand<Object, Boolean>()
        {
            @Override
            public Boolean doWork( Object state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    ReadOperations stmt = statementContextSupplier.get().readOperations();
                    assertRels( stmt.nodeGetRelationships( refNode, both ), longs );
                }
                return true;
            }
        } ).get( 10, TimeUnit.SECONDS ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.RelationshipIT.assertRelsInSeparateTx.assertTrue.get.execute.new OtherThreadExecutor.WorkerCommand<Object,Boolean> with state -> {try(Transaction tx=db.beginTx())ReadOperations stmt=statementContextSupplier.get().readOperations(); in method private assertRelsInSeparateTx(refNode long, both Direction, longs long...) : void from class org.neo4j.kernel.impl.api.integrationtest.RelationshipIT


    @Test
    public void changedConstraintsShouldResultInTransientFailure() throws InterruptedException
    {
        // Given
        Runnable constraintCreation = () ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                createConstraintInRunningTx( db, KEY, PROP );
                tx.success();
            }
        };

        // When
        try
        {
            try ( Transaction tx = db.beginTx() )
            {
                Executors.newSingleThreadExecutor().submit( constraintCreation ).get();
                db.createNode();
                tx.success();
            }
            fail( "Exception expected" );
        }
        catch ( Exception e )
        {
            // Then
            assertThat( e, instanceOf( TransientTransactionFailureException.class ) );
            assertThat( e.getCause(), instanceOf( TransactionFailureException.class ) );
            TransactionFailureException cause = (TransactionFailureException) e.getCause();
            assertEquals( Status.Transaction.ConstraintsChanged, cause.status() );
        }
    }

    @Test
    public void changedConstraintsShouldResultInTransientFailure() throws InterruptedException
    {
        // Given
        Runnable constraintCreation = new Runnable()
        {
            @Override
            public void run()
            {
                try ( Transaction tx = db.beginTx() )
                {
                    createConstraintInRunningTx( db, KEY, PROP );
                    tx.success();
                }
            }
        };

        // When
        try
        {
            try ( Transaction tx = db.beginTx() )
            {
                Executors.newSingleThreadExecutor().submit( constraintCreation ).get();
                db.createNode();
                tx.success();
            }
            fail( "Exception expected" );
        }
        catch ( Exception e )
        {
            // Then
            assertThat( e, instanceOf( TransientTransactionFailureException.class ) );
            assertThat( e.getCause(), instanceOf( TransactionFailureException.class ) );
            TransactionFailureException cause = (TransactionFailureException) e.getCause();
            assertEquals( Status.Transaction.ConstraintsChanged, cause.status() );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.AbstractConstraintCreationIT.changedConstraintsShouldResultInTransientFailure.constraintCreation.new Runnable with () -> {try(Transaction tx=db.beginTx())createConstraintInRunningTx(db,KEY,PROP); in method public changedConstraintsShouldResultInTransientFailure() : void from class org.neo4j.kernel.impl.api.integrationtest.AbstractConstraintCreationIT


    /**
     * Creates a {@link Set} from an {@link Iterable}.
     *
     * @param iterable The items to create the set from.
     * @param <T> The generic type of items.
     * @return a set containing all items from the {@link Iterable}.
     */
    public static <T> Set<T> asUniqueSet( Iterable<T> iterable )
    {
        return Iterators.addToCollectionUnique( iterable, new HashSet<>() );
    }

    /**
     * Creates a {@link Set} from an {@link Iterable}.
     *
     * @param iterable The items to create the set from.
     * @param <T> The generic type of items.
     * @return a set containing all items from the {@link Iterable}.
     */
    public static <T> Set<T> asUniqueSet( Iterable<T> iterable )
    {
        return Iterators.addToCollectionUnique( iterable, new HashSet<T>() );
    }

Replace Generic With Diamond HashSet<T> with HashSet<> in method public asUniqueSet(iterable Iterable<T>) : Set<T> from class org.neo4j.helpers.collection.Iterables


    @Test
    public void testGetRelationshipTypesOnDiscreteNode() throws Exception
    {
        testGetRelationshipTypes( getGraphDb().createNode(), new HashSet<>() );
    }

    @Test
    public void testGetRelationshipTypesOnDiscreteNode() throws Exception
    {
        testGetRelationshipTypes( getGraphDb().createNode(), new HashSet<String>() );
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public testGetRelationshipTypesOnDiscreteNode() : void from class org.neo4j.kernel.impl.core.TestRelationshipCount


    @Override
    public long forceCheckPoint( TriggerInfo info ) throws IOException
    {
        ioLimiter.disableLimit();
        try ( Resource lock = mutex.checkPoint() )
        {
            return doCheckPoint( info, LogCheckPointEvent.NULL );
        }
        finally
        {
            ioLimiter.enableLimit();
        }
    }

    @Override
    public long forceCheckPoint( TriggerInfo info ) throws IOException
    {
        ioLimiter.disableLimit();
        lock.lock();
        try
        {
            return doCheckPoint( info, LogCheckPointEvent.NULL );
        }
        finally
        {
            lock.unlock();
            ioLimiter.enableLimit();
        }
    }

Try With Resources try(Resource lock=mutex.checkPoint()) in method public forceCheckPoint(info TriggerInfo) : long from class org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointerImpl


    private void throwsWhenInitMessageFails( Consumer<ThrowingSessionMonitor> monitorSetup,
            boolean shouldBeAbleToGetSession )
    {
        ThrowingSessionMonitor sessionMonitor = new ThrowingSessionMonitor();
        monitorSetup.accept( sessionMonitor );
        Monitors monitors = newMonitorsSpy( sessionMonitor );

        db = startTestDb( monitors );
        driver = createDriver();

        try ( Session session = driver.session() )
        {
            if ( shouldBeAbleToGetSession )
            {
                session.run( "CREATE ()" ).consume();
            }
            else
            {
                fail( "Exception expected" );
            }
        }
        catch ( Exception e )
        {
            assertThat( e, instanceOf( ConnectionFailureException.class ) );
        }
    }

    private void throwsWhenInitMessageFails( Consumer<ThrowingSessionMonitor> monitorSetup,
            boolean shouldBeAbleToGetSession )
    {
        ThrowingSessionMonitor sessionMonitor = new ThrowingSessionMonitor();
        monitorSetup.accept( sessionMonitor );
        Monitors monitors = newMonitorsSpy( sessionMonitor );

        db = startTestDb( monitors );
        driver = createDriver();

        try
        {
            Session session = driver.session();
            if ( shouldBeAbleToGetSession )
            {
                session.run( "CREATE ()" ).consume();
            }
            else
            {
                fail( "Exception expected" );
            }
        }
        catch ( Exception e )
        {
            assertThat( e, instanceOf( ConnectionFailureException.class ) );
        }
    }

Try With Resources try(Session session=driver.session()) in method private throwsWhenInitMessageFails(monitorSetup Consumer<ThrowingSessionMonitor>, shouldBeAbleToGetSession boolean) : void from class org.neo4j.bolt.BoltFailuresIT


    public IndexCreatorImpl( InternalSchemaActions actions, Label label )
    {
        this( actions, label, new ArrayList<>() );
    }

    public IndexCreatorImpl( InternalSchemaActions actions, Label label )
    {
        this( actions, label, new ArrayList<String>() );
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public IndexCreatorImpl(actions InternalSchemaActions, label Label) from class org.neo4j.kernel.impl.coreapi.schema.IndexCreatorImpl


    static <T> DiagnosticsProvider extractedProvider( DiagnosticsExtractor<T> extractor, T source )
    {
        if ( extractor instanceof DiagnosticsExtractor.VisitableDiagnostics<?> )
        {
            return new ExtractedVisitableDiagnosticsProvider<>(
                    (DiagnosticsExtractor.VisitableDiagnostics<T>) extractor, source );
        }
        else
        {
            return new ExtractedDiagnosticsProvider<>( extractor, source );
        }
    }

    static <T> DiagnosticsProvider extractedProvider( DiagnosticsExtractor<T> extractor, T source )
    {
        if ( extractor instanceof DiagnosticsExtractor.VisitableDiagnostics<?> )
        {
            return new ExtractedVisitableDiagnosticsProvider<T>(
                    (DiagnosticsExtractor.VisitableDiagnostics<T>) extractor, source );
        }
        else
        {
            return new ExtractedDiagnosticsProvider<T>( extractor, source );
        }
    }

Replace Generic With Diamond ExtractedVisitableDiagnosticsProvider<T> with ExtractedVisitableDiagnosticsProvider<> in method package extractedProvider(extractor DiagnosticsExtractor<T>, source T) : DiagnosticsProvider from class org.neo4j.kernel.info.DiagnosticsManager


    @Test
    public void shouldProvideElapsedCpuTime() throws Exception
    {
        // given
        String QUERY = "MATCH (n) SET n.v = n.v + 1";
        try ( Resource<Node> test = test( db::createNode, Transaction::acquireWriteLock, QUERY ) )
        {
            // when
            Map<String,Object> data = getQueryListing( QUERY );

            // then
            assertThat( data, hasKey( "elapsedTimeMillis" ) );
            Object elapsedTime = data.get( "elapsedTimeMillis" );
            assertThat( elapsedTime, instanceOf( Long.class ) );
            assertThat( data, hasKey( "cpuTimeMillis" ) );
            Object cpuTime1 = data.get( "cpuTimeMillis" );
            assertThat( cpuTime1, instanceOf( Long.class ) );
            assertThat( data, hasKey( "status" ) );
            Object status = data.get( "status" );
            assertThat( status, instanceOf( Map.class ) );
            @SuppressWarnings( "unchecked" )
            Map<String,Object> statusMap = (Map<String,Object>) status;
            assertEquals( "WAITING", statusMap.get( "state" ) );
            assertEquals( "NODE", statusMap.get( "resourceType" ) );
            assertArrayEquals( new long[] {test.resource().getId()}, (long[]) statusMap.get( "resourceIds" ) );
            assertThat( data, hasKey( "waitTimeMillis" ) );
            Object waitTime1 = data.get( "waitTimeMillis" );
            assertThat( waitTime1, instanceOf( Long.class ) );

            // when
            data = getQueryListing( QUERY );

            // then
            Long cpuTime2 = (Long) data.get( "cpuTimeMillis" );
            assertThat( cpuTime2, greaterThanOrEqualTo( (Long) cpuTime1 ) );
            Long waitTime2 = (Long) data.get( "waitTimeMillis" );
            assertThat( waitTime2, greaterThan( (Long) waitTime1 ) );
        }
    }

    @Test
    public void shouldProvideElapsedCpuTime() throws Exception
    {
        // given
        CountDownLatch nodeLocked = new CountDownLatch( 1 ), listQueriesLatch = new CountDownLatch( 1 );
        Node node;
        try ( Transaction tx = db.beginTx() )
        {
            node = db.createNode();
            node.setProperty( "v", 1L );
            tx.success();
        }
        threads.execute( parameter ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                tx.acquireWriteLock( node );
                nodeLocked.countDown();
                listQueriesLatch.await();
            }
            return null;
        }, null );
        nodeLocked.await();

        threads.executeAndAwait( parameter ->
        {
            db.execute( "MATCH (n) SET n.v = n.v + 1" ).close();
            return null;
        }, null, waitingWhileIn( GraphDatabaseFacade.class, "execute" ), 5, SECONDS );

        try
        {
            // when
            Map<String,Object> data = getQueryListing( "MATCH (n) SET n.v = n.v + 1" );

            // then
            assertThat( data, hasKey( "elapsedTimeMillis" ) );
            Object elapsedTime = data.get( "elapsedTimeMillis" );
            assertThat( elapsedTime, instanceOf( Long.class ) );
            assertThat( data, hasKey( "cpuTimeMillis" ) );
            Object cpuTime1 = data.get( "cpuTimeMillis" );
            assertThat( cpuTime1, instanceOf( Long.class ) );
            assertThat( data, hasKey( "status" ) );
            Object status = data.get( "status" );
            assertThat( status, instanceOf( Map.class ) );
            @SuppressWarnings( "unchecked" )
            Map<String,Object> statusMap = (Map<String,Object>) status;
            assertEquals( "WAITING", statusMap.get( "state" ) );
            assertEquals( "NODE", statusMap.get( "resourceType" ) );
            assertArrayEquals( new long[]{node.getId()}, (long[]) statusMap.get( "resourceIds" ) );
            assertThat( data, hasKey( "waitTimeMillis" ) );
            Object waitTime1 = data.get( "waitTimeMillis" );
            assertThat( waitTime1, instanceOf( Long.class ) );

            // when
            data = getQueryListing( "MATCH (n) SET n.v = n.v + 1" );

            // then
            Long cpuTime2 = (Long) data.get( "cpuTimeMillis" );
            assertThat( cpuTime2, greaterThanOrEqualTo( (Long) cpuTime1 ) );
            Long waitTime2 = (Long) data.get( "waitTimeMillis" );
            assertThat( waitTime2, greaterThan( (Long) waitTime1 ) );
        }
        finally
        {
            listQueriesLatch.countDown();
        }
    }

Try With Resources try(Resource<Node> test=test(db::createNode,Transaction::acquireWriteLock,QUERY)) in method public shouldProvideElapsedCpuTime() : void from class org.neo4j.kernel.enterprise.builtinprocs.ListQueriesProcedureTest


    @BeforeClass
    public static void initServer() throws Exception
    {
        suppressAll().call( (Callable<Void>) () ->
        {
            CommunityServerBuilder serverBuilder = EnterpriseServerBuilder.server( NullLogProvider.getInstance() );

            PropertyExistenceConstraintsIT.server = ServerHelper.createNonPersistentServer( serverBuilder );
            return null;
        } );
    }

    @BeforeClass
    public static void initServer() throws Exception
    {
        suppressAll().call( new Callable<Void>()
        {
            @Override
            public Void call() throws IOException
            {
                CommunityServerBuilder serverBuilder = EnterpriseServerBuilder.server( NullLogProvider.getInstance() )
                        .withProperty( ClusterSettings.mode.name(), "enterprise" );

                PropertyExistenceConstraintsIT.server = ServerHelper.createNonPersistentServer( serverBuilder );
                return null;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.PropertyExistenceConstraintsIT.initServer.call.new Callable<Void> with () -> {CommunityServerBuilder serverBuilder=EnterpriseServerBuilder.server(NullLogProvider.getInstance()); in method public initServer() : void from class org.neo4j.server.rest.PropertyExistenceConstraintsIT


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

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

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


    private void executeInThread( final String query )
    {
        executorService.execute( () ->
        {
            Result execute = db.execute( query );
            try
            {
                //resultAsString is good test case since it serializes labels, types, properties etc
                execute.resultAsString();
            }
            catch ( Exception e )
            {
                hasFailed.set( true );
            }
        } );
    }

    private void executeInThread( final String query )
    {
        executorService.execute( new Runnable()
        {
            @Override
            public void run()
            {
                Result execute = db.execute( query );
                try
                {
                    //resultAsString is good test case since it serializes labels, types, properties etc
                    execute.resultAsString();
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                    hasFailed.set( true );
                }
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.cypher.DeleteRelationshipStressIT.executeInThread.execute.new Runnable with () -> {Result execute=db.execute(query); in method private executeInThread(query String) : void from class org.neo4j.cypher.DeleteRelationshipStressIT


    @Test
    public void shouldNotEndLockSessionWhereThereIsAnActiveLockAcquisition() throws Throwable
    {
        // GIVEN
        CountDownLatch latch = new CountDownLatch( 1 );
        try
        {
            Client client = newWaitingLocksClient( latch );
            MasterImpl master = newMasterWithLocksClient( client );
            HandshakeResult handshake = master.handshake( 1, newStoreIdForCurrentVersion() ).response();

            // WHEN
            RequestContext context = new RequestContext( handshake.epoch(), 1, 2, 0, 0 );
            master.newLockSession( context );
            Future<Void> acquireFuture = otherThread.execute( state ->
            {
                master.acquireExclusiveLock( context, ResourceTypes.NODE, 1L );
                return null;
            } );
            otherThread.get().waitUntilWaiting();
            master.endLockSession( context, true );
            verify( client, never() ).stop();
            verify( client, never() ).close();
            latch.countDown();
            acquireFuture.get();

            // THEN
            verify( client ).close();
        }
        finally
        {
            latch.countDown();
        }
    }

    @Test
    public void shouldNotEndLockSessionWhereThereIsAnActiveLockAcquisition() throws Throwable
    {
        // GIVEN
        CountDownLatch latch = new CountDownLatch( 1 );
        try
        {
            Client client = newWaitingLocksClient( latch );
            MasterImpl master = newMasterWithLocksClient( client );
            HandshakeResult handshake = master.handshake( 1, newStoreIdForCurrentVersion() ).response();

            // WHEN
            RequestContext context = new RequestContext( handshake.epoch(), 1, 2, 0, 0 );
            master.newLockSession( context );
            Future<Void> acquireFuture = otherThread.execute( new WorkerCommand<Void,Void>()
            {
                @Override
                public Void doWork( Void state ) throws Exception
                {
                    master.acquireExclusiveLock( context, ResourceTypes.NODE, 1L );
                    return null;
                }
            } );
            otherThread.get().waitUntilWaiting();
            master.endLockSession( context, true );
            verify( client, never() ).stop();
            verify( client, never() ).close();
            latch.countDown();
            acquireFuture.get();

            // THEN
            verify( client ).close();
        }
        finally
        {
            latch.countDown();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.com.master.MasterImplTest.shouldNotEndLockSessionWhereThereIsAnActiveLockAcquisition.acquireFuture.execute.new WorkerCommand<Void,Void> with state -> {master.acquireExclusiveLock(context,ResourceTypes.NODE,1L); in method public shouldNotEndLockSessionWhereThereIsAnActiveLockAcquisition() : void from class org.neo4j.kernel.ha.com.master.MasterImplTest


    @Test
    public void shouldStopLockSessionOnFailureWhereThereIsAnActiveLockAcquisition() throws Throwable
    {
        // GIVEN
        CountDownLatch latch = new CountDownLatch( 1 );
        try
        {
            Client client = newWaitingLocksClient( latch );
            MasterImpl master = newMasterWithLocksClient( client );
            HandshakeResult handshake = master.handshake( 1, newStoreIdForCurrentVersion() ).response();

            // WHEN
            RequestContext context = new RequestContext( handshake.epoch(), 1, 2, 0, 0 );
            master.newLockSession( context );
            Future<Void> acquireFuture = otherThread.execute( state ->
            {
                master.acquireExclusiveLock( context, ResourceTypes.NODE, 1L );
                return null;
            } );
            otherThread.get().waitUntilWaiting();
            master.endLockSession( context, false );
            verify( client ).stop();
            verify( client, never() ).close();
            latch.countDown();
            acquireFuture.get();

            // THEN
            verify( client ).close();
        }
        finally
        {
            latch.countDown();
        }
    }

    @Test
    public void shouldStopLockSessionOnFailureWhereThereIsAnActiveLockAcquisition() throws Throwable
    {
        // GIVEN
        CountDownLatch latch = new CountDownLatch( 1 );
        try
        {
            Client client = newWaitingLocksClient( latch );
            MasterImpl master = newMasterWithLocksClient( client );
            HandshakeResult handshake = master.handshake( 1, newStoreIdForCurrentVersion() ).response();

            // WHEN
            RequestContext context = new RequestContext( handshake.epoch(), 1, 2, 0, 0 );
            master.newLockSession( context );
            Future<Void> acquireFuture = otherThread.execute( new WorkerCommand<Void,Void>()
            {
                @Override
                public Void doWork( Void state ) throws Exception
                {
                    master.acquireExclusiveLock( context, ResourceTypes.NODE, 1L );
                    return null;
                }
            } );
            otherThread.get().waitUntilWaiting();
            master.endLockSession( context, false );
            verify( client ).stop();
            verify( client, never() ).close();
            latch.countDown();
            acquireFuture.get();

            // THEN
            verify( client ).close();
        }
        finally
        {
            latch.countDown();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.com.master.MasterImplTest.shouldStopLockSessionOnFailureWhereThereIsAnActiveLockAcquisition.acquireFuture.execute.new WorkerCommand<Void,Void> with state -> {master.acquireExclusiveLock(context,ResourceTypes.NODE,1L); in method public shouldStopLockSessionOnFailureWhereThereIsAnActiveLockAcquisition() : void from class org.neo4j.kernel.ha.com.master.MasterImplTest


    private Client newWaitingLocksClient( final CountDownLatch latch )
    {
        Client client = mock( Client.class );

        doAnswer( invocation ->
        {
            latch.await();
            return null;
        } ).when( client ).acquireExclusive( any( ResourceType.class ), anyLong() );

        return client;
    }

    private Client newWaitingLocksClient( final CountDownLatch latch )
    {
        Client client = mock( Client.class );

        doAnswer( new Answer<Void>()
        {
            @Override
            public Void answer( InvocationOnMock invocation ) throws Throwable
            {
                latch.await();
                return null;
            }
        } ).when( client ).acquireExclusive( any( ResourceType.class ), anyLong() );

        return client;
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.com.master.MasterImplTest.newWaitingLocksClient.acquireExclusive.when.doAnswer.new Answer<Void> with invocation -> {latch.await(); in method private newWaitingLocksClient(latch CountDownLatch) : Client from class org.neo4j.kernel.ha.com.master.MasterImplTest


    @Test
    public void updatesPulledAndPullingScheduledOnSwitchToSlave() throws Throwable
    {
        SwitchToSlaveBranchThenCopy switchToSlave = newSwitchToSlaveSpy();

        when( fs.fileExists( any( File.class ) ) ).thenReturn( true );
        JobScheduler jobScheduler = mock( JobScheduler.class );
        LifeSupport communicationLife = mock( LifeSupport.class );
        URI localhost = getLocalhostUri();
        final UpdatePullerScheduler pullerScheduler =
                new UpdatePullerScheduler( jobScheduler, NullLogProvider.getInstance(), updatePuller, 10L );

        when( pullerFactory.createUpdatePullerScheduler( updatePuller ) ).thenReturn( pullerScheduler );
        // emulate lifecycle start call on scheduler
        doAnswer( invocationOnMock ->
        {
            pullerScheduler.init();
            return null;
        } ).when( communicationLife ).start();

        switchToSlave.switchToSlave( communicationLife, localhost, localhost, mock( CancellationRequest.class ) );

        verify( updatePuller ).tryPullUpdates();
        verify( communicationLife ).add( pullerScheduler );
        verify( jobScheduler ).scheduleRecurring( eq( JobScheduler.Groups.pullUpdates ), any( Runnable.class ),
                eq( 10L ), eq( 10L ), eq( TimeUnit.MILLISECONDS ) );
    }

    @Test
    public void updatesPulledAndPullingScheduledOnSwitchToSlave() throws Throwable
    {
        SwitchToSlaveBranchThenCopy switchToSlave = newSwitchToSlaveSpy();

        when( fs.fileExists( any( File.class ) ) ).thenReturn( true );
        JobScheduler jobScheduler = mock( JobScheduler.class );
        LifeSupport communicationLife = mock( LifeSupport.class );
        URI localhost = getLocalhostUri();
        final UpdatePullerScheduler pullerScheduler =
                new UpdatePullerScheduler( jobScheduler, NullLogProvider.getInstance(), updatePuller, 10L );

        when( pullerFactory.createUpdatePullerScheduler( updatePuller ) ).thenReturn( pullerScheduler );
        // emulate lifecycle start call on scheduler
        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocationOnMock ) throws Throwable
            {
                pullerScheduler.init();
                return null;
            }
        } ).when( communicationLife ).start();

        switchToSlave.switchToSlave( communicationLife, localhost, localhost, mock( CancellationRequest.class ) );

        verify( updatePuller ).tryPullUpdates();
        verify( communicationLife ).add( pullerScheduler );
        verify( jobScheduler ).scheduleRecurring( eq( JobScheduler.Groups.pullUpdates ), any( Runnable.class ),
                eq( 10L ), eq( 10L ), eq( TimeUnit.MILLISECONDS ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.SwitchToSlaveBranchThenCopyTest.updatesPulledAndPullingScheduledOnSwitchToSlave.start.when.doAnswer.new Answer with invocationOnMock -> {pullerScheduler.init(); in method public updatesPulledAndPullingScheduledOnSwitchToSlave() : void from class org.neo4j.kernel.ha.cluster.SwitchToSlaveBranchThenCopyTest


    static Runnable throwing( ThrowingRunnable callable )
    {
        return () ->
        {
            try
            {
                callable.run();
            }
            catch ( Exception e )
            {
                throw new RuntimeException( e );
            }
        };
    }

    static Runnable throwing( ThrowingRunnable callable )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    callable.run();
                }
                catch ( Exception e )
                {
                    throw new RuntimeException( e );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.index.gbptree.ThrowingRunnable.throwing.new Runnable with () -> {trycallable.run(); in method public throwing(callable ThrowingRunnable) : Runnable from class org.neo4j.index.gbptree.ThrowingRunnable


    private Runnable waitForLatch( final CountDownLatch threadStarted, final CountDownLatch runUntil )
    {
        return () ->
        {
            try
            {
                threadStarted.countDown();
                runUntil.await();
            }
            catch ( InterruptedException e )
            {
                throw new RuntimeException( e );
            }
        };
    }

    private Runnable waitForLatch( final CountDownLatch threadStarted, final CountDownLatch runUntil )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    threadStarted.countDown();
                    runUntil.await();
                }
                catch ( InterruptedException e )
                {
                    throw new RuntimeException( e );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.util.Neo4jJobSchedulerTest.waitForLatch.new Runnable with () -> {trythreadStarted.countDown(); in method private waitForLatch(threadStarted CountDownLatch, runUntil CountDownLatch) : Runnable from class org.neo4j.kernel.impl.util.Neo4jJobSchedulerTest


    public LuceneBatchInserterIndexProviderNewImpl( final BatchInserter inserter )
    {
        this.inserter = inserter;
        this.indexStore = ((IndexConfigStoreProvider) inserter).getIndexConfigStore();
        this.relationshipLookup = id ->
        {
            // TODO too may objects allocated here
            BatchRelationship rel = inserter.getRelationshipById( id );
            return new EntityId.RelationshipData( id, rel.getStartNode(), rel.getEndNode() );
        };
    }

    public LuceneBatchInserterIndexProviderNewImpl( final BatchInserter inserter )
    {
        this.inserter = inserter;
        this.indexStore = ((BatchInserterImpl) inserter).getIndexStore();
        this.relationshipLookup = new LuceneBatchInserterIndex.RelationshipLookup()
        {
            @Override
            public EntityId lookup( long id )
            {
                // TODO too may objects allocated here
                BatchRelationship rel = inserter.getRelationshipById( id );
                return new EntityId.RelationshipData( id, rel.getStartNode(), rel.getEndNode() );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.index.impl.lucene.legacy.LuceneBatchInserterIndexProviderNewImpl.LuceneBatchInserterIndexProviderNewImpl.new LuceneBatchInserterIndex.RelationshipLookup with id -> {BatchRelationship rel=inserter.getRelationshipById(id); in method public LuceneBatchInserterIndexProviderNewImpl(inserter BatchInserter) from class org.neo4j.index.impl.lucene.legacy.LuceneBatchInserterIndexProviderNewImpl


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

        public void commitTx() 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.store.TestGraphProperties.Worker.commitTx.execute.new WorkerCommand<State,Void> with state -> {state.tx.success(); in method public commitTx() : void from class org.neo4j.kernel.impl.store.TestGraphProperties.Worker


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

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

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


        Future<Void> setProperty( final String key, final Object value ) throws Exception
        {
            return executeDontWait( state ->
            {
                state.properties.setProperty( key, value );
                return null;
            } );
        }

        Future<Void> setProperty( final String key, final Object value ) throws Exception
        {
            return executeDontWait( new WorkerCommand<State, Void>()
            {
                @Override
                public Void doWork( State state )
                {
                    state.properties.setProperty( key, value );
                    return null;
                }
            } );
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.TestGraphProperties.Worker.setProperty.executeDontWait.new WorkerCommand<State,Void> with state -> {state.properties.setProperty(key,value); in method package setProperty(key String, value Object) : Future<Void> from class org.neo4j.kernel.impl.store.TestGraphProperties.Worker


    private long lastAppliedTx( File storeDir )
    {
        try ( FileSystemAbstraction fileSyste = new DefaultFileSystemAbstraction();
              PageCache pageCache = createPageCache( new DefaultFileSystemAbstraction() ) )
        {
            return MetaDataStore.getRecord( pageCache, new File( storeDir, MetaDataStore.DEFAULT_NAME ),
                    MetaDataStore.Position.LAST_TRANSACTION_ID );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

    private long lastAppliedTx( File storeDir )
    {
        try
        {
            return MetaDataStore.getRecord( createPageCache( new DefaultFileSystemAbstraction() ),
                    new File( storeDir, MetaDataStore.DEFAULT_NAME ),
                    MetaDataStore.Position.LAST_TRANSACTION_ID );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

Try With Resources try(FileSystemAbstraction fileSyste=new DefaultFileSystemAbstraction(); PageCache pageCache=createPageCache(new DefaultFileSystemAbstraction())) in method private lastAppliedTx(storeDir File) : long from class org.neo4j.tools.applytx.DatabaseRebuildToolTest


    @Override
    public void execute( String[] args ) throws IncorrectUsage, CommandFailed
    {
        final String database;
        final Boolean verbose;
        final Optional<Path> additionalConfigFile;
        final Path reportDir;

        try
        {
            database = arguments.parse( "database", args );
            verbose = arguments.parseBoolean( "verbose", args );
            additionalConfigFile = arguments.parseOptionalPath( "additional-config", args );
            reportDir = arguments.parseOptionalPath( "report-dir", args )
                    .orElseThrow( () -> new IllegalArgumentException( "report-dir must be a valid path" ) );
        }
        catch ( IllegalArgumentException e )
        {
            throw new IncorrectUsage( e.getMessage() );
        }

        Config config = loadNeo4jConfig( homeDir, configDir, database, loadAdditionalConfig( additionalConfigFile ) );

        try ( FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction() )
        {
            File storeDir = config.get( database_path );
            checkDbState( storeDir, config );
            ConsistencyCheckService.Result consistencyCheckResult = consistencyCheckService
                    .runFullConsistencyCheck( storeDir, config, ProgressMonitorFactory.textual( System.err ),
                            FormattedLogProvider.toOutputStream( System.out ), fileSystem, verbose,
                            reportDir.toFile() );

            if ( !consistencyCheckResult.isSuccessful() )
            {
                throw new CommandFailed( format( "Inconsistencies found. See '%s' for details.",
                        consistencyCheckResult.reportFile() ) );
            }
        }
        catch ( ConsistencyCheckIncompleteException | IOException e )
        {
            throw new CommandFailed( "Consistency checking failed." + e.getMessage(), e );
        }
    }

    @Override
    public void execute( String[] args ) throws IncorrectUsage, CommandFailed
    {
        final String database;
        final Boolean verbose;
        final Optional<Path> additionalConfigFile;
        final Path reportDir;

        try
        {
            database = arguments.parse( "database", args );
            verbose = arguments.parseBoolean( "verbose", args );
            additionalConfigFile = arguments.parseOptionalPath( "additional-config", args );
            reportDir = arguments.parseOptionalPath( "report-dir", args )
                    .orElseThrow( () -> new IllegalArgumentException( "report-dir must be a valid path" ) );
        }
        catch ( IllegalArgumentException e )
        {
            throw new IncorrectUsage( e.getMessage() );
        }

        Config config = loadNeo4jConfig( homeDir, configDir, database, loadAdditionalConfig( additionalConfigFile ) );

        try
        {
            File storeDir = config.get( database_path );
            checkDbState( storeDir, config );
            ConsistencyCheckService.Result consistencyCheckResult = consistencyCheckService
                    .runFullConsistencyCheck( storeDir, config, ProgressMonitorFactory.textual( System.err ),
                            FormattedLogProvider.toOutputStream( System.out ), this.fileSystemAbstraction, verbose,
                            reportDir.toFile() );

            if ( !consistencyCheckResult.isSuccessful() )
            {
                throw new CommandFailed( format( "Inconsistencies found. See '%s' for details.",
                        consistencyCheckResult.reportFile() ) );
            }
        }
        catch ( ConsistencyCheckIncompleteException | IOException e )
        {
            throw new CommandFailed( "Consistency checking failed." + e.getMessage(), e );
        }
    }

Try With Resources try(FileSystemAbstraction fileSystem=new DefaultFileSystemAbstraction()) in method public execute(args String[]) : void from class org.neo4j.consistency.CheckConsistencyCommand


    /**
     * Runs the import tool given the supplied arguments.
     *
     * @param incomingArguments arguments for specifying input and configuration for the import.
     * @param defaultSettingsSuitableForTests default configuration geared towards unit/integration
     * test environments, for example lower default buffer sizes.
     */
    public static void main( String[] incomingArguments, boolean defaultSettingsSuitableForTests ) throws IOException
    {
        System.err.println("WARNING: neo4j-import is deprecated and support for it will be removed in a future\n" +
                "version of Neo4j; please use neo4j-admin import instead.\n");
        PrintStream out = System.out;
        PrintStream err = System.err;
        Args args = Args.parse( incomingArguments );

        if ( ArrayUtil.isEmpty( incomingArguments ) || asksForUsage( args ) )
        {
            printUsage( out );
            return;
        }

        File storeDir;
        Collection<Option<File[]>> nodesFiles, relationshipsFiles;
        boolean enableStacktrace;
        Number processors = null;
        Input input = null;
        int badTolerance;
        Charset inputEncoding;
        boolean skipBadRelationships, skipDuplicateNodes, ignoreExtraColumns;
        Config dbConfig;
        OutputStream badOutput = null;
        IdType idType = null;
        int pageSize = UNSPECIFIED;
        Collector badCollector;
        org.neo4j.unsafe.impl.batchimport.Configuration configuration = null;
        File logsDir;
        File badFile;

        boolean success = false;
        try ( FileSystemAbstraction fs = new DefaultFileSystemAbstraction() )
        {
            storeDir = args.interpretOption( Options.STORE_DIR.key(), Converters.<File>mandatory(),
                    Converters.toFile(), Validators.DIRECTORY_IS_WRITABLE, Validators.CONTAINS_NO_EXISTING_DATABASE );
            Config config = Config.defaults();
            config.augment( stringMap( GraphDatabaseSettings.neo4j_home.name(), storeDir.getAbsolutePath() ) );
            logsDir = config.get( GraphDatabaseSettings.logs_directory );
            fs.mkdirs( logsDir );

            badFile = new File( storeDir, BAD_FILE_NAME );
            badOutput = new BufferedOutputStream( fs.openAsOutputStream( badFile, false ) );
            nodesFiles = extractInputFiles( args, Options.NODE_DATA.key(), err );
            relationshipsFiles = extractInputFiles( args, Options.RELATIONSHIP_DATA.key(), err );
            validateInputFiles( nodesFiles, relationshipsFiles );
            enableStacktrace = args.getBoolean( Options.STACKTRACE.key(), Boolean.FALSE, Boolean.TRUE );
            processors = args.getNumber( Options.PROCESSORS.key(), null );
            idType = args.interpretOption( Options.ID_TYPE.key(),
                    withDefault( (IdType)Options.ID_TYPE.defaultValue() ), TO_ID_TYPE );
            badTolerance = args.getNumber( Options.BAD_TOLERANCE.key(),
                    (Number) Options.BAD_TOLERANCE.defaultValue() ).intValue();
            inputEncoding = Charset.forName( args.get( Options.INPUT_ENCODING.key(), defaultCharset().name() ) );
            skipBadRelationships = args.getBoolean( Options.SKIP_BAD_RELATIONSHIPS.key(),
                    (Boolean)Options.SKIP_BAD_RELATIONSHIPS.defaultValue(), true );
            skipDuplicateNodes = args.getBoolean( Options.SKIP_DUPLICATE_NODES.key(),
                    (Boolean)Options.SKIP_DUPLICATE_NODES.defaultValue(), true );
            ignoreExtraColumns = args.getBoolean( Options.IGNORE_EXTRA_COLUMNS.key(),
                    (Boolean)Options.IGNORE_EXTRA_COLUMNS.defaultValue(), true );

            badCollector = badCollector( badOutput, badTolerance, collect( skipBadRelationships,
                    skipDuplicateNodes, ignoreExtraColumns ) );

            dbConfig = loadDbConfig( args.interpretOption( Options.DATABASE_CONFIG.key(), Converters.<File>optional(),
                    Converters.toFile(), Validators.REGEX_FILE_EXISTS ) );
            if ( args.has( Options.PAGE_SIZE.key() ) )
            {
                pageSize = toIntExact( parseLongWithUnit( args.get( Options.PAGE_SIZE.key(),
                        String.valueOf( UNSPECIFIED ) ) ) );
            }
            configuration = importConfiguration( processors, defaultSettingsSuitableForTests, dbConfig, pageSize );
            input = new CsvInput( nodeData( inputEncoding, nodesFiles ), defaultFormatNodeFileHeader(),
                    relationshipData( inputEncoding, relationshipsFiles ), defaultFormatRelationshipFileHeader(),
                    idType, csvConfiguration( args, defaultSettingsSuitableForTests ), badCollector,
                    configuration.maxNumberOfProcessors() );

            doImport( out, err, storeDir, logsDir, badFile, fs, nodesFiles, relationshipsFiles,
                    enableStacktrace, input, dbConfig, badOutput, configuration );

            success = true;
        }
        catch ( IllegalArgumentException e )
        {
            throw andPrintError( "Input error", e, false, err );
        }
        catch ( IOException e )
        {
            throw andPrintError( "File error", e, false, err );
        }
        finally
        {
            if ( !success && badOutput != null )
            {
                badOutput.close();
            }
        }
    }

    /**
     * Runs the import tool given the supplied arguments.
     *
     * @param incomingArguments arguments for specifying input and configuration for the import.
     * @param defaultSettingsSuitableForTests default configuration geared towards unit/integration
     * test environments, for example lower default buffer sizes.
     */
    public static void main( String[] incomingArguments, boolean defaultSettingsSuitableForTests ) throws IOException
    {
        System.err.println("WARNING: neo4j-import is deprecated and support for it will be removed in a future\n" +
                "version of Neo4j; please use neo4j-admin import instead.\n");
        PrintStream out = System.out;
        PrintStream err = System.err;
        Args args = Args.parse( incomingArguments );

        if ( ArrayUtil.isEmpty( incomingArguments ) || asksForUsage( args ) )
        {
            printUsage( out );
            return;
        }

        FileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        File storeDir;
        Collection<Option<File[]>> nodesFiles, relationshipsFiles;
        boolean enableStacktrace;
        Number processors = null;
        Input input = null;
        int badTolerance;
        Charset inputEncoding;
        boolean skipBadRelationships, skipDuplicateNodes, ignoreExtraColumns;
        Config dbConfig;
        OutputStream badOutput = null;
        IdType idType = null;
        int pageSize = UNSPECIFIED;
        Collector badCollector;
        org.neo4j.unsafe.impl.batchimport.Configuration configuration = null;
        File logsDir;
        File badFile;

        boolean success = false;
        try
        {
            storeDir = args.interpretOption( Options.STORE_DIR.key(), Converters.<File>mandatory(),
                    Converters.toFile(), Validators.DIRECTORY_IS_WRITABLE, Validators.CONTAINS_NO_EXISTING_DATABASE );
            Config config = Config.defaults();
            config.augment( stringMap( GraphDatabaseSettings.neo4j_home.name(), storeDir.getAbsolutePath() ) );
            logsDir = config.get( GraphDatabaseSettings.logs_directory );
            fs.mkdirs( logsDir );

            badFile = new File( storeDir, BAD_FILE_NAME );
            badOutput = new BufferedOutputStream( fs.openAsOutputStream( badFile, false ) );
            nodesFiles = extractInputFiles( args, Options.NODE_DATA.key(), err );
            relationshipsFiles = extractInputFiles( args, Options.RELATIONSHIP_DATA.key(), err );
            validateInputFiles( nodesFiles, relationshipsFiles );
            enableStacktrace = args.getBoolean( Options.STACKTRACE.key(), Boolean.FALSE, Boolean.TRUE );
            processors = args.getNumber( Options.PROCESSORS.key(), null );
            idType = args.interpretOption( Options.ID_TYPE.key(),
                    withDefault( (IdType)Options.ID_TYPE.defaultValue() ), TO_ID_TYPE );
            badTolerance = args.getNumber( Options.BAD_TOLERANCE.key(),
                    (Number) Options.BAD_TOLERANCE.defaultValue() ).intValue();
            inputEncoding = Charset.forName( args.get( Options.INPUT_ENCODING.key(), defaultCharset().name() ) );
            skipBadRelationships = args.getBoolean( Options.SKIP_BAD_RELATIONSHIPS.key(),
                    (Boolean)Options.SKIP_BAD_RELATIONSHIPS.defaultValue(), true );
            skipDuplicateNodes = args.getBoolean( Options.SKIP_DUPLICATE_NODES.key(),
                    (Boolean)Options.SKIP_DUPLICATE_NODES.defaultValue(), true );
            ignoreExtraColumns = args.getBoolean( Options.IGNORE_EXTRA_COLUMNS.key(),
                    (Boolean)Options.IGNORE_EXTRA_COLUMNS.defaultValue(), true );

            badCollector = badCollector( badOutput, badTolerance, collect( skipBadRelationships,
                    skipDuplicateNodes, ignoreExtraColumns ) );

            dbConfig = loadDbConfig( args.interpretOption( Options.DATABASE_CONFIG.key(), Converters.<File>optional(),
                    Converters.toFile(), Validators.REGEX_FILE_EXISTS ) );
            if ( args.has( Options.PAGE_SIZE.key() ) )
            {
                pageSize = toIntExact( parseLongWithUnit( args.get( Options.PAGE_SIZE.key(),
                        String.valueOf( UNSPECIFIED ) ) ) );
            }
            configuration = importConfiguration( processors, defaultSettingsSuitableForTests, dbConfig, pageSize );
            input = new CsvInput( nodeData( inputEncoding, nodesFiles ), defaultFormatNodeFileHeader(),
                    relationshipData( inputEncoding, relationshipsFiles ), defaultFormatRelationshipFileHeader(),
                    idType, csvConfiguration( args, defaultSettingsSuitableForTests ), badCollector,
                    configuration.maxNumberOfProcessors() );

            doImport( out, err, storeDir, logsDir, badFile, fs, nodesFiles, relationshipsFiles,
                    enableStacktrace, input, dbConfig, badOutput, configuration );

            success = true;
        }
        catch ( IllegalArgumentException e )
        {
            throw andPrintError( "Input error", e, false, err );
        }
        catch ( IOException e )
        {
            throw andPrintError( "File error", e, false, err );
        }
        finally
        {
            if ( !success && badOutput != null )
            {
                badOutput.close();
            }
        }
    }

Try With Resources try(FileSystemAbstraction fs=new DefaultFileSystemAbstraction()) in method public main(incomingArguments String[], defaultSettingsSuitableForTests boolean) : void from class org.neo4j.tooling.ImportTool


    @Override
    public void execute( String[] incomingArguments ) throws IncorrectUsage, CommandFailed
    {
        String databaseName;
        String fromPath;
        boolean forceOverwrite;

        try
        {
            databaseName = arguments.parse( "database", incomingArguments );
            fromPath = arguments.parse("from", incomingArguments);
            forceOverwrite = arguments.parseBoolean("force", incomingArguments);
        }
        catch ( IllegalArgumentException e )
        {
            throw new IncorrectUsage( e.getMessage() );
        }

        Config config = loadNeo4jConfig( homeDir, configDir, databaseName );

        try ( FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction() )
        {
            RestoreDatabaseCommand restoreDatabaseCommand = new RestoreDatabaseCommand( fileSystem,
                    new File( fromPath ), config, databaseName, forceOverwrite );
            restoreDatabaseCommand.execute();
        }
        catch ( IOException e )
        {
            throw new CommandFailed( "Failed to restore database", e );
        }
    }

    @Override
    public void execute( String[] incomingArguments ) throws IncorrectUsage, CommandFailed
    {
        String databaseName;
        String fromPath;
        boolean forceOverwrite;

        try
        {
            databaseName = arguments.parse( "database", incomingArguments );
            fromPath = arguments.parse("from", incomingArguments);
            forceOverwrite = arguments.parseBoolean("force", incomingArguments);
        }
        catch ( IllegalArgumentException e )
        {
            throw new IncorrectUsage( e.getMessage() );
        }

        Config config = loadNeo4jConfig( homeDir, configDir, databaseName );

        RestoreDatabaseCommand restoreDatabaseCommand = new RestoreDatabaseCommand( new DefaultFileSystemAbstraction(),
                new File( fromPath ), config, databaseName, forceOverwrite );

        try
        {
            restoreDatabaseCommand.execute();
        }
        catch ( IOException e )
        {
            throw new CommandFailed( "Failed to restore database", e );
        }
    }

Try With Resources try(FileSystemAbstraction fileSystem=new DefaultFileSystemAbstraction()) in method public execute(incomingArguments String[]) : void from class org.neo4j.restore.RestoreDatabaseCli


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

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

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


    private WorkerCommand<Void, Object> setProperty( final PropertyContainer entity,
            final String key, final String value )
    {
        return state ->
        {
            entity.setProperty( key, value );
            return null;
        };
    }

    private WorkerCommand<Void, Object> setProperty( final PropertyContainer entity,
            final String key, final String value )
    {
        return new WorkerCommand<Void, Object>()
        {
            @Override
            public Object doWork( Void state ) throws Exception
            {
                entity.setProperty( key, value );
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.graphdb.GraphDatabaseServiceTest.setProperty.new WorkerCommand<Void,Object> with state -> {entity.setProperty(key,value); in method private setProperty(entity PropertyContainer, key String, value String) : WorkerCommand<Void,Object> from class org.neo4j.graphdb.GraphDatabaseServiceTest


    private WorkerCommand<Void, Void> close( final Transaction tx )
    {
        return state ->
        {
            tx.close();
            return null;
        };
    }

    private WorkerCommand<Void, Void> close( final Transaction tx )
    {
        return new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                tx.close();
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.graphdb.GraphDatabaseServiceTest.close.new WorkerCommand<Void,Void> with state -> {tx.close(); in method private close(tx Transaction) : WorkerCommand<Void,Void> from class org.neo4j.graphdb.GraphDatabaseServiceTest


    private LockAcquisition acquireLockInAnotherThread( final boolean shared )
    {
        final LockAcquisition lockAcquisition = new LockAcquisition();

        Future<Void> future = threadA.execute( state ->
        {
            Locks.Client client = newLockClient( lockAcquisition );
            if ( shared )
            {
                client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );
            }
            else
            {
                client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
            }
            return null;
        } );
        lockAcquisition.setFuture( future, threadA.get() );

        return lockAcquisition;
    }

    private LockAcquisition acquireLockInAnotherThread( final boolean shared )
    {
        final LockAcquisition lockAcquisition = new LockAcquisition();

        Future<Void> future = threadA.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                Locks.Client client = newLockClient( lockAcquisition );
                if ( shared )
                {
                    client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );
                }
                else
                {
                    client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
                }
                return null;
            }
        } );
        lockAcquisition.setFuture( future, threadA.get() );

        return lockAcquisition;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.StopCompatibility.acquireLockInAnotherThread.future.execute.new WorkerCommand<Void,Void> with state -> {Locks.Client client=newLockClient(lockAcquisition); in method private acquireLockInAnotherThread(shared boolean) : LockAcquisition from class org.neo4j.kernel.impl.locking.StopCompatibility


    private LockAcquisition acquireTwoLocksInAnotherThread( final boolean firstShared, final boolean secondShared,
            final CountDownLatch firstLockFailed, final CountDownLatch startSecondLock )
    {
        final LockAcquisition lockAcquisition = new LockAcquisition();

        Future<Void> future = threadA.execute( state ->
        {
            try ( Locks.Client client = newLockClient( lockAcquisition ) )
            {
                try
                {
                    if ( firstShared )
                    {
                        client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );
                    }
                    else
                    {
                        client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
                    }
                    fail( "Transaction termination expected" );
                }
                catch ( Exception e )
                {
                    assertThat( e, instanceOf( LockClientStoppedException.class ) );
                }
            }

            lockAcquisition.setClient( null );
            firstLockFailed.countDown();
            await( startSecondLock );

            try ( Locks.Client client = newLockClient( lockAcquisition ) )
            {
                if ( secondShared )
                {
                    client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );
                }
                else
                {
                    client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
                }
            }
            return null;
        } );
        lockAcquisition.setFuture( future, threadA.get() );

        return lockAcquisition;
    }

    private LockAcquisition acquireTwoLocksInAnotherThread( final boolean firstShared, final boolean secondShared,
            final CountDownLatch firstLockFailed, final CountDownLatch startSecondLock )
    {
        final LockAcquisition lockAcquisition = new LockAcquisition();

        Future<Void> future = threadA.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Locks.Client client = newLockClient( lockAcquisition ) )
                {
                    try
                    {
                        if ( firstShared )
                        {
                            client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );
                        }
                        else
                        {
                            client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
                        }
                        fail( "Transaction termination expected" );
                    }
                    catch ( Exception e )
                    {
                        assertThat( e, instanceOf( LockClientStoppedException.class ) );
                    }
                }

                lockAcquisition.setClient( null );
                firstLockFailed.countDown();
                await( startSecondLock );

                try ( Locks.Client client = newLockClient( lockAcquisition ) )
                {
                    if ( secondShared )
                    {
                        client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );
                    }
                    else
                    {
                        client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
                    }
                }
                return null;
            }
        } );
        lockAcquisition.setFuture( future, threadA.get() );

        return lockAcquisition;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.StopCompatibility.acquireTwoLocksInAnotherThread.future.execute.new WorkerCommand<Void,Void> with state -> {try(Locks.Client client=newLockClient(lockAcquisition))tryif(firstShared){client.acquireShared(RESOURCE_TYPE,RESOURCE_ID); in method private acquireTwoLocksInAnotherThread(firstShared boolean, secondShared boolean, firstLockFailed CountDownLatch, startSecondLock CountDownLatch) : LockAcquisition from class org.neo4j.kernel.impl.locking.StopCompatibility