    private void baseTestForElectionOk( Set<InstanceId> failed, boolean moreThanQuorum )
    {
        Map<InstanceId, URI> members = new HashMap<>();
        members.put( new InstanceId( 1 ), URI.create( "server1" ) );
        members.put( new InstanceId( 2 ), URI.create( "server2" ) );
        members.put( new InstanceId( 3 ), URI.create( "server3" ) );

        Config config = mock( Config.class );
        when( config.get( ClusterSettings.max_acceptors ) ).thenReturn( 10 );

        ClusterConfiguration clusterConfiguration = mock( ClusterConfiguration.class );
        when( clusterConfiguration.getMembers() ).thenReturn( members );

        ClusterContext clusterContext = mock( ClusterContext.class );
        when( clusterContext.getConfiguration() ).thenReturn( clusterConfiguration );

        MultiPaxosContext context =
                new MultiPaxosContext( new InstanceId( 1 ), Iterables.iterable( new ElectionRole( "coordinator" ) ),
                        clusterConfiguration, mock( Executor.class ), NullLogProvider.getInstance(),
                        mock( ObjectInputStreamFactory.class ), mock( ObjectOutputStreamFactory.class ),
                        mock( AcceptorInstanceStore.class ), mock( Timeouts.class ),
                        mock( ElectionCredentialsProvider.class ), config );

        context.getHeartbeatContext().getFailed().addAll( failed );

        ElectionContext toTest = context.getElectionContext();

        assertEquals( moreThanQuorum, !toTest.electionOk() );
    }

    private void baseTestForElectionOk( Set<InstanceId> failed, boolean moreThanQuorum )
    {
        Map<InstanceId, URI> members = new HashMap<InstanceId, URI>();
        members.put( new InstanceId( 1 ), URI.create( "server1" ) );
        members.put( new InstanceId( 2 ), URI.create( "server2" ) );
        members.put( new InstanceId( 3 ), URI.create( "server3" ) );

        Config config = mock( Config.class );
        when( config.get( ClusterSettings.max_acceptors ) ).thenReturn( 10 );

        ClusterConfiguration clusterConfiguration = mock( ClusterConfiguration.class );
        when( clusterConfiguration.getMembers() ).thenReturn( members );

        ClusterContext clusterContext = mock( ClusterContext.class );
        when( clusterContext.getConfiguration() ).thenReturn( clusterConfiguration );

        MultiPaxosContext context =
                new MultiPaxosContext( new InstanceId( 1 ), Iterables.iterable( new ElectionRole( "coordinator" ) ),
                        clusterConfiguration, mock( Executor.class ), NullLogProvider.getInstance(),
                        mock( ObjectInputStreamFactory.class ), mock( ObjectOutputStreamFactory.class ),
                        mock( AcceptorInstanceStore.class ), mock( Timeouts.class ),
                        mock( ElectionCredentialsProvider.class ), config );

        context.getHeartbeatContext().getFailed().addAll( failed );

        ElectionContext toTest = context.getElectionContext();

        assertEquals( moreThanQuorum, !toTest.electionOk() );
    }

Replace Generic With Diamond HashMap<InstanceId,URI> with HashMap<> in method private baseTestForElectionOk(failed Set<InstanceId>, moreThanQuorum boolean) : void from class org.neo4j.cluster.protocol.election.ElectionContextTest


    @Test
    public void electionShouldRemainLocalIfStartedBySingleInstanceWhichIsTheRoleHolder() throws Throwable
    {
        /*
         * Ensures that when an instance is alone in the cluster, elections for roles that it holds do not set
         * timeouts or try to reach other instances.
         */

        // Given
        ElectionContext context = mock( ElectionContext.class );
        ClusterContext clusterContextMock = mock( ClusterContext.class );

        when( clusterContextMock.getLog( ArgumentMatchers.<Class>any() ) ).thenReturn( NullLog.getInstance() );
        MessageHolder holder = mock( MessageHolder.class );

          // These mean the election can proceed normally, by us
        when( context.electionOk() ).thenReturn( true );
        when( context.isInCluster() ).thenReturn( true );
        when( context.isElector() ).thenReturn( true );

          // Like it says on the box, we are the only instance
        final InstanceId myInstanceId = new InstanceId( 1 );
        Map<InstanceId, URI> members = new HashMap<>();
        members.put( myInstanceId, URI.create( "ha://me" ) );
        when( context.getMembers() ).thenReturn( members );

          // Any role would do, just make sure we have it
        final String role = "master";
        ElectionContext.VoteRequest voteRequest = new ElectionContext.VoteRequest( role, 13 );
        when( context.getPossibleRoles() ).thenReturn(
                Collections.singletonList( new ElectionRole( role ) ) );
        when( context.getElected( role ) ).thenReturn( myInstanceId );
        when( context.voteRequestForRole( new ElectionRole( role ) ) ).thenReturn( voteRequest );

          // Required for logging
        when( context.getLog( Mockito.<Class>any() ) ).thenReturn( NullLog.getInstance() );

        // When
        election.handle( context,
                Message.internal( performRoleElections ), holder );

        // Then
          // Make sure that we asked ourselves to vote for that role and that no timer was set
        verify( holder, times(1) ).offer( ArgumentMatchers.argThat( new MessageArgumentMatcher<ElectionMessage>()
                .onMessageType( ElectionMessage.vote ).withPayload( voteRequest ) ) );
        verify( context, times( 0 ) ).setTimeout( ArgumentMatchers.<String>any(), ArgumentMatchers.<Message>any() );
    }

    @Test
    public void electionShouldRemainLocalIfStartedBySingleInstanceWhichIsTheRoleHolder() throws Throwable
    {
        /*
         * Ensures that when an instance is alone in the cluster, elections for roles that it holds do not set
         * timeouts or try to reach other instances.
         */

        // Given
        ElectionContext context = mock( ElectionContext.class );
        ClusterContext clusterContextMock = mock( ClusterContext.class );

        when( clusterContextMock.getLog( ArgumentMatchers.<Class>any() ) ).thenReturn( NullLog.getInstance() );
        MessageHolder holder = mock( MessageHolder.class );

          // These mean the election can proceed normally, by us
        when( context.electionOk() ).thenReturn( true );
        when( context.isInCluster() ).thenReturn( true );
        when( context.isElector() ).thenReturn( true );

          // Like it says on the box, we are the only instance
        final InstanceId myInstanceId = new InstanceId( 1 );
        Map<InstanceId, URI> members = new HashMap<InstanceId, URI>();
        members.put( myInstanceId, URI.create( "ha://me" ) );
        when( context.getMembers() ).thenReturn( members );

          // Any role would do, just make sure we have it
        final String role = "master";
        ElectionContext.VoteRequest voteRequest = new ElectionContext.VoteRequest( role, 13 );
        when( context.getPossibleRoles() ).thenReturn(
                Collections.singletonList( new ElectionRole( role ) ) );
        when( context.getElected( role ) ).thenReturn( myInstanceId );
        when( context.voteRequestForRole( new ElectionRole( role ) ) ).thenReturn( voteRequest );

          // Required for logging
        when( context.getLog( Mockito.<Class>any() ) ).thenReturn( NullLog.getInstance() );

        // When
        election.handle( context,
                Message.internal( performRoleElections ), holder );

        // Then
          // Make sure that we asked ourselves to vote for that role and that no timer was set
        verify( holder, times(1) ).offer( ArgumentMatchers.argThat( new MessageArgumentMatcher<ElectionMessage>()
                .onMessageType( ElectionMessage.vote ).withPayload( voteRequest ) ) );
        verify( context, times( 0 ) ).setTimeout( ArgumentMatchers.<String>any(), ArgumentMatchers.<Message>any() );
    }

Replace Generic With Diamond HashMap<InstanceId,URI> with HashMap<> in method public electionShouldRemainLocalIfStartedBySingleInstanceWhichIsTheRoleHolder() : void from class org.neo4j.cluster.protocol.election.ElectionStateTest


    @Before
    public void setup()
    {
        Map<InstanceId, URI> members = new HashMap<>();
        for ( int i = 0; i < instanceIds.length; i++ )
        {
            members.put( instanceIds[i], URI.create( initialHosts[i] ) );
        }
        ClusterConfiguration config = new ClusterConfiguration( "clusterName", NullLogProvider.getInstance(), initialHosts );
        config.setMembers( members );

        context = mock( ClusterContext.class );

        Config configuration = mock( Config.class );
        when( configuration.get( ClusterSettings.max_acceptors ) ).thenReturn( 10 );

        when( context.getConfiguration() ).thenReturn( config );
        when( context.getMyId() ).thenReturn( instanceIds[0] );

        MultiPaxosContext context = new MultiPaxosContext( instanceIds[0], Iterables.iterable(
                        new ElectionRole( "coordinator" ) ), config,
                        Mockito.mock( Executor.class ), NullLogProvider.getInstance(),
                        Mockito.mock( ObjectInputStreamFactory.class), Mockito.mock( ObjectOutputStreamFactory.class),
                        Mockito.mock( AcceptorInstanceStore.class), Mockito.mock( Timeouts.class),
                        mock( ElectionCredentialsProvider.class ), configuration );

        toTest = context.getHeartbeatContext();
    }

    @Before
    public void setup()
    {
        Map<InstanceId, URI> members = new HashMap<InstanceId, URI>(  );
        for ( int i = 0; i < instanceIds.length; i++ )
        {
            members.put( instanceIds[i], URI.create( initialHosts[i] ) );
        }
        ClusterConfiguration config = new ClusterConfiguration( "clusterName", NullLogProvider.getInstance(), initialHosts );
        config.setMembers( members );

        context = mock( ClusterContext.class );

        Config configuration = mock( Config.class );
        when( configuration.get( ClusterSettings.max_acceptors ) ).thenReturn( 10 );

        when( context.getConfiguration() ).thenReturn( config );
        when( context.getMyId() ).thenReturn( instanceIds[0] );

        MultiPaxosContext context = new MultiPaxosContext( instanceIds[0], Iterables.iterable(
                        new ElectionRole( "coordinator" ) ), config,
                        Mockito.mock( Executor.class ), NullLogProvider.getInstance(),
                        Mockito.mock( ObjectInputStreamFactory.class), Mockito.mock( ObjectOutputStreamFactory.class),
                        Mockito.mock( AcceptorInstanceStore.class), Mockito.mock( Timeouts.class),
                        mock( ElectionCredentialsProvider.class ), configuration );

        toTest = context.getHeartbeatContext();
    }

Replace Generic With Diamond HashMap<InstanceId,URI> with HashMap<> in method public setup() : void from class org.neo4j.cluster.protocol.heartbeat.HeartbeatContextTest


    @Test
    public void testSuspicions()
    {
        InstanceId suspect = instanceIds[1];
        toTest.suspect( suspect );
        assertEquals( Collections.singleton( suspect ), toTest.getSuspicionsFor( context.getMyId() ) );
        assertEquals( Collections.singletonList( context.getMyId() ), toTest.getSuspicionsOf( suspect ) );
        // Being suspected by just one (us) is not enough
        assertFalse( toTest.isFailed( suspect ) );
        assertTrue( toTest.alive( suspect ) ); // This resets the suspicion above

        // If we suspect an instance twice in a row, it shouldn't change its status in any way.
        toTest.suspect( suspect );
        toTest.suspect( suspect );
        assertEquals( Collections.singleton( suspect ), toTest.getSuspicionsFor( context.getMyId() ) );
        assertEquals( Collections.singletonList( context.getMyId() ), toTest.getSuspicionsOf( suspect ) );
        assertFalse( toTest.isFailed( suspect ) );
        assertTrue( toTest.alive( suspect ) );

        // The other one sends suspicions too
        InstanceId newSuspiciousBastard = instanceIds[2];
        toTest.suspicions( newSuspiciousBastard, Collections.singleton( suspect ) );
        toTest.suspect( suspect );
        // Now two instances suspect it, it should be reported failed
        assertEquals( Collections.singleton( suspect ), toTest.getSuspicionsFor( context.getMyId() ) );
        assertEquals( Collections.singleton( suspect ), toTest.getSuspicionsFor( newSuspiciousBastard ) );
        List<InstanceId> suspiciousBastards = new ArrayList<>( 2 );
        suspiciousBastards.add( context.getMyId() );
        suspiciousBastards.add( newSuspiciousBastard );
        assertEquals( suspiciousBastards, toTest.getSuspicionsOf( suspect ) );
        assertTrue( toTest.isFailed( suspect ) );
        assertTrue( toTest.alive( suspect ) );
    }

    @Test
    public void testSuspicions()
    {
        InstanceId suspect = instanceIds[1];
        toTest.suspect( suspect );
        assertEquals( Collections.singleton( suspect ), toTest.getSuspicionsFor( context.getMyId() ) );
        assertEquals( Collections.singletonList( context.getMyId() ), toTest.getSuspicionsOf( suspect ) );
        // Being suspected by just one (us) is not enough
        assertFalse( toTest.isFailed( suspect ) );
        assertTrue( toTest.alive( suspect ) ); // This resets the suspicion above

        // If we suspect an instance twice in a row, it shouldn't change its status in any way.
        toTest.suspect( suspect );
        toTest.suspect( suspect );
        assertEquals( Collections.singleton( suspect ), toTest.getSuspicionsFor( context.getMyId() ) );
        assertEquals( Collections.singletonList( context.getMyId() ), toTest.getSuspicionsOf( suspect ) );
        assertFalse( toTest.isFailed( suspect ) );
        assertTrue( toTest.alive( suspect ) );

        // The other one sends suspicions too
        InstanceId newSuspiciousBastard = instanceIds[2];
        toTest.suspicions( newSuspiciousBastard, Collections.singleton( suspect ) );
        toTest.suspect( suspect );
        // Now two instances suspect it, it should be reported failed
        assertEquals( Collections.singleton( suspect ), toTest.getSuspicionsFor( context.getMyId() ) );
        assertEquals( Collections.singleton( suspect ), toTest.getSuspicionsFor( newSuspiciousBastard ) );
        List<InstanceId> suspiciousBastards = new ArrayList<InstanceId>( 2 );
        suspiciousBastards.add( context.getMyId() );
        suspiciousBastards.add( newSuspiciousBastard );
        assertEquals( suspiciousBastards, toTest.getSuspicionsOf( suspect ) );
        assertTrue( toTest.isFailed( suspect ) );
        assertTrue( toTest.alive( suspect ) );
    }

Replace Generic With Diamond ArrayList<InstanceId> with ArrayList<> in method public testSuspicions() : void from class org.neo4j.cluster.protocol.heartbeat.HeartbeatContextTest


    @Test
    public void shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat() throws Exception
    {
        final List<Message> sentOut = new LinkedList<>();

        // Given
        MessageHolder holder = mock( MessageHolder.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( invocation ->
        {
            sentOut.add( invocation.getArgument( 0 ) );
            return null;
        } ).when( holder ).offer( ArgumentMatchers.<Message<MessageType>>any() );

        ClusterContext mockContext = mock( ClusterContext.class );
        ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
        when( mockConfiguration.getMembers() ).thenReturn(
                new HashMap<InstanceId, URI>()
                {{
                        put( new InstanceId( 1 ), URI.create( "ha://1" ) );
                        put( new InstanceId( 2 ), URI.create( "ha://2" ) );
                    }}
        );
        when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );

        HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );

        Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
                .setHeader( Message.INSTANCE_ID, "2" ).setHeader( Message.FROM, "ha://2" );

        // WHEN
        processor.process( incoming );

        // THEN
        assertEquals( 1, sentOut.size() );
        assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
        assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
    }

    @Test
    public void shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat() throws Exception
    {
        final List<Message> sentOut = new LinkedList<Message>();

        // Given
        MessageHolder holder = mock( MessageHolder.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( invocation ->
        {
            sentOut.add( invocation.getArgument( 0 ) );
            return null;
        } ).when( holder ).offer( ArgumentMatchers.<Message<MessageType>>any() );

        ClusterContext mockContext = mock( ClusterContext.class );
        ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
        when( mockConfiguration.getMembers() ).thenReturn(
                new HashMap<InstanceId, URI>()
                {{
                        put( new InstanceId( 1 ), URI.create( "ha://1" ) );
                        put( new InstanceId( 2 ), URI.create( "ha://2" ) );
                    }}
        );
        when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );

        HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );

        Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
                .setHeader( Message.INSTANCE_ID, "2" ).setHeader( Message.FROM, "ha://2" );

        // WHEN
        processor.process( incoming );

        // THEN
        assertEquals( 1, sentOut.size() );
        assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
        assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
    }

Replace Generic With Diamond LinkedList<Message> with LinkedList<> in method public shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat() : void from class org.neo4j.cluster.protocol.heartbeat.HeartbeatIAmAliveProcessorTest


    @Test
    public void shouldRevertToInverseUriLookupIfNoInstanceIdHeader() throws Exception
    {
        final List<Message> sentOut = new LinkedList<>();
        String instance2UriString = "ha://2";

        // Given
        MessageHolder holder = mock( MessageHolder.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( invocation ->
        {
            sentOut.add( invocation.getArgument( 0 ) );
            return null;
        } ).when( holder ).offer( ArgumentMatchers.<Message<MessageType>>any() );

        ClusterContext mockContext = mock( ClusterContext.class );
        ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
        when( mockConfiguration.getIdForUri( URI.create( instance2UriString ) ) ).thenReturn( new InstanceId( 2 ) );
        when( mockConfiguration.getMembers() ).thenReturn(
                new HashMap<InstanceId, URI>()
                {{
                        put( new InstanceId( 1 ), URI.create( "ha://1" ) );
                        put( new InstanceId( 2 ), URI.create( "ha://2" ) );
                    }}
        );
        when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );

        HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );

        Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
                .setHeader( Message.FROM, instance2UriString );

        // WHEN
        processor.process( incoming );

        // THEN
        assertEquals( 1, sentOut.size() );
        assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
        assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
    }

    @Test
    public void shouldRevertToInverseUriLookupIfNoInstanceIdHeader() throws Exception
    {
        final List<Message> sentOut = new LinkedList<Message>();
        String instance2UriString = "ha://2";

        // Given
        MessageHolder holder = mock( MessageHolder.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( invocation ->
        {
            sentOut.add( invocation.getArgument( 0 ) );
            return null;
        } ).when( holder ).offer( ArgumentMatchers.<Message<MessageType>>any() );

        ClusterContext mockContext = mock( ClusterContext.class );
        ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
        when( mockConfiguration.getIdForUri( URI.create( instance2UriString ) ) ).thenReturn( new InstanceId( 2 ) );
        when( mockConfiguration.getMembers() ).thenReturn(
                new HashMap<InstanceId, URI>()
                {{
                        put( new InstanceId( 1 ), URI.create( "ha://1" ) );
                        put( new InstanceId( 2 ), URI.create( "ha://2" ) );
                    }}
        );
        when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );

        HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );

        Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
                .setHeader( Message.FROM, instance2UriString );

        // WHEN
        processor.process( incoming );

        // THEN
        assertEquals( 1, sentOut.size() );
        assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
        assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
    }

Replace Generic With Diamond LinkedList<Message> with LinkedList<> in method public shouldRevertToInverseUriLookupIfNoInstanceIdHeader() : void from class org.neo4j.cluster.protocol.heartbeat.HeartbeatIAmAliveProcessorTest


    @Test
    public void testNoSnapshotRequestIfCoordinatorInExistingCluster() throws Throwable
    {
        Map<InstanceId, URI> extraMember = new HashMap<>();
        URI other = URI.create( "cluster://other");
        extraMember.put( new InstanceId( 2 ), other );
        baseNoSendTest( extraMember );
    }

    @Test
    public void testNoSnapshotRequestIfCoordinatorInExistingCluster() throws Throwable
    {
        Map<InstanceId, URI> extraMember = new HashMap<InstanceId, URI>();
        URI other = URI.create( "cluster://other");
        extraMember.put( new InstanceId( 2 ), other );
        baseNoSendTest( extraMember );
    }

Replace Generic With Diamond HashMap<InstanceId,URI> with HashMap<> in method public testNoSnapshotRequestIfCoordinatorInExistingCluster() : void from class org.neo4j.cluster.protocol.snapshot.SnapshotStateTest


    @Test
    public void testNoSnapshotRequestIfOnlyMember() throws Throwable
    {
        Map<InstanceId, URI> extraMember = new HashMap<>();
        baseNoSendTest( extraMember );
    }

    @Test
    public void testNoSnapshotRequestIfOnlyMember() throws Throwable
    {
        Map<InstanceId, URI> extraMember = new HashMap<InstanceId, URI>();
        baseNoSendTest( extraMember );
    }

Replace Generic With Diamond HashMap<InstanceId,URI> with HashMap<> in method public testNoSnapshotRequestIfOnlyMember() : void from class org.neo4j.cluster.protocol.snapshot.SnapshotStateTest


    public void baseNoSendTest( Map<InstanceId,URI> extraMembers ) throws Throwable
    {
        URI me = URI.create( "cluster://me" );

        Map<InstanceId,URI> members = new HashMap<>();
        final InstanceId myId = new InstanceId( 1 );
        members.put( myId, me );
        members.putAll( extraMembers );

        ClusterConfiguration clusterConfiguration = mock( ClusterConfiguration.class );
        when( clusterConfiguration.getMembers() ).thenReturn( members );
        when( clusterConfiguration.getElected( ClusterConfiguration.COORDINATOR ) ).thenReturn( myId );
        when( clusterConfiguration.getUriForId( myId ) ).thenReturn( me );

        ClusterContext clusterContext = mock( ClusterContext.class );
        when( clusterContext.getConfiguration() ).thenReturn( clusterConfiguration );
        when( clusterContext.getMyId() ).thenReturn( myId );

        SnapshotContext context = mock( SnapshotContext.class );
        when( context.getClusterContext() ).thenReturn( clusterContext );
        when( context.getSnapshotProvider() ).thenReturn( mock( SnapshotProvider.class ) );

        Message<SnapshotMessage> message = Message.to( SnapshotMessage.refreshSnapshot, me );

        MessageHolder outgoing = mock( MessageHolder.class );

        SnapshotState newState = (SnapshotState) SnapshotState.ready.handle( context, message, outgoing );
        assertThat( newState, equalTo( SnapshotState.ready ) );
        Mockito.verifyZeroInteractions( outgoing );
    }

    public void baseNoSendTest( Map<InstanceId,URI> extraMembers ) throws Throwable
    {
        URI me = URI.create( "cluster://me" );

        Map<InstanceId,URI> members = new HashMap<InstanceId,URI>();
        final InstanceId myId = new InstanceId( 1 );
        members.put( myId, me );
        members.putAll( extraMembers );

        ClusterConfiguration clusterConfiguration = mock( ClusterConfiguration.class );
        when( clusterConfiguration.getMembers() ).thenReturn( members );
        when( clusterConfiguration.getElected( ClusterConfiguration.COORDINATOR ) ).thenReturn( myId );
        when( clusterConfiguration.getUriForId( myId ) ).thenReturn( me );

        ClusterContext clusterContext = mock( ClusterContext.class );
        when( clusterContext.getConfiguration() ).thenReturn( clusterConfiguration );
        when( clusterContext.getMyId() ).thenReturn( myId );

        SnapshotContext context = mock( SnapshotContext.class );
        when( context.getClusterContext() ).thenReturn( clusterContext );
        when( context.getSnapshotProvider() ).thenReturn( mock( SnapshotProvider.class ) );

        Message<SnapshotMessage> message = Message.to( SnapshotMessage.refreshSnapshot, me );

        MessageHolder outgoing = mock( MessageHolder.class );

        SnapshotState newState = (SnapshotState) SnapshotState.ready.handle( context, message, outgoing );
        assertThat( newState, equalTo( SnapshotState.ready ) );
        Mockito.verifyZeroInteractions( outgoing );
    }

Replace Generic With Diamond HashMap<InstanceId,URI> with HashMap<> in method public baseNoSendTest(extraMembers Map<InstanceId,URI>) : void from class org.neo4j.cluster.protocol.snapshot.SnapshotStateTest


    @Override
    protected void shutdown( boolean normal )
    {
        if ( server != null )
        {
            try
            {
                server.stop();
                server.shutdown();
            }
            catch ( Throwable throwable )
            {
                throw new RuntimeException( throwable );
            }
        }
        new Thread( () -> {
            try
            {
                Thread.sleep( 100 );
            }
            catch ( InterruptedException e )
            {
                Thread.interrupted();
            }
            shutdownProcess();
        } ).start();
    }

    @Override
    protected void shutdown( boolean normal )
    {
        if ( server != null )
        {
            try
            {
                server.stop();
                server.shutdown();
            }
            catch ( Throwable throwable )
            {
                throw new RuntimeException( throwable );
            }
        }
        new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    Thread.sleep( 100 );
                }
                catch ( InterruptedException e )
                {
                    Thread.interrupted();
                }
                shutdownProcess();
            }
        }.start();
    }

Replace Anonymous With Lambda org.neo4j.com.MadeUpServerProcess.shutdown.start.new Thread with () -> {tryThread.sleep(100); in method protected shutdown(normal boolean) : void from class org.neo4j.com.MadeUpServerProcess


    public ClusterMemberInfo[] getClusterInfo()
    {
        List<ClusterMemberInfo> clusterMemberInfos = new ArrayList<>();
        Function<Object,String> nullSafeToString = from -> from == null ? "" : from.toString();
        for ( ClusterMember clusterMember : memberInfo.getMembers() )
        {
            ClusterMemberInfo clusterMemberInfo = new ClusterMemberInfo( clusterMember.getInstanceId().toString(),
                    clusterMember.getHAUri() != null, clusterMember.isAlive(), clusterMember.getHARole(),
                    asArray( String.class, map( nullSafeToString, clusterMember.getRoleURIs() ) ),
                    asArray( String.class, map( nullSafeToString, clusterMember.getRoles() ) ) );
            clusterMemberInfos.add( clusterMemberInfo );
        }

        return clusterMemberInfos.toArray( new ClusterMemberInfo[clusterMemberInfos.size()] );
    }

    public ClusterMemberInfo[] getClusterInfo()
    {
        List<ClusterMemberInfo> clusterMemberInfos = new ArrayList<ClusterMemberInfo>(  );
        Function<Object,String> nullSafeToString = from -> from == null ? "" : from.toString();
        for ( ClusterMember clusterMember : memberInfo.getMembers() )
        {
            ClusterMemberInfo clusterMemberInfo = new ClusterMemberInfo( clusterMember.getInstanceId().toString(),
                    clusterMember.getHAUri() != null, clusterMember.isAlive(), clusterMember.getHARole(),
                    asArray( String.class, map( nullSafeToString, clusterMember.getRoleURIs() ) ),
                    asArray( String.class, map( nullSafeToString, clusterMember.getRoles() ) ) );
            clusterMemberInfos.add( clusterMemberInfo );
        }

        return clusterMemberInfos.toArray( new ClusterMemberInfo[clusterMemberInfos.size()] );
    }

Replace Generic With Diamond ArrayList<ClusterMemberInfo> with ArrayList<> in method public getClusterInfo() : ClusterMemberInfo[] from class org.neo4j.kernel.ha.management.HighlyAvailableKernelData


    private boolean isSuccessful( ReplicationContext context )
    {
        try
        {
            context.future.get();
            return true;
        }
        catch ( InterruptedException | CancellationException e )
        {
            return false;
        }
        catch ( ExecutionException e )
        {
            context.throwable = e.getCause();
            slaveCommitFailureLogger.error( "Slave " + context.slave.getServerId() + ": Replication commit threw" +
                                            (context.throwable instanceof ComException ? " communication" : "") +
                                            " exception:", context.throwable );
            return false;
        }
    }

    private boolean isSuccessful( ReplicationContext context )
    {
        try
        {
            context.future.get();
            return true;
        }
        catch ( InterruptedException e )
        {
            return false;
        }
        catch ( ExecutionException e )
        {
            context.throwable = e.getCause();
            slaveCommitFailureLogger.error( "Slave " + context.slave.getServerId() + ": Replication commit threw" +
                                            (context.throwable instanceof ComException ? " communication" : "") +
                                            " exception:", context.throwable );
            return false;
        }
        catch ( CancellationException e )
        {
            return false;
        }
    }

Merge Catch [catch(InterruptedException e), catch(CancellationException e)] to catch(InterruptedException|CancellationException e) in method private isSuccessful(context ReplicationContext) : boolean from class org.neo4j.kernel.ha.transaction.TransactionPropagator


    @Test
    public void testCompareToDifferentTxId() throws Exception
    {
        DefaultElectionCredentials highTxId =
                new DefaultElectionCredentials( 3, 12, false );

        DefaultElectionCredentials mediumTxId =
                new DefaultElectionCredentials( 1, 11, false );

        DefaultElectionCredentials lowTxId =
                new DefaultElectionCredentials( 2, 10, false );

        List<ElectionCredentials> toSort = new ArrayList<>( 2 );
        toSort.add( mediumTxId);
        toSort.add( highTxId);
        toSort.add( lowTxId );
        Collections.sort( toSort );
        assertEquals(toSort.get( 0 ), lowTxId);
        assertEquals(toSort.get( 1 ), mediumTxId);
        assertEquals(toSort.get( 2 ), highTxId);
    }

    @Test
    public void testCompareToDifferentTxId() throws Exception
    {
        DefaultElectionCredentials highTxId =
                new DefaultElectionCredentials( 3, 12, false );

        DefaultElectionCredentials mediumTxId =
                new DefaultElectionCredentials( 1, 11, false );

        DefaultElectionCredentials lowTxId =
                new DefaultElectionCredentials( 2, 10, false );

        List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 );
        toSort.add( mediumTxId);
        toSort.add( highTxId);
        toSort.add( lowTxId );
        Collections.sort( toSort );
        assertEquals(toSort.get( 0 ), lowTxId);
        assertEquals(toSort.get( 1 ), mediumTxId);
        assertEquals(toSort.get( 2 ), highTxId);
    }

Replace Generic With Diamond ArrayList<ElectionCredentials> with ArrayList<> in method public testCompareToDifferentTxId() : void from class org.neo4j.ha.DefaultElectionCredentialsTest


    @Test
    public void testCompareToSameTxId() throws Exception
    {
        // Lower id means higher priority
        DefaultElectionCredentials highSameTxId = new DefaultElectionCredentials( 1, 10, false );

        DefaultElectionCredentials lowSameTxId = new DefaultElectionCredentials( 2, 10, false );

        List<ElectionCredentials> toSort = new ArrayList<>( 2 );
        toSort.add( highSameTxId );
        toSort.add(lowSameTxId);
        Collections.sort( toSort );
        assertEquals(toSort.get( 0 ), lowSameTxId);
        assertEquals(toSort.get( 1 ), highSameTxId);
    }

    @Test
    public void testCompareToSameTxId() throws Exception
    {
        // Lower id means higher priority
        DefaultElectionCredentials highSameTxId = new DefaultElectionCredentials( 1, 10, false );

        DefaultElectionCredentials lowSameTxId = new DefaultElectionCredentials( 2, 10, false );

        List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 );
        toSort.add( highSameTxId );
        toSort.add(lowSameTxId);
        Collections.sort( toSort );
        assertEquals(toSort.get( 0 ), lowSameTxId);
        assertEquals(toSort.get( 1 ), highSameTxId);
    }

Replace Generic With Diamond ArrayList<ElectionCredentials> with ArrayList<> in method public testCompareToSameTxId() : void from class org.neo4j.ha.DefaultElectionCredentialsTest


    @Test
    public void testExistingMasterLosesWhenComparedToHigherTxIdHigherId()
    {
        DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 1, 10, true );
        DefaultElectionCredentials incoming = new DefaultElectionCredentials( 2, 11, false );

        List<ElectionCredentials> toSort = new ArrayList<>( 2 );
        toSort.add( currentMaster );
        toSort.add( incoming );
        Collections.sort( toSort );

        assertEquals( toSort.get( 0 ), currentMaster );
        assertEquals( toSort.get( 1 ), incoming );
    }

    @Test
    public void testExistingMasterLosesWhenComparedToHigherTxIdHigherId()
    {
        DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 1, 10, true );
        DefaultElectionCredentials incoming = new DefaultElectionCredentials( 2, 11, false );

        List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 );
        toSort.add( currentMaster );
        toSort.add( incoming );
        Collections.sort( toSort );

        assertEquals( toSort.get( 0 ), currentMaster );
        assertEquals( toSort.get( 1 ), incoming );
    }

Replace Generic With Diamond ArrayList<ElectionCredentials> with ArrayList<> in method public testExistingMasterLosesWhenComparedToHigherTxIdHigherId() : void from class org.neo4j.ha.DefaultElectionCredentialsTest


    @Test
    public void testExistingMasterWinsWhenComparedToLowerIdSameTxId()
    {
        DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 2, 10, true );
        DefaultElectionCredentials incoming = new DefaultElectionCredentials( 1, 10, false );

        List<ElectionCredentials> toSort = new ArrayList<>( 2 );
        toSort.add( currentMaster );
        toSort.add( incoming );
        Collections.sort( toSort );

        assertEquals( toSort.get( 0 ), incoming );
        assertEquals( toSort.get( 1 ), currentMaster );
    }

    @Test
    public void testExistingMasterWinsWhenComparedToLowerIdSameTxId()
    {
        DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 2, 10, true );
        DefaultElectionCredentials incoming = new DefaultElectionCredentials( 1, 10, false );

        List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 );
        toSort.add( currentMaster );
        toSort.add( incoming );
        Collections.sort( toSort );

        assertEquals( toSort.get( 0 ), incoming );
        assertEquals( toSort.get( 1 ), currentMaster );
    }

Replace Generic With Diamond ArrayList<ElectionCredentials> with ArrayList<> in method public testExistingMasterWinsWhenComparedToLowerIdSameTxId() : void from class org.neo4j.ha.DefaultElectionCredentialsTest


    @Test
    public void testExistingMasterWinsWhenComparedToHigherIdLowerTxId()
    {
        DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 1, 10, true );
        DefaultElectionCredentials incoming = new DefaultElectionCredentials( 2, 9, false );

        List<ElectionCredentials> toSort = new ArrayList<>( 2 );
        toSort.add( currentMaster );
        toSort.add( incoming );
        Collections.sort( toSort );

        assertEquals( toSort.get( 0 ), incoming );
        assertEquals( toSort.get( 1 ), currentMaster );
    }

    @Test
    public void testExistingMasterWinsWhenComparedToHigherIdLowerTxId()
    {
        DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 1, 10, true );
        DefaultElectionCredentials incoming = new DefaultElectionCredentials( 2, 9, false );

        List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 );
        toSort.add( currentMaster );
        toSort.add( incoming );
        Collections.sort( toSort );

        assertEquals( toSort.get( 0 ), incoming );
        assertEquals( toSort.get( 1 ), currentMaster );
    }

Replace Generic With Diamond ArrayList<ElectionCredentials> with ArrayList<> in method public testExistingMasterWinsWhenComparedToHigherIdLowerTxId() : void from class org.neo4j.ha.DefaultElectionCredentialsTest


    @Test
    public void onlyOneNonFullBlock() throws IOException
    {
        byte[] bytes = new byte[255];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte byteValue = 5;
        int intValue = 1234;
        long longValue = 574853;
        float floatValue = 304985.5f;
        double doubleValue = 48493.22d;
        final byte[] bytesValue = new byte[] { 1, 5, 2, 6, 3 };
        buffer.put( byteValue );
        buffer.putInt( intValue );
        buffer.putLong( longValue );
        buffer.putFloat( floatValue );
        buffer.putDouble( doubleValue );
        buffer.put( bytesValue, bytesValue.length );
        buffer.close();

        ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes );
        assertEquals( 30, verificationBuffer.get() );
        assertEquals( byteValue, verificationBuffer.get() );
        assertEquals( intValue, verificationBuffer.getInt() );
        assertEquals( longValue, verificationBuffer.getLong() );
        assertEquals( floatValue, verificationBuffer.getFloat(), 0.0 );
        assertEquals( doubleValue, verificationBuffer.getDouble(), 0.0 );
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<>( bytesValue ) );
    }

    @Test
    public void onlyOneNonFullBlock() throws IOException
    {
        byte[] bytes = new byte[255];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte byteValue = 5;
        int intValue = 1234;
        long longValue = 574853;
        float floatValue = 304985.5f;
        double doubleValue = 48493.22d;
        final byte[] bytesValue = new byte[] { 1, 5, 2, 6, 3 };
        buffer.put( byteValue );
        buffer.putInt( intValue );
        buffer.putLong( longValue );
        buffer.putFloat( floatValue );
        buffer.putDouble( doubleValue );
        buffer.put( bytesValue, bytesValue.length );
        buffer.close();

        ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes );
        assertEquals( 30, verificationBuffer.get() );
        assertEquals( byteValue, verificationBuffer.get() );
        assertEquals( intValue, verificationBuffer.getInt() );
        assertEquals( longValue, verificationBuffer.getLong() );
        assertEquals( floatValue, verificationBuffer.getFloat(), 0.0 );
        assertEquals( doubleValue, verificationBuffer.getDouble(), 0.0 );
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) );
    }

Replace Generic With Diamond ArrayMatches<byte[]> with ArrayMatches<> in method public onlyOneNonFullBlock() : void from class org.neo4j.ha.TestBlockLogBuffer


    @Test
    public void readOnlyOneNonFullBlock() throws IOException
    {
        byte[] bytes = new byte[255];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte byteValue = 5;
        int intValue = 1234;
        long longValue = 574853;
        float floatValue = 304985.5f;
        double doubleValue = 48493.22d;
        final byte[] bytesValue = new byte[] { 1, 5, 2, 6, 3 };
        buffer.put( byteValue );
        buffer.putInt( intValue );
        buffer.putLong( longValue );
        buffer.putFloat( floatValue );
        buffer.putDouble( doubleValue );
        buffer.put( bytesValue, bytesValue.length );
        buffer.close();

        ReadableByteChannel reader = new BlockLogReader( wrappedBuffer );
        ByteBuffer verificationBuffer = ByteBuffer.wrap( new byte[1000] );
        reader.read( verificationBuffer );
        verificationBuffer.flip();
        assertEquals( byteValue, verificationBuffer.get() );
        assertEquals( intValue, verificationBuffer.getInt() );
        assertEquals( longValue, verificationBuffer.getLong() );
        assertEquals( floatValue, verificationBuffer.getFloat(), 0.0 );
        assertEquals( doubleValue, verificationBuffer.getDouble(), 0.0 );
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<>( bytesValue ) );
    }

    @Test
    public void readOnlyOneNonFullBlock() throws IOException
    {
        byte[] bytes = new byte[255];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte byteValue = 5;
        int intValue = 1234;
        long longValue = 574853;
        float floatValue = 304985.5f;
        double doubleValue = 48493.22d;
        final byte[] bytesValue = new byte[] { 1, 5, 2, 6, 3 };
        buffer.put( byteValue );
        buffer.putInt( intValue );
        buffer.putLong( longValue );
        buffer.putFloat( floatValue );
        buffer.putDouble( doubleValue );
        buffer.put( bytesValue, bytesValue.length );
        buffer.close();

        ReadableByteChannel reader = new BlockLogReader( wrappedBuffer );
        ByteBuffer verificationBuffer = ByteBuffer.wrap( new byte[1000] );
        reader.read( verificationBuffer );
        verificationBuffer.flip();
        assertEquals( byteValue, verificationBuffer.get() );
        assertEquals( intValue, verificationBuffer.getInt() );
        assertEquals( longValue, verificationBuffer.getLong() );
        assertEquals( floatValue, verificationBuffer.getFloat(), 0.0 );
        assertEquals( doubleValue, verificationBuffer.getDouble(), 0.0 );
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) );
    }

Replace Generic With Diamond ArrayMatches<byte[]> with ArrayMatches<> in method public readOnlyOneNonFullBlock() : void from class org.neo4j.ha.TestBlockLogBuffer


    @Test
    public void onlyOneFullBlock() throws Exception
    {
        byte[] bytes = new byte[256];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte[] bytesValue = new byte[255];
        bytesValue[0] = 1;
        bytesValue[254] = -1;
        buffer.put( bytesValue, bytesValue.length );
        buffer.close();

        ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes );
        assertEquals( (byte) 255, verificationBuffer.get() );
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<>( bytesValue ) );
    }

    @Test
    public void onlyOneFullBlock() throws Exception
    {
        byte[] bytes = new byte[256];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte[] bytesValue = new byte[255];
        bytesValue[0] = 1;
        bytesValue[254] = -1;
        buffer.put( bytesValue, bytesValue.length );
        buffer.close();

        ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes );
        assertEquals( (byte) 255, verificationBuffer.get() );
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) );
    }

Replace Generic With Diamond ArrayMatches<byte[]> with ArrayMatches<> in method public onlyOneFullBlock() : void from class org.neo4j.ha.TestBlockLogBuffer


    @Test
    public void readOnlyOneFullBlock() throws Exception
    {
        byte[] bytes = new byte[256];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte[] bytesValue = new byte[255];
        bytesValue[0] = 1;
        bytesValue[254] = -1;
        buffer.put( bytesValue, bytesValue.length );
        buffer.close();

        ReadableByteChannel reader = new BlockLogReader( wrappedBuffer );
        ByteBuffer verificationBuffer = ByteBuffer.wrap( new byte[1000] );
        reader.read( verificationBuffer );
        verificationBuffer.flip();
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<>( bytesValue ) );
    }

    @Test
    public void readOnlyOneFullBlock() throws Exception
    {
        byte[] bytes = new byte[256];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte[] bytesValue = new byte[255];
        bytesValue[0] = 1;
        bytesValue[254] = -1;
        buffer.put( bytesValue, bytesValue.length );
        buffer.close();

        ReadableByteChannel reader = new BlockLogReader( wrappedBuffer );
        ByteBuffer verificationBuffer = ByteBuffer.wrap( new byte[1000] );
        reader.read( verificationBuffer );
        verificationBuffer.flip();
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) );
    }

Replace Generic With Diamond ArrayMatches<byte[]> with ArrayMatches<> in method public readOnlyOneFullBlock() : void from class org.neo4j.ha.TestBlockLogBuffer


    @Test
    public void canWriteLargestAtomAfterFillingBuffer() throws Exception
    {
        byte[] bytes = new byte[300];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte[] bytesValue = new byte[255];
        bytesValue[0] = 1;
        bytesValue[254] = -1;
        long longValue = 123456;
        buffer.put( bytesValue, bytesValue.length );
        buffer.putLong( longValue );
        buffer.close();

        ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes );
        assertEquals( (byte) 0, verificationBuffer.get() );
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<>( bytesValue ) );
        assertEquals( (byte) 8, verificationBuffer.get() );
        assertEquals( longValue, verificationBuffer.getLong() );
    }

    @Test
    public void canWriteLargestAtomAfterFillingBuffer() throws Exception
    {
        byte[] bytes = new byte[300];
        ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes );
        wrappedBuffer.resetWriterIndex();
        BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );

        byte[] bytesValue = new byte[255];
        bytesValue[0] = 1;
        bytesValue[254] = -1;
        long longValue = 123456;
        buffer.put( bytesValue, bytesValue.length );
        buffer.putLong( longValue );
        buffer.close();

        ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes );
        assertEquals( (byte) 0, verificationBuffer.get() );
        byte[] actualBytes = new byte[bytesValue.length];
        verificationBuffer.get( actualBytes );
        assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) );
        assertEquals( (byte) 8, verificationBuffer.get() );
        assertEquals( longValue, verificationBuffer.getLong() );
    }

Replace Generic With Diamond ArrayMatches<byte[]> with ArrayMatches<> in method public canWriteLargestAtomAfterFillingBuffer() : void from class org.neo4j.ha.TestBlockLogBuffer


    public static Future<LegacyDatabase> start( String classpath, File storeDir, Map<String, String> config )
            throws Exception
    {
        List<String> args = new ArrayList<>();
        args.add( storeDir.getAbsolutePath() );
        int rmiPort = 7000 + parseInt( config.get( "ha.server_id" ) );
        args.add( "" + rmiPort );
        args.addAll( asList( new Args( config ).asArgs() ) );
        final Process process = execJava( appendNecessaryTestClasses( classpath ),
                LegacyDatabaseImpl.class.getName(), args.toArray( new String[0] ) );
        new ProcessStreamHandler( process, false ).launch();

        final RmiLocation rmiLocation = rmiLocation( rmiPort );
        ExecutorService executor = newSingleThreadExecutor();
        Future<LegacyDatabase> future = executor.submit( () ->
        {
            long endTime = currentTimeMillis() + SECONDS.toMillis( 10000 );
            while ( currentTimeMillis() < endTime )
            {
                try
                {
                    return (LegacyDatabase) rmiLocation.getBoundObject();
                }
                catch ( RemoteException e )
                {
                    // OK
                    sleep( 100 );
                }
            }
            process.destroy();
            throw new IllegalStateException( "Couldn't get remote to legacy database" );
        } );
        executor.shutdown();
        return future;
    }

    public static Future<LegacyDatabase> start( String classpath, File storeDir, Map<String, String> config )
            throws Exception
    {
        List<String> args = new ArrayList<String>();
        args.add( storeDir.getAbsolutePath() );
        int rmiPort = 7000 + parseInt( config.get( "ha.server_id" ) );
        args.add( "" + rmiPort );
        args.addAll( asList( new Args( config ).asArgs() ) );
        final Process process = execJava( appendNecessaryTestClasses( classpath ),
                LegacyDatabaseImpl.class.getName(), args.toArray( new String[0] ) );
        new ProcessStreamHandler( process, false ).launch();

        final RmiLocation rmiLocation = rmiLocation( rmiPort );
        ExecutorService executor = newSingleThreadExecutor();
        Future<LegacyDatabase> future = executor.submit( () ->
        {
            long endTime = currentTimeMillis() + SECONDS.toMillis( 10000 );
            while ( currentTimeMillis() < endTime )
            {
                try
                {
                    return (LegacyDatabase) rmiLocation.getBoundObject();
                }
                catch ( RemoteException e )
                {
                    // OK
                    sleep( 100 );
                }
            }
            process.destroy();
            throw new IllegalStateException( "Couldn't get remote to legacy database" );
        } );
        executor.shutdown();
        return future;
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public start(classpath String, storeDir File, config Map<String,String>) : Future<LegacyDatabase> from class org.neo4j.ha.upgrade.LegacyDatabaseImpl


    public static String assembleClassPathFromPackage( File directory )
    {
        List<File> jarFiles = new ArrayList<>();
        FileFilter jarFilter = file -> file.isFile() && file.getName().endsWith( ".jar" );
        gatherFiles( jarFiles, directory, jarFilter );

        StringBuilder classpath = new StringBuilder();
        for ( File file : jarFiles )
        {
            classpath.append( classpath.length() > 0 ? File.pathSeparator : "" ).append( file.getAbsolutePath() );
        }
        return classpath.toString();
    }

    public static String assembleClassPathFromPackage( File directory )
    {
        List<File> jarFiles = new ArrayList<File>();
        FileFilter jarFilter = file -> file.isFile() && file.getName().endsWith( ".jar" );
        gatherFiles( jarFiles, directory, jarFilter );

        StringBuilder classpath = new StringBuilder();
        for ( File file : jarFiles )
        {
            classpath.append( classpath.length() > 0 ? File.pathSeparator : "" ).append( file.getAbsolutePath() );
        }
        return classpath.toString();
    }

Replace Generic With Diamond ArrayList<File> with ArrayList<> in method public assembleClassPathFromPackage(directory File) : String from class org.neo4j.ha.upgrade.Utils


    public static List<File> unzip( File zipFile, File targetDir ) throws IOException
    {
        List<File> files = new ArrayList<>();
        ZipFile zip = new ZipFile( zipFile );
        try
        {
            zip = new ZipFile( zipFile );
            for ( ZipEntry entry : Collections.list( zip.entries() ) )
            {
                File target = new File( targetDir, entry.getName() );
                target.getParentFile().mkdirs();
                if ( !entry.isDirectory() )
                {
                    InputStream input = zip.getInputStream( entry );
                    try
                    {
                        copyInputStreamToFile( input, target );
                        files.add( target );
                    }
                    finally
                    {
                        closeQuietly( input );
                    }
                }
            }
            return files;
        }
        finally
        {
            zip.close();
        }
    }

    public static List<File> unzip( File zipFile, File targetDir ) throws IOException
    {
        List<File> files = new ArrayList<File>();
        ZipFile zip = new ZipFile( zipFile );
        try
        {
            zip = new ZipFile( zipFile );
            for ( ZipEntry entry : Collections.list( zip.entries() ) )
            {
                File target = new File( targetDir, entry.getName() );
                target.getParentFile().mkdirs();
                if ( !entry.isDirectory() )
                {
                    InputStream input = zip.getInputStream( entry );
                    try
                    {
                        copyInputStreamToFile( input, target );
                        files.add( target );
                    }
                    finally
                    {
                        closeQuietly( input );
                    }
                }
            }
            return files;
        }
        finally
        {
            zip.close();
        }
    }

Replace Generic With Diamond ArrayList<File> with ArrayList<> in method public unzip(zipFile File, targetDir File) : List<File> from class org.neo4j.ha.upgrade.Utils


    public static Process execJava( String classPath, String mainClass, String... args ) throws Exception
    {
        List<String> allArgs = new ArrayList<>( asList( "java", "-cp", classPath, mainClass ) );
        allArgs.addAll( asList( args ) );
        return getRuntime().exec( allArgs.toArray( new String[0] ) );
    }

    public static Process execJava( String classPath, String mainClass, String... args ) throws Exception
    {
        List<String> allArgs = new ArrayList<String>( asList( "java", "-cp", classPath, mainClass ) );
        allArgs.addAll( asList( args ) );
        return getRuntime().exec( allArgs.toArray( new String[0] ) );
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public execJava(classPath String, mainClass String, args String...) : Process from class org.neo4j.ha.upgrade.Utils


    private void startMeasuringTheGap( final AtomicInteger good, final AtomicInteger bad, final AtomicInteger ugly,
            final AtomicBoolean halter, final AtomicLong[] highIdNodes, final GraphDatabaseAPI db )
    {
        new Thread( () -> {
            while ( !halter.get() )
            {
                for ( int i = 0; i < numberOfIndexes; i++ )
                {
                    long targetNodeId = highIdNodes[i].get();
                    if ( targetNodeId == 0 )
                    {
                        continue;
                    }

                    try ( Transaction tx = db.beginTx() )
                    {
                        Node nodeFromStorePOV = null;
                        long nodeId = targetNodeId;
                        while ( nodeFromStorePOV == null && !halter.get() )
                        {
                            try
                            {
                                nodeFromStorePOV = db.getNodeById( nodeId );
                            }
                            catch ( NotFoundException e )
                            {   // Keep on spinning
                                nodeId = max( nodeId - 1, 0 );
                                try
                                {
                                    Thread.sleep( 10 );
                                }
                                catch ( InterruptedException e1 )
                                {
                                    throw new RuntimeException( e1 );
                                }
                            }
                        }

                        Node nodeFromIndexPOV = db.findNode( label( i ), key( i ), nodeId );
                        tx.success();
                        if ( nodeFromIndexPOV != null )
                        {
                            good.incrementAndGet();
                        }
                        else
                        {
                            bad.incrementAndGet();
                        }
                        if ( nodeId != targetNodeId )
                        {
                            ugly.incrementAndGet();
                        }
                    }
                }
            }
        } ).start();
    }

    private void startMeasuringTheGap( final AtomicInteger good, final AtomicInteger bad, final AtomicInteger ugly,
            final AtomicBoolean halter, final AtomicLong[] highIdNodes, final GraphDatabaseAPI db )
    {
        new Thread()
        {
            @Override
            public void run()
            {
                while ( !halter.get() )
                {
                    for ( int i = 0; i < numberOfIndexes; i++ )
                    {
                        long targetNodeId = highIdNodes[i].get();
                        if ( targetNodeId == 0 )
                        {
                            continue;
                        }

                        try ( Transaction tx = db.beginTx() )
                        {
                            Node nodeFromStorePOV = null;
                            long nodeId = targetNodeId;
                            while ( nodeFromStorePOV == null && !halter.get() )
                            {
                                try
                                {
                                    nodeFromStorePOV = db.getNodeById( nodeId );
                                }
                                catch ( NotFoundException e )
                                {   // Keep on spinning
                                    nodeId = max( nodeId - 1, 0 );
                                    try
                                    {
                                        Thread.sleep( 10 );
                                    }
                                    catch ( InterruptedException e1 )
                                    {
                                        throw new RuntimeException( e1 );
                                    }
                                }
                            }

                            Node nodeFromIndexPOV = db.findNode( label( i ), key( i ), nodeId );
                            tx.success();
                            if ( nodeFromIndexPOV != null )
                            {
                                good.incrementAndGet();
                            }
                            else
                            {
                                bad.incrementAndGet();
                            }
                            if ( nodeId != targetNodeId )
                            {
                                ugly.incrementAndGet();
                            }
                        }
                    }
                }
            }
        }.start();
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.MeasureUpdatePullingRecordAndIndexGap.startMeasuringTheGap.start.new Thread with () -> {while(!halter.get()){for(int i=0; i < numberOfIndexes; i++){long targetNodeId=highIdNodes[i].get(); in method private startMeasuringTheGap(good AtomicInteger, bad AtomicInteger, ugly AtomicInteger, halter AtomicBoolean, highIdNodes AtomicLong[], db GraphDatabaseAPI) : void from class org.neo4j.kernel.ha.MeasureUpdatePullingRecordAndIndexGap


    private void startCatchingUp( final GraphDatabaseAPI db, final AtomicBoolean halter, final CountDownLatch endLatch )
    {
        new Thread( () -> {
            try
            {
                while ( !halter.get() )
                {
                    try
                    {
                        db.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();
                    }
                    catch ( InterruptedException e )
                    {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException( e );
                    }
                }
            }
            finally
            {
                endLatch.countDown();
            }
        } ).start();
    }

    private void startCatchingUp( final GraphDatabaseAPI db, final AtomicBoolean halter, final CountDownLatch endLatch )
    {
        new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    while ( !halter.get() )
                    {
                        try
                        {
                            db.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();
                        }
                        catch ( InterruptedException e )
                        {
                            Thread.currentThread().interrupt();
                            throw new RuntimeException( e );
                        }
                    }
                }
                finally
                {
                    endLatch.countDown();
                }
            }
        }.start();
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.MeasureUpdatePullingRecordAndIndexGap.startCatchingUp.start.new Thread with () -> {trywhile(!halter.get()){trydb.getDependencyResolver().resolveDependency(UpdatePuller.class).pullUpdates(); in method private startCatchingUp(db GraphDatabaseAPI, halter AtomicBoolean, endLatch CountDownLatch) : void from class org.neo4j.kernel.ha.MeasureUpdatePullingRecordAndIndexGap


    private void startLoadOn( final GraphDatabaseService db, final AtomicBoolean halter, final AtomicLong[] highIdNodes,
            final CountDownLatch endLatch )
    {
        for ( int i = 0; i < numberOfIndexes; i++ )
        {
            final int x = i;
            new Thread( () -> {
                try
                {
                    while ( !halter.get() )
                    {
                        long nodeId;
                        try ( Transaction tx = db.beginTx() )
                        {
                            Node node = db.createNode( label( x ) );
                            node.setProperty( key( x ), nodeId = node.getId() );
                            tx.success();
                        }
                        highIdNodes[x].set( nodeId );
                    }
                }
                finally
                {
                    endLatch.countDown();
                }
            } ).start();
        }
    }

    private void startLoadOn( final GraphDatabaseService db, final AtomicBoolean halter, final AtomicLong[] highIdNodes,
            final CountDownLatch endLatch )
    {
        for ( int i = 0; i < numberOfIndexes; i++ )
        {
            final int x = i;
            new Thread()
            {
                @Override
                public void run()
                {
                    try
                    {
                        while ( !halter.get() )
                        {
                            long nodeId;
                            try ( Transaction tx = db.beginTx() )
                            {
                                Node node = db.createNode( label( x ) );
                                node.setProperty( key( x ), nodeId = node.getId() );
                                tx.success();
                            }
                            highIdNodes[x].set( nodeId );
                        }
                    }
                    finally
                    {
                        endLatch.countDown();
                    }
                }
            }.start();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.MeasureUpdatePullingRecordAndIndexGap.startLoadOn.start.new Thread with () -> {trywhile(!halter.get()){long nodeId; in method private startLoadOn(db GraphDatabaseService, halter AtomicBoolean, highIdNodes AtomicLong[], endLatch CountDownLatch) : void from class org.neo4j.kernel.ha.MeasureUpdatePullingRecordAndIndexGap


    /**
     * Inserts a bunch of new nodes with the label and property key currently set in the fields in this class, where
     * running this method twice will insert nodes with duplicate property values, assuming property key or label has
     * not changed.
     */
    private WorkerCommand<Object,Integer> performInserts( final HighlyAvailableGraphDatabase slave,
            final boolean constraintCompliant )
    {
        return state ->
        {
            int i = 0;

            try
            {
                for (; i < 100; i++ )
                {
                    try ( Transaction tx = slave.beginTx() )
                    {
                        constraintOps.createEntity( slave, labelOrRelType, property, "value" + i,
                                constraintCompliant );
                        tx.success();
                    }
                }
            }
            catch ( TransactionFailureException | TransientTransactionFailureException | ComException | ConstraintViolationException e )
            {
                // TransactionFailureException and TransientTransactionFailureException
                //   Swallowed on purpose, we except it to fail sometimes due to either
                //    - constraint violation on master
                //    - concurrent schema operation on master

                // ConstraintViolationException
                //   Constraint violation detected on slave while building transaction

                // ComException
                //   Happens sometimes, cause:
                //   - The lock session requested to start is already in use.
                //     Please retry your request in a few seconds.
            }
            return i;
        };
    }

    /**
     * Inserts a bunch of new nodes with the label and property key currently set in the fields in this class, where
     * running this method twice will insert nodes with duplicate property values, assuming property key or label has
     * not changed.
     */
    private WorkerCommand<Object,Integer> performInserts( final HighlyAvailableGraphDatabase slave,
            final boolean constraintCompliant )
    {
        return state ->
        {
            int i = 0;

            try
            {
                for (; i < 100; i++ )
                {
                    try ( Transaction tx = slave.beginTx() )
                    {
                        constraintOps.createEntity( slave, labelOrRelType, property, "value" + i,
                                constraintCompliant );
                        tx.success();
                    }
                }
            }
            catch ( TransactionFailureException | TransientTransactionFailureException e )
            {
                // Swallowed on purpose, we except it to fail sometimes due to either
                //  - constraint violation on master
                //  - concurrent schema operation on master
            }
            catch ( ConstraintViolationException e )
            {
                // Constraint violation detected on slave while building transaction
            }
            catch ( ComException e )
            {
                // Happens sometimes, cause:
                // - The lock session requested to start is already in use.
                //   Please retry your request in a few seconds.
            }
            return i;
        };
    }

Merge Catch [catch(TransactionFailureException|TransientTransactionFailureException e), catch(ConstraintViolationException e), catch(ComException e)] to catch(TransactionFailureException|TransientTransactionFailureException|ComException|ConstraintViolationException e) in method private performInserts(slave HighlyAvailableGraphDatabase, constraintCompliant boolean) : WorkerCommand<Object,Integer> from class org.neo4j.kernel.ha.PropertyConstraintsStressIT


    private Iterable<Slave> instantiateSlaves( int count, boolean[] failingSlaves )
    {
        List<Slave> slaves = new ArrayList<>();
        for ( int i = 0; i < count; i++ )
        {
            slaves.add( new FakeSlave( i < failingSlaves.length && failingSlaves[i], i + MasterServerId + 1 ) );
        }
        return slaves;
    }

    private Iterable<Slave> instantiateSlaves( int count, boolean[] failingSlaves )
    {
        List<Slave> slaves = new ArrayList<Slave>();
        for ( int i = 0; i < count; i++ )
        {
            slaves.add( new FakeSlave( i < failingSlaves.length && failingSlaves[i], i + MasterServerId + 1 ) );
        }
        return slaves;
    }

Replace Generic With Diamond ArrayList<Slave> with ArrayList<> in method private instantiateSlaves(count int, failingSlaves boolean[]) : Iterable<Slave> from class org.neo4j.kernel.ha.TestMasterCommittingAtSlave


    public static <T> Collection<T> loadAll( MBeanServerConnection mbs, Class<T> beanInterface, ObjectName query )
    {
        Collection<T> beans = new LinkedList<>();
        try
        {
            for ( ObjectName name : mbs.queryNames( query, null ) )
            {
                beans.add( factory.makeProxy( mbs, beanInterface, name ) );
            }
        }
        catch ( IOException e )
        {
            // fall through and return the empty collection...
        }
        return beans;
    }

    public static <T> Collection<T> loadAll( MBeanServerConnection mbs, Class<T> beanInterface, ObjectName query )
    {
        Collection<T> beans = new LinkedList<T>();
        try
        {
            for ( ObjectName name : mbs.queryNames( query, null ) )
            {
                beans.add( factory.makeProxy( mbs, beanInterface, name ) );
            }
        }
        catch ( IOException e )
        {
            // fall through and return the empty collection...
        }
        return beans;
    }

Replace Generic With Diamond LinkedList<T> with LinkedList<> in method public loadAll(mbs MBeanServerConnection, beanInterface Class<T>, query ObjectName) : Collection<T> from class org.neo4j.management.impl.BeanProxy


    protected List<Object> allBeans()
    {
        List<Object> beans = new ArrayList<>();
        Iterable<ObjectInstance> mbeans;
        try
        {
            mbeans = server.queryMBeans( mbeanQuery(), null );
        }
        catch ( IOException handled )
        {
            return beans;
        }
        for ( ObjectInstance instance : mbeans )
        {
            String className = instance.getClassName();
            Class<?> beanType = null;
            try
            {
                if ( className != null )
                {
                    beanType = Class.forName( className );
                }
            }
            catch ( Exception | LinkageError ignored )
            {
                // fall through
            }
            if ( beanType != null )
            {
                try
                {
                    beans.add( BeanProxy.load( server, beanType, instance.getObjectName() ) );
                }
                catch ( Exception ignored )
                {
                    // fall through
                }
            }
        }
        return beans;
    }

    protected List<Object> allBeans()
    {
        List<Object> beans = new ArrayList<Object>();
        Iterable<ObjectInstance> mbeans;
        try
        {
            mbeans = server.queryMBeans( mbeanQuery(), null );
        }
        catch ( IOException handled )
        {
            return beans;
        }
        for ( ObjectInstance instance : mbeans )
        {
            String className = instance.getClassName();
            Class<?> beanType = null;
            try
            {
                if ( className != null )
                {
                    beanType = Class.forName( className );
                }
            }
            catch ( Exception | LinkageError ignored )
            {
                // fall through
            }
            if ( beanType != null )
            {
                try
                {
                    beans.add( BeanProxy.load( server, beanType, instance.getObjectName() ) );
                }
                catch ( Exception ignored )
                {
                    // fall through
                }
            }
        }
        return beans;
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method protected allBeans() : List<Object> from class org.neo4j.management.impl.KernelProxy


    protected static ObjectName createObjectName( String kernelIdentifier, String beanName, String... extraNaming )
    {
        Hashtable<String, String> properties = new Hashtable<>();
        properties.put( "instance", "kernel#" + kernelIdentifier );
        return createObjectName( "org.neo4j", properties, beanName, false, extraNaming );
    }

    protected static ObjectName createObjectName( String kernelIdentifier, String beanName, String... extraNaming )
    {
        Hashtable<String, String> properties = new Hashtable<String, String>();
        properties.put( "instance", "kernel#" + kernelIdentifier );
        return createObjectName( "org.neo4j", properties, beanName, false, extraNaming );
    }

Replace Generic With Diamond Hashtable<String,String> with Hashtable<> in method protected createObjectName(kernelIdentifier String, beanName String, extraNaming String...) : ObjectName from class org.neo4j.management.impl.KernelProxy


    static ObjectName createObjectNameQuery( String kernelIdentifier, String beanName, String... extraNaming )
    {
        Hashtable<String, String> properties = new Hashtable<>();
        properties.put( "instance", "kernel#" + kernelIdentifier );
        return createObjectName( "org.neo4j", properties, beanName, true, extraNaming );
    }

    static ObjectName createObjectNameQuery( String kernelIdentifier, String beanName, String... extraNaming )
    {
        Hashtable<String, String> properties = new Hashtable<String, String>();
        properties.put( "instance", "kernel#" + kernelIdentifier );
        return createObjectName( "org.neo4j", properties, beanName, true, extraNaming );
    }

Replace Generic With Diamond Hashtable<String,String> with Hashtable<> in method package createObjectNameQuery(kernelIdentifier String, beanName String, extraNaming String...) : ObjectName from class org.neo4j.management.impl.KernelProxy


    private static ObjectName createObjectName( ObjectName query, String beanName, boolean isQuery )
    {
        Hashtable<String,String> properties = new Hashtable<>( query.getKeyPropertyList() );
        return createObjectName( query.getDomain(), properties, beanName, isQuery );
    }

    private static ObjectName createObjectName( ObjectName query, String beanName, boolean isQuery )
    {
        Hashtable<String,String> properties = new Hashtable<String,String>( query.getKeyPropertyList() );
        return createObjectName( query.getDomain(), properties, beanName, isQuery );
    }

Replace Generic With Diamond Hashtable<String,String> with Hashtable<> in method private createObjectName(query ObjectName, beanName String, isQuery boolean) : ObjectName from class org.neo4j.management.impl.KernelProxy


    private void addShutdownHook()
    {
        Runtime.getRuntime().addShutdownHook( new Thread( () -> {
            // ClusterJoin will block on a Future.get(), which will prevent it to shutdown.
            // Adding a timer here in case a shutdown is requested before cluster join has succeeded. Otherwise
            // the deadlock will prevent the shutdown from finishing.
            timer.schedule( new TimerTask()
            {
                @Override
                public void run()
                {
                    System.err.println( "Failed to stop in a reasonable time, terminating..." );
                    Runtime.getRuntime().halt( 1 );
                }
            }, 4_000L );
            ArbiterBootstrapper.this.stop();
        } ) );
    }

    private void addShutdownHook()
    {
        Runtime.getRuntime().addShutdownHook( new Thread()
        {
            @Override
            public void run()
            {
                // ClusterJoin will block on a Future.get(), which will prevent it to shutdown.
                // Adding a timer here in case a shutdown is requested before cluster join has succeeded. Otherwise
                // the deadlock will prevent the shutdown from finishing.
                timer.schedule( new TimerTask()
                {
                    @Override
                    public void run()
                    {
                        System.err.println( "Failed to stop in a reasonable time, terminating..." );
                        Runtime.getRuntime().halt( 1 );
                    }
                }, 4_000L );
                ArbiterBootstrapper.this.stop();
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.enterprise.ArbiterBootstrapper.addShutdownHook.addShutdownHook.new Thread with () -> {timer.schedule(new TimerTask(){ in method private addShutdownHook() : void from class org.neo4j.server.enterprise.ArbiterBootstrapper


    @Override
    public InputIterable nodes()
    {
        return replayable( () -> new GeneratingInputIterator<>( nodeCount, 1_000, batch -> null,
                (GeneratingInputIterator.Generator<Void>) ( state, visitor, id ) -> {
                    visitor.id( id, Group.GLOBAL );
                    visitor.labels( labels );
                    for ( int i = 0; i < properties.length; i++ )
                    {
                        visitor.property( (String) properties[i++], properties[i] );
                    }
                }, 0 ) );
    }

    @Override
    public InputIterable nodes()
    {
        return replayable( () -> new GeneratingInputIterator<>( nodeCount, 1_000, batch -> null, new GeneratingInputIterator.Generator<Void>()
        {
            @Override
            public void accept( Void state, InputEntityVisitor visitor, long id ) throws IOException
            {
                visitor.id( id, Group.GLOBAL );
                visitor.labels( labels );
                for ( int i = 0; i < properties.length; i++ )
                {
                    visitor.property( (String) properties[i++], properties[i] );
                }
            }
        }, 0 ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.stresstests.transaction.checkpoint.NodeCountInputs.nodes.replayable.new GeneratingInputIterator<>.new GeneratingInputIterator.Generator<Void> with (state, visitor, id) -> {visitor.id(id,Group.GLOBAL); in method public nodes() : InputIterable from class org.neo4j.kernel.stresstests.transaction.checkpoint.NodeCountInputs


    public NeoStoreFileListing( File storeDir, LogFiles logFiles,
            LabelScanStore labelScanStore, IndexingService indexingService,
            ExplicitIndexProviderLookup explicitIndexProviders, StorageEngine storageEngine )
    {
        this.storeDir = storeDir;
        this.logFiles = logFiles;
        this.labelScanStore = labelScanStore;
        this.indexingService = indexingService;
        this.explicitIndexProviders = explicitIndexProviders;
        this.storageEngine = storageEngine;
        this.additionalProviders = new CopyOnWriteArrayList<>();
    }

    public NeoStoreFileListing( File storeDir, LogFiles logFiles,
            LabelScanStore labelScanStore, IndexingService indexingService,
            ExplicitIndexProviderLookup explicitIndexProviders, StorageEngine storageEngine )
    {
        this.storeDir = storeDir;
        this.logFiles = logFiles;
        this.labelScanStore = labelScanStore;
        this.indexingService = indexingService;
        this.explicitIndexProviders = explicitIndexProviders;
        this.storageEngine = storageEngine;
        this.additionalProviders = new CopyOnWriteArrayList<ThrowingFunction<Collection<StoreFileMetadata>,Resource,IOException>>();
    }

Replace Generic With Diamond CopyOnWriteArrayList<ThrowingFunction<Collection<StoreFileMetadata>,Resource,IOException>> with CopyOnWriteArrayList<> in method public NeoStoreFileListing(storeDir File, logFiles LogFiles, labelScanStore LabelScanStore, indexingService IndexingService, explicitIndexProviders ExplicitIndexProviderLookup, storageEngine StorageEngine) from class org.neo4j.kernel.impl.transaction.state.NeoStoreFileListing


    private ResourceIterator<Node> nodesByLabelAndProperty( Label myLabel, String key, Value value )
    {
        KernelTransaction transaction = statementContext.getKernelTransactionBoundToThisThread( true );
        Statement statement = transaction.acquireStatement();
        Read read = transaction.dataRead();
        TokenRead tokenRead = transaction.tokenRead();
        int propertyId = tokenRead.propertyKey( key );
        int labelId = tokenRead.nodeLabel( myLabel.name() );

        if ( propertyId == NO_SUCH_PROPERTY_KEY || labelId == NO_SUCH_LABEL )
        {
            statement.close();
            return emptyResourceIterator();
        }
        CapableIndexReference index = transaction.schemaRead().index( labelId, propertyId );
        if ( index != CapableIndexReference.NO_INDEX )
        {
            // Ha! We found an index - let's use it to find matching nodes
            try
            {
                NodeValueIndexCursor cursor = transaction.cursors().allocateNodeValueIndexCursor();
                IndexQuery.ExactPredicate query = IndexQuery.exact( propertyId, value );
                read.nodeIndexSeek( index, cursor, IndexOrder.NONE, query );

                return new NodeCursorResourceIterator<>( cursor, statement );
            }
            catch ( KernelException e )
            {
                // weird at this point but ignore and fallback to a label scan
            }
        }

        return getNodesByLabelAndPropertyWithoutIndex( propertyId, value, statement, labelId );
    }

    private ResourceIterator<Node> nodesByLabelAndProperty( Label myLabel, String key, Value value )
    {
        KernelTransaction transaction = statementContext.getKernelTransactionBoundToThisThread( true );
        Statement statement = transaction.acquireStatement();
        Read read = transaction.dataRead();
        TokenRead tokenRead = transaction.tokenRead();
        int propertyId = tokenRead.propertyKey( key );
        int labelId = tokenRead.nodeLabel( myLabel.name() );

        if ( propertyId == NO_SUCH_PROPERTY_KEY || labelId == NO_SUCH_LABEL )
        {
            statement.close();
            return emptyResourceIterator();
        }
        CapableIndexReference index = transaction.schemaRead().index( labelId, propertyId );
        if ( index != CapableIndexReference.NO_INDEX )
        {
            // Ha! We found an index - let's use it to find matching nodes
            try
            {
                NodeValueIndexCursor cursor = transaction.cursors().allocateNodeValueIndexCursor();
                IndexQuery.ExactPredicate query = IndexQuery.exact( propertyId, value );
                read.nodeIndexSeek( index, cursor, IndexOrder.NONE, query );

                return new PrefetchingResourceIterator<Node>()
                {
                    private boolean closed;
                    @Override
                    protected Node fetchNextOrNull()
                    {
                        if ( cursor.next() )
                        {
                            return newNodeProxy( cursor.nodeReference() );
                        }
                        else
                        {
                            close();
                            return null;
                        }
                    }

                    @Override
                    public void close()
                    {
                        if ( !closed )
                        {
                            statement.close();
                            cursor.close();
                            closed = true;
                        }
                    }
                };
            }
            catch ( KernelException e )
            {
                // weird at this point but ignore and fallback to a label scan
            }
        }

        return getNodesByLabelAndPropertyWithoutIndex( propertyId, value, statement, labelId );
    }

Replace Generic With Diamond PrefetchingResourceIterator<Node> with NodeCursorResourceIterator<> in method private nodesByLabelAndProperty(myLabel Label, key String, value Value) : ResourceIterator<Node> from class org.neo4j.kernel.impl.factory.GraphDatabaseFacade


    private String getFieldFromExtractTerms( Query query )
    {
        Set<Term> terms = new HashSet<>();
        try
        {
            searcher.createNormalizedWeight( query, false ).extractTerms( terms );
        }
        catch ( IOException ioe )
        {
            throw new UnsupportedOperationException( ioe );
        }
        catch ( UnsupportedOperationException ue )
        {
            // TODO This is for "*" queries and such. Lucene doesn't seem
            // to be able/willing to rewrite such queries.
            // Just ignore the orphans then... OK?
        }
        return terms.isEmpty() ? null : terms.iterator().next().field();
    }

    private String getFieldFromExtractTerms( Query query )
    {
        Set<Term> terms = new HashSet<Term>();
        try
        {
            searcher.createNormalizedWeight( query, false ).extractTerms( terms );
        }
        catch ( IOException ioe )
        {
            throw new UnsupportedOperationException( ioe );
        }
        catch ( UnsupportedOperationException ue )
        {
            // TODO This is for "*" queries and such. Lucene doesn't seem
            // to be able/willing to rewrite such queries.
            // Just ignore the orphans then... OK?
        }
        return terms.isEmpty() ? null : terms.iterator().next().field();
    }

Replace Generic With Diamond HashSet<Term> with HashSet<> in method private getFieldFromExtractTerms(query Query) : String from class org.neo4j.index.impl.lucene.explicit.FullTxData


    @Test
    public void shouldParameteriseUrisInNodeRepresentationWithHostHeaderValue() throws Exception
    {
        try ( CloseableHttpClient httpclient = HttpClientBuilder.create().build() )
        {
            HttpGet httpget = new HttpGet( nodeUri );

            httpget.setHeader( "Accept", "application/json" );
            httpget.setHeader( "Host", "dummy.neo4j.org" );
            HttpResponse response = httpclient.execute( httpget );
            HttpEntity entity = response.getEntity();

            String entityBody = IOUtils.toString( entity.getContent(), StandardCharsets.UTF_8 );

            assertThat( entityBody, containsString( "http://dummy.neo4j.org/db/data/node/" ) );

        }
    }

    @Test
    public void shouldParameteriseUrisInNodeRepresentationWithHostHeaderValue() throws Exception
    {
        HttpClient httpclient = new DefaultHttpClient();
        try
        {
            HttpGet httpget = new HttpGet( nodeUri );

            httpget.setHeader( "Accept", "application/json" );
            httpget.setHeader( "Host", "dummy.neo4j.org" );
            HttpResponse response = httpclient.execute( httpget );
            HttpEntity entity = response.getEntity();

            String entityBody = IOUtils.toString( entity.getContent(), StandardCharsets.UTF_8 );

            assertThat( entityBody, containsString( "http://dummy.neo4j.org/db/data/node/" ) );

        }
        finally
        {
            httpclient.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient httpclient=HttpClientBuilder.create().build()) in method public shouldParameteriseUrisInNodeRepresentationWithHostHeaderValue() : void from class org.neo4j.server.rest.RetrieveNodeIT


    @Test
    public void shouldParameteriseUrisInNodeRepresentationWithoutHostHeaderUsingRequestUri() throws Exception
    {
        try ( CloseableHttpClient httpclient = HttpClientBuilder.create().build() )
        {
            HttpGet httpget = new HttpGet( nodeUri );

            httpget.setHeader( "Accept", "application/json" );
            HttpResponse response = httpclient.execute( httpget );
            HttpEntity entity = response.getEntity();

            String entityBody = IOUtils.toString( entity.getContent(), StandardCharsets.UTF_8 );

            assertThat( entityBody, containsString( nodeUri.toString() ) );
        }
    }

    @Test
    public void shouldParameteriseUrisInNodeRepresentationWithoutHostHeaderUsingRequestUri() throws Exception
    {
        HttpClient httpclient = new DefaultHttpClient();
        try
        {
            HttpGet httpget = new HttpGet( nodeUri );

            httpget.setHeader( "Accept", "application/json" );
            HttpResponse response = httpclient.execute( httpget );
            HttpEntity entity = response.getEntity();

            String entityBody = IOUtils.toString( entity.getContent(), StandardCharsets.UTF_8 );

            assertThat( entityBody, containsString( nodeUri.toString() ) );
        }
        finally
        {
            httpclient.getConnectionManager().shutdown();
        }
    }

Try With Resources try(CloseableHttpClient httpclient=HttpClientBuilder.create().build()) in method public shouldParameteriseUrisInNodeRepresentationWithoutHostHeaderUsingRequestUri() : void from class org.neo4j.server.rest.RetrieveNodeIT