    @Override
    public int complete( String buffer, int cursor, List candidates )
    {
        if ( buffer == null || buffer.length() == 0 )
        {
            return cursor;
        }

        try
        {
            if ( buffer.contains( " " ) )
            {
                TabCompletion completion = client.getServer().tabComplete( client.getId(), buffer.trim() );
                cursor = completion.getCursor();
                //noinspection unchecked
                candidates.addAll( completion.getCandidates() );
            }
            else
            {
                // Complete the app name
                return getAppNameCompleter().complete( buffer, cursor, candidates );
            }
        }
        catch ( RemoteException | ShellException e )
        {
            // TODO Throw something?
            e.printStackTrace();
        }
        return cursor;
    }

    @Override
    public int complete( String buffer, int cursor, List candidates )
    {
        if ( buffer == null || buffer.length() == 0 )
        {
            return cursor;
        }

        try
        {
            if ( buffer.contains( " " ) )
            {
                TabCompletion completion = client.getServer().tabComplete( client.getId(), buffer.trim() );
                cursor = completion.getCursor();
                //noinspection unchecked
                candidates.addAll( completion.getCandidates() );
            }
            else
            {
                // Complete the app name
                return getAppNameCompleter().complete( buffer, cursor, candidates );
            }
        }
        catch ( RemoteException e )
        {
            // TODO Throw something?
            e.printStackTrace();
        }
        catch ( ShellException e )
        {
            // TODO Throw something?
            e.printStackTrace();
        }
        return cursor;
    }

Merge Catch [catch(RemoteException e), catch(ShellException e)] to catch(RemoteException|ShellException e) in method public complete(buffer String, cursor int, candidates List) : int from class org.neo4j.shell.impl.ShellTabCompleter


        @Override
        public IndexHits<T> get( String key, Object value )
        {
            return new ReadOnlyIndexHitsProxy<>( this, actual.get( key, value ) );
        }

        @Override
        public IndexHits<T> get( String key, Object value )
        {
            return new ReadOnlyIndexHitsProxy<T>( this, actual.get( key, value ) );
        }

Replace Generic With Diamond ReadOnlyIndexHitsProxy<T> with ReadOnlyIndexHitsProxy<> in method public get(key String, value Object) : IndexHits<T> from class org.neo4j.shell.kernel.ReadOnlyGraphDatabaseProxy.ReadOnlyIndexProxy


        @Override
        public IndexHits<T> query( String key, Object queryOrQueryObject )
        {
            return new ReadOnlyIndexHitsProxy<>( this, actual.query( key, queryOrQueryObject ) );
        }

        @Override
        public IndexHits<T> query( String key, Object queryOrQueryObject )
        {
            return new ReadOnlyIndexHitsProxy<T>( this, actual.query( key, queryOrQueryObject ) );
        }

Replace Generic With Diamond ReadOnlyIndexHitsProxy<T> with ReadOnlyIndexHitsProxy<> in method public query(key String, queryOrQueryObject Object) : IndexHits<T> from class org.neo4j.shell.kernel.ReadOnlyGraphDatabaseProxy.ReadOnlyIndexProxy


        @Override
        public IndexHits<T> query( Object queryOrQueryObject )
        {
            return new ReadOnlyIndexHitsProxy<>( this, actual.query( queryOrQueryObject ) );
        }

        @Override
        public IndexHits<T> query( Object queryOrQueryObject )
        {
            return new ReadOnlyIndexHitsProxy<T>( this, actual.query( queryOrQueryObject ) );
        }

Replace Generic With Diamond ReadOnlyIndexHitsProxy<T> with ReadOnlyIndexHitsProxy<> in method public query(queryOrQueryObject Object) : IndexHits<T> from class org.neo4j.shell.kernel.ReadOnlyGraphDatabaseProxy.ReadOnlyIndexProxy


    @Override
    protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception
    {
        Kernel kernel = getKernel();
        boolean list = parser.options().containsKey( "l" );
        boolean get = parser.options().containsKey( "g" );
        if ( (list && get) || (!list && !get) )
        {
            StringBuilder usage = new StringBuilder();
            getUsage( usage );
            usage.append( ".\n" );
            out.print( usage.toString() );
            return Continuation.INPUT_COMPLETE;
        }
        MBeanServer mbeans = getPlatformMBeanServer();
        String bean = null;
        String[] attributes = null;
        if ( list )
        {
            bean = parser.options().get( "l" );
        }
        else if ( get )
        {
            bean = parser.options().get( "g" );
            attributes = parser.arguments().toArray( new String[parser.arguments().size()] );
        }
        if ( bean == null ) // list beans
        {
            StringBuilder result = new StringBuilder();
            availableBeans( mbeans, kernel, result );
            out.print( result.toString() );
            return Continuation.INPUT_COMPLETE;
        }
        ObjectName mbean;
        {
            mbean = kernel.getMBeanQuery();
            Hashtable<String, String> properties = new Hashtable<>( mbean.getKeyPropertyList() );
            properties.put( "name", bean );
            try
            {
                Iterator<ObjectName> names = mbeans.queryNames(
                        new ObjectName( mbean.getDomain(), properties ), null ).iterator();
                if ( names.hasNext() )
                {
                    mbean = names.next();
                    if ( names.hasNext() )
                    {
                        mbean = null;
                    }
                }
                else
                {
                    mbean = null;
                }
            }
            catch ( Exception e )
            {
                mbean = null;
            }
        }
        if ( mbean == null )
        {
            throw new ShellException( "No such management bean \"" + bean + "\"." );
        }
        if ( attributes == null ) // list attributes
        {
            for ( MBeanAttributeInfo attr : mbeans.getMBeanInfo( mbean ).getAttributes() )
            {
                out.println( attr.getName() + " - " + attr.getDescription() );
            }
        }
        else
        {
            if ( attributes.length == 0 ) // specify all attributes
            {
                MBeanAttributeInfo[] allAttributes = mbeans.getMBeanInfo( mbean ).getAttributes();
                attributes = new String[allAttributes.length];
                for ( int i = 0; i < allAttributes.length; i++ )
                {
                    attributes[i] = allAttributes[i].getName();
                }
            }
            JSONObject json = new JSONObject();
            for ( Object value : mbeans.getAttributes( mbean, attributes ) )
            {
                printAttribute( json, value );
            }
            out.println( json.toString( 2 ) );
        }
        return Continuation.INPUT_COMPLETE;
    }

    @Override
    protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception
    {
        Kernel kernel = getKernel();
        boolean list = parser.options().containsKey( "l" );
        boolean get = parser.options().containsKey( "g" );
        if ( (list && get) || (!list && !get) )
        {
            StringBuilder usage = new StringBuilder();
            getUsage( usage );
            usage.append( ".\n" );
            out.print( usage.toString() );
            return Continuation.INPUT_COMPLETE;
        }
        MBeanServer mbeans = getPlatformMBeanServer();
        String bean = null;
        String[] attributes = null;
        if ( list )
        {
            bean = parser.options().get( "l" );
        }
        else if ( get )
        {
            bean = parser.options().get( "g" );
            attributes = parser.arguments().toArray( new String[parser.arguments().size()] );
        }
        if ( bean == null ) // list beans
        {
            StringBuilder result = new StringBuilder();
            availableBeans( mbeans, kernel, result );
            out.print( result.toString() );
            return Continuation.INPUT_COMPLETE;
        }
        ObjectName mbean;
        {
            mbean = kernel.getMBeanQuery();
            Hashtable<String, String> properties = new Hashtable<String, String>(
                    mbean.getKeyPropertyList() );
            properties.put( "name", bean );
            try
            {
                Iterator<ObjectName> names = mbeans.queryNames(
                        new ObjectName( mbean.getDomain(), properties ), null ).iterator();
                if ( names.hasNext() )
                {
                    mbean = names.next();
                    if ( names.hasNext() )
                    {
                        mbean = null;
                    }
                }
                else
                {
                    mbean = null;
                }
            }
            catch ( Exception e )
            {
                mbean = null;
            }
        }
        if ( mbean == null )
        {
            throw new ShellException( "No such management bean \"" + bean + "\"." );
        }
        if ( attributes == null ) // list attributes
        {
            for ( MBeanAttributeInfo attr : mbeans.getMBeanInfo( mbean ).getAttributes() )
            {
                out.println( attr.getName() + " - " + attr.getDescription() );
            }
        }
        else
        {
            if ( attributes.length == 0 ) // specify all attributes
            {
                MBeanAttributeInfo[] allAttributes = mbeans.getMBeanInfo( mbean ).getAttributes();
                attributes = new String[allAttributes.length];
                for ( int i = 0; i < allAttributes.length; i++ )
                {
                    attributes[i] = allAttributes[i].getName();
                }
            }
            JSONObject json = new JSONObject();
            for ( Object value : mbeans.getAttributes( mbean, attributes ) )
            {
                printAttribute( json, value );
            }
            out.println( json.toString( 2 ) );
        }
        return Continuation.INPUT_COMPLETE;
    }

Replace Generic With Diamond Hashtable<String,String> with Hashtable<> in method protected exec(parser AppCommandParser, session Session, out Output) : Continuation from class org.neo4j.shell.kernel.apps.Dbinfo


    @Override
    protected Continuation exec( AppCommandParser parser, Session session, Output out )
            throws ShellException, RemoteException
    {
        boolean doCd = parser.options().containsKey( "cd" );
        boolean doLs = parser.options().containsKey( "ls" );
        boolean query = parser.options().containsKey( "q" );
        boolean get = parser.options().containsKey( "g" ) || query || doCd || doLs;
        boolean index = parser.options().containsKey( "i" );
        boolean remove = parser.options().containsKey( "r" );
        boolean getConfig = parser.options().containsKey( "get-config" );
        boolean create = parser.options().containsKey( "create" );
        boolean setConfig = parser.options().containsKey( "set-config" );
        boolean delete = parser.options().containsKey( "delete" );
        boolean indexes = parser.options().containsKey( "indexes" );
        int count = boolCount( get, index, remove, getConfig, create, setConfig, delete, indexes );
        if ( count != 1 )
        {
            throw new ShellException( "Supply one of: -g, -i, -r, --get-config, --set-config, --create, --delete, --indexes" );
        }

        if ( get )
        {
            String commandToRun = parser.options().get( "c" );
            Collection<String> commandsToRun = new ArrayList<>();
            boolean specialCommand = false;
            if ( doCd || doLs )
            {
                specialCommand = true;
                if ( doCd )
                {
                    commandsToRun.add( "cd -a $i" );
                }
                else if ( doLs )
                {
                    commandsToRun.add( "ls $i" );
                }
            }
            else if ( commandToRun != null )
            {
                commandsToRun.addAll( Arrays.asList( commandToRun.split( Pattern.quote( "&&" ) ) ) );
            }

            if ( getIndex( getIndexName( parser ), getEntityType( parser ), out ) == null )
            {
                return Continuation.INPUT_COMPLETE;
            }

            try ( IndexHits<PropertyContainer> result = query ? query( parser, out ) : get( parser, out ) )
            {
                for ( PropertyContainer hit : result )
                {
                    printAndInterpretTemplateLines( commandsToRun, !specialCommand,
                            NodeOrRelationship.wrap( hit ), getServer(), session, out );
                }
            }
        }
        else if ( index )
        {
            index( parser, session, out );
        }
        else if ( remove )
        {
            if ( getIndex( getIndexName( parser ), Node.class, out ) == null )
            {
                return null;
            }
            remove( parser, session, out );
        }
        else if ( getConfig )
        {
            displayConfig( parser, out );
        }
        else if ( create )
        {
            createIndex( parser, out );
        }
        else if ( setConfig )
        {
            setConfig( parser, out );
        }
        else if ( delete )
        {
            deleteIndex( parser, out );
        }

        if ( indexes )
        {
            listIndexes( out );
        }

        return Continuation.INPUT_COMPLETE;
    }

    @Override
    protected Continuation exec( AppCommandParser parser, Session session, Output out )
            throws ShellException, RemoteException
    {
        boolean doCd = parser.options().containsKey( "cd" );
        boolean doLs = parser.options().containsKey( "ls" );
        boolean query = parser.options().containsKey( "q" );
        boolean get = parser.options().containsKey( "g" ) || query || doCd || doLs;
        boolean index = parser.options().containsKey( "i" );
        boolean remove = parser.options().containsKey( "r" );
        boolean getConfig = parser.options().containsKey( "get-config" );
        boolean create = parser.options().containsKey( "create" );
        boolean setConfig = parser.options().containsKey( "set-config" );
        boolean delete = parser.options().containsKey( "delete" );
        boolean indexes = parser.options().containsKey( "indexes" );
        int count = boolCount( get, index, remove, getConfig, create, setConfig, delete, indexes );
        if ( count != 1 )
        {
            throw new ShellException( "Supply one of: -g, -i, -r, --get-config, --set-config, --create, --delete, --indexes" );
        }

        if ( get )
        {
            String commandToRun = parser.options().get( "c" );
            Collection<String> commandsToRun = new ArrayList<String>();
            boolean specialCommand = false;
            if ( doCd || doLs )
            {
                specialCommand = true;
                if ( doCd )
                {
                    commandsToRun.add( "cd -a $i" );
                }
                else if ( doLs )
                {
                    commandsToRun.add( "ls $i" );
                }
            }
            else if ( commandToRun != null )
            {
                commandsToRun.addAll( Arrays.asList( commandToRun.split( Pattern.quote( "&&" ) ) ) );
            }

            if ( getIndex( getIndexName( parser ), getEntityType( parser ), out ) == null )
            {
                return Continuation.INPUT_COMPLETE;
            }

            IndexHits<PropertyContainer> result = query ? query( parser, out ) : get( parser, out );
            try
            {
                for ( PropertyContainer hit : result )
                {
                    printAndInterpretTemplateLines( commandsToRun, false, !specialCommand, NodeOrRelationship.wrap( hit ),
                            getServer(), session, out );
                }
            }
            finally
            {
                result.close();
            }
        }
        else if ( index )
        {
            index( parser, session, out );
        }
        else if ( remove )
        {
            if ( getIndex( getIndexName( parser ), Node.class, out ) == null )
            {
                return null;
            }
            remove( parser, session, out );
        }
        else if ( getConfig )
        {
            displayConfig( parser, out );
        }
        else if ( create )
        {
            createIndex( parser, out );
        }
        else if ( setConfig )
        {
            setConfig( parser, out );
        }
        else if ( delete )
        {
            deleteIndex( parser, out );
        }

        if ( indexes )
        {
            listIndexes( out );
        }

        return Continuation.INPUT_COMPLETE;
    }

Try With Resources try(IndexHits<PropertyContainer> result=query ? query(parser,out) : get(parser,out)) in method protected exec(parser AppCommandParser, session Session, out Output) : Continuation from class org.neo4j.shell.kernel.apps.IndexProviderShellApp


    private void displayLabels( NodeOrRelationship thing, Output out, Map<String, Object> filterMap,
            boolean caseInsensitiveFilters, boolean looseFilters, boolean brief ) throws RemoteException
    {
        List<String> labelNames = new ArrayList<>();
        for ( Label label : thing.asNode().getLabels() )
        {
            labelNames.add( label.name() );
        }

        if ( brief )
        {
            out.println( "Label count: " + labelNames.size() );
        }
        else
        {
            for ( String label : sortKeys( labelNames ) )
            {
                if ( filterMatches( filterMap, caseInsensitiveFilters, looseFilters, label, "" ) )
                {
                    out.println( ":" + label );
                }
            }
        }
    }

    private void displayLabels( NodeOrRelationship thing, Output out, Map<String, Object> filterMap,
            boolean caseInsensitiveFilters, boolean looseFilters, boolean brief ) throws RemoteException
    {
        List<String> labelNames = new ArrayList<String>();
        for ( Label label : thing.asNode().getLabels() )
        {
            labelNames.add( label.name() );
        }

        if ( brief )
        {
            out.println( "Label count: " + labelNames.size() );
        }
        else
        {
            for ( String label : sortKeys( labelNames ) )
            {
                if ( filterMatches( filterMap, caseInsensitiveFilters, looseFilters, label, "" ) )
                {
                    out.println( ":" + label );
                }
            }
        }
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method private displayLabels(thing NodeOrRelationship, out Output, filterMap Map<String,Object>, caseInsensitiveFilters boolean, looseFilters boolean, brief boolean) : void from class org.neo4j.shell.kernel.apps.Ls


    /**
     * Reads the session variable specified in {@link org.neo4j.shell.Variables#WORKING_DIR_KEY} and
     * returns it as a list of typed ids.
     * @param session the session to read from.
     * @return the working directory as a list.
     * @throws RemoteException if an RMI error occurs.
     */
    public static List<TypedId> readCurrentWorkingDir( Session session ) throws RemoteException
    {
        List<TypedId> list = new ArrayList<>();
        String path = session.getPath();
        if ( path != null && path.trim().length() > 0 )
        {
            for ( String typedId : path.split( "," ) )
            {
                list.add( new TypedId( typedId ) );
            }
        }
        return list;
    }

    /**
     * Reads the session variable specified in {@link org.neo4j.shell.Variables#WORKING_DIR_KEY} and
     * returns it as a list of typed ids.
     * @param session the session to read from.
     * @return the working directory as a list.
     * @throws RemoteException if an RMI error occurs.
     */
    public static List<TypedId> readCurrentWorkingDir( Session session ) throws RemoteException
    {
        List<TypedId> list = new ArrayList<TypedId>();
        String path = session.getPath();
        if ( path != null && path.trim().length() > 0 )
        {
            for ( String typedId : path.split( "," ) )
            {
                list.add( new TypedId( typedId ) );
            }
        }
        return list;
    }

Replace Generic With Diamond ArrayList<TypedId> with ArrayList<> in method public readCurrentWorkingDir(session Session) : List<TypedId> from class org.neo4j.shell.kernel.apps.TransactionProvidingApp


    protected static Map<String, Direction> filterMapToTypes( GraphDatabaseService db,
            Direction defaultDirection, Map<String, Object> filterMap, boolean caseInsensitiveFilters,
            boolean looseFilters ) throws ShellException
    {
        Map<String, Direction> matches = new TreeMap<>();
        for ( RelationshipType type : db.getAllRelationshipTypes() )
        {
            Direction direction = null;
            if ( filterMap == null || filterMap.isEmpty() )
            {
                direction = defaultDirection;
            }
            else
            {
                for ( Map.Entry<String, Object> entry : filterMap.entrySet() )
                {
                    if ( matches( newPattern( entry.getKey(), caseInsensitiveFilters ),
                        type.name(), caseInsensitiveFilters, looseFilters ) )
                    {
                        direction = getDirection( entry.getValue() != null ? entry.getValue().toString() : null, defaultDirection );
                        break;
                    }
                }
            }

            // It matches
            if ( direction != null )
            {
                matches.put( type.name(), direction );
            }
        }
        return matches.isEmpty() ? Collections.emptyMap() : matches;
    }

    protected static Map<String, Direction> filterMapToTypes( GraphDatabaseService db,
            Direction defaultDirection, Map<String, Object> filterMap, boolean caseInsensitiveFilters,
            boolean looseFilters ) throws ShellException
    {
        Map<String, Direction> matches = new TreeMap<String, Direction>();
        for ( RelationshipType type : db.getAllRelationshipTypes() )
        {
            Direction direction = null;
            if ( filterMap == null || filterMap.isEmpty() )
            {
                direction = defaultDirection;
            }
            else
            {
                for ( Map.Entry<String, Object> entry : filterMap.entrySet() )
                {
                    if ( matches( newPattern( entry.getKey(), caseInsensitiveFilters ),
                        type.name(), caseInsensitiveFilters, looseFilters ) )
                    {
                        direction = getDirection( entry.getValue() != null ? entry.getValue().toString() : null, defaultDirection );
                        break;
                    }
                }
            }

            // It matches
            if ( direction != null )
            {
                matches.put( type.name(), direction );
            }
        }
        return matches.isEmpty() ? Collections.emptyMap() : matches;
    }

Replace Generic With Diamond TreeMap<String,Direction> with TreeMap<> in method protected filterMapToTypes(db GraphDatabaseService, defaultDirection Direction, filterMap Map<String,Object>, caseInsensitiveFilters boolean, looseFilters boolean) : Map<String,Direction> from class org.neo4j.shell.kernel.apps.TransactionProvidingApp


    /**
     * Construct an empty JSONArray.
     */
    public JSONArray()
    {
        this.myArrayList = new ArrayList<>();
    }

    /**
     * Construct an empty JSONArray.
     */
    public JSONArray()
    {
        this.myArrayList = new ArrayList<Object>();
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method public JSONArray() from class org.neo4j.shell.util.json.JSONArray


    /**
     * Construct a JSONArray from a collection of beans.
     * The collection should have Java Beans.
     */

    public JSONArray( Collection collection, boolean includeSuperClass )
    {
        this.myArrayList = new ArrayList<>();
        if ( collection != null )
        {
            Iterator iter = collection.iterator();
            while ( iter.hasNext() )
            {
                Object o = iter.next();
                if ( o instanceof Map )
                {
                    this.myArrayList.add( new JSONObject( (Map) o, includeSuperClass ) );
                }
                else if ( !JSONObject.isStandardProperty( o.getClass() ) )
                {
                    this.myArrayList.add( new JSONObject( o, includeSuperClass ) );
                }
                else
                {
                    this.myArrayList.add( o );
                }
            }
        }
    }

    /**
     * Construct a JSONArray from a collection of beans.
     * The collection should have Java Beans.
     */

    public JSONArray( Collection collection, boolean includeSuperClass )
    {
        this.myArrayList = new ArrayList<Object>();
        if ( collection != null )
        {
            Iterator iter = collection.iterator();
            while ( iter.hasNext() )
            {
                Object o = iter.next();
                if ( o instanceof Map )
                {
                    this.myArrayList.add( new JSONObject( (Map) o, includeSuperClass ) );
                }
                else if ( !JSONObject.isStandardProperty( o.getClass() ) )
                {
                    this.myArrayList.add( new JSONObject( o, includeSuperClass ) );
                }
                else
                {
                    this.myArrayList.add( o );
                }
            }
        }
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method public JSONArray(collection Collection, includeSuperClass boolean) from class org.neo4j.shell.util.json.JSONArray


    @Test
    public void shouldInstallProvidedHandlerAfterReadingUserInput() throws Exception
    {
        final StubCtrlCHandler handler = new StubCtrlCHandler();
        AbstractClient client = new AbstractClient( new HashMap<>(), handler )
        {
            @Override
            public ShellServer getServer()
            {
                try
                {
                    return new FakeShellServer( null );
                }
                catch ( RemoteException e )
                {
                    throw new RuntimeException( e );
                }
            }

            @Override
            public Output getOutput()
            {
                try
                {
                    return new CollectingOutput();
                }
                catch ( RemoteException e )
                {
                    throw new RuntimeException( e );
                }
            }

            @Override
            public String readLine( String ignored )
            {
                assertFalse( "handler installed, expected it to not be there", handler.installed );
                return "CYPHER 2.1 RETURN 42;";
            }

            @Override
            public void evaluate( String output )
            {
                assertTrue( "handler not installed, but expected to be there", handler.installed );
                end();
            }
        };
        client.grabPrompt();
        assertFalse( "handler installed, expected it to not be there", handler.installed );
    }

    @Test
    public void shouldInstallProvidedHandlerAfterReadingUserInput() throws Exception
    {
        final StubCtrlCHandler handler = new StubCtrlCHandler();
        AbstractClient client = new AbstractClient( new HashMap<String, Serializable>(), handler )
        {
            @Override
            public ShellServer getServer()
            {
                try
                {
                    return new FakeShellServer( null );
                }
                catch ( RemoteException e )
                {
                    throw new RuntimeException( e );
                }
            }

            @Override
            public Output getOutput()
            {
                try
                {
                    return new CollectingOutput();
                }
                catch ( RemoteException e )
                {
                    throw new RuntimeException( e );
                }
            }

            @Override
            public String readLine( String ignored )
            {
                assertFalse( "handler installed, expected it to not be there", handler.installed );
                return "CYPHER 2.1 RETURN 42;";
            }

            @Override
            public void evaluate( String output )
            {
                assertTrue( "handler not installed, but expected to be there", handler.installed );
                end();
            }
        };
        client.grabPrompt();
        assertFalse( "handler installed, expected it to not be there", handler.installed );
    }

Replace Generic With Diamond AbstractClient with AbstractClient in method public shouldInstallProvidedHandlerAfterReadingUserInput() : void from class org.neo4j.shell.CtrlCTest


    @Before
    public void doBefore() throws Exception
    {
        db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase();
        shellServer = new FakeShellServer( db );
        shellClient = new SameJvmClient( new HashMap<>(), shellServer, new CollectingOutput() );
   }

    @Before
    public void doBefore() throws Exception
    {
        db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase();
        shellServer = new FakeShellServer( db );
        shellClient = new SameJvmClient( new HashMap<String, Serializable>(), shellServer, new CollectingOutput() );
   }

Replace Generic With Diamond SameJvmClient with SameJvmClient in method public doBefore() : void from class org.neo4j.shell.TestTransactionApps


    @Test
    public void shouldPingServer()
    {
        final HostnamePort hostURL = new HostnamePort( hostname, server.getLocalPort() );
        final Map<String,String> udcFields = new HashMap<>();
        udcFields.put( ID, EXPECTED_STORE_ID );
        udcFields.put( UdcConstants.VERSION, EXPECTED_KERNEL_VERSION );

        Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) );
        Exception thrownException = null;
        try
        {
            p.ping();
        }
        catch ( IOException e )
        {
            thrownException = e;
            e.printStackTrace();
        }
        assertThat( thrownException, nullValue() );

        Map<String,String> actualQueryMap = handler.getQueryMap();
        assertThat( actualQueryMap, notNullValue() );
        assertThat( actualQueryMap.get( ID ), is( EXPECTED_STORE_ID ) );

    }

    @Test
    public void shouldPingServer()
    {
        final HostnamePort hostURL = new HostnamePort( hostname, server.getLocalPort() );
        final Map<String,String> udcFields = new HashMap<String,String>();
        udcFields.put( ID, EXPECTED_STORE_ID );
        udcFields.put( UdcConstants.VERSION, EXPECTED_KERNEL_VERSION );

        Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) );
        Exception thrownException = null;
        try
        {
            p.ping();
        }
        catch ( IOException e )
        {
            thrownException = e;
            e.printStackTrace();
        }
        assertThat( thrownException, nullValue() );

        Map<String,String> actualQueryMap = handler.getQueryMap();
        assertThat( actualQueryMap, notNullValue() );
        assertThat( actualQueryMap.get( ID ), is( EXPECTED_STORE_ID ) );

    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public shouldPingServer() : void from class org.neo4j.ext.udc.impl.PingerTest


    @Test
    public void shouldIncludePingCountInURI() throws IOException
    {
        final int EXPECTED_PING_COUNT = 16;
        final HostnamePort hostURL = new HostnamePort( hostname, server.getLocalPort() );
        final Map<String,String> udcFields = new HashMap<>();

        Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) );
        for ( int i = 0; i < EXPECTED_PING_COUNT; i++ )
        {
            p.ping();
        }

        assertThat( p.getPingCount(), is( equalTo( EXPECTED_PING_COUNT ) ) );

        Map<String,String> actualQueryMap = handler.getQueryMap();
        assertThat( actualQueryMap.get( UdcConstants.PING ), is( Integer.toString( EXPECTED_PING_COUNT ) ) );
    }

    @Test
    public void shouldIncludePingCountInURI() throws IOException
    {
        final int EXPECTED_PING_COUNT = 16;
        final HostnamePort hostURL = new HostnamePort( hostname, server.getLocalPort() );
        final Map<String,String> udcFields = new HashMap<String,String>();

        Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) );
        for ( int i = 0; i < EXPECTED_PING_COUNT; i++ )
        {
            p.ping();
        }

        assertThat( p.getPingCount(), is( equalTo( EXPECTED_PING_COUNT ) ) );

        Map<String,String> actualQueryMap = handler.getQueryMap();
        assertThat( actualQueryMap.get( UdcConstants.PING ), is( Integer.toString( EXPECTED_PING_COUNT ) ) );
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public shouldIncludePingCountInURI() : void from class org.neo4j.ext.udc.impl.PingerTest


    @Test
    public void normalPingSequenceShouldBeOneThenTwoThenThreeEtc() throws Exception
    {
        int[] expectedSequence = {1, 2, 3, 4};
        final HostnamePort hostURL = new HostnamePort( hostname, server.getLocalPort() );
        final Map<String,String> udcFields = new HashMap<>();

        Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) );
        for ( int s : expectedSequence )
        {
            p.ping();
            int count = Integer.parseInt( handler.getQueryMap().get( UdcConstants.PING ) );
            assertEquals( s, count );
        }
    }

    @Test
    public void normalPingSequenceShouldBeOneThenTwoThenThreeEtc() throws Exception
    {
        int[] expectedSequence = {1, 2, 3, 4};
        final HostnamePort hostURL = new HostnamePort( hostname, server.getLocalPort() );
        final Map<String,String> udcFields = new HashMap<String,String>();

        Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ) );
        for ( int s : expectedSequence )
        {
            p.ping();
            int count = Integer.parseInt( handler.getQueryMap().get( UdcConstants.PING ) );
            assertEquals( s, count );
        }
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public normalPingSequenceShouldBeOneThenTwoThenThreeEtc() : void from class org.neo4j.ext.udc.impl.PingerTest


    @Test
    public void crashPingSequenceShouldBeMinusOneThenTwoThenThreeEtc() throws Exception
    {
        int[] expectedSequence = {-1, 2, 3, 4};
        final HostnamePort hostURL = new HostnamePort( hostname, server.getLocalPort() );
        final Map<String,String> udcFields = new HashMap<>();

        Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ).withCrash() );
        for ( int s : expectedSequence )
        {
            p.ping();
            int count = Integer.parseInt( handler.getQueryMap().get( UdcConstants.PING ) );
            assertEquals( s, count );
        }
    }

    @Test
    public void crashPingSequenceShouldBeMinusOneThenTwoThenThreeEtc() throws Exception
    {
        int[] expectedSequence = {-1, 2, 3, 4};
        final HostnamePort hostURL = new HostnamePort( hostname, server.getLocalPort() );
        final Map<String,String> udcFields = new HashMap<String,String>();

        Pinger p = new Pinger( hostURL, new TestUdcCollector( udcFields ).withCrash() );
        for ( int s : expectedSequence )
        {
            p.ping();
            int count = Integer.parseInt( handler.getQueryMap().get( UdcConstants.PING ) );
            assertEquals( s, count );
        }
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public crashPingSequenceShouldBeMinusOneThenTwoThenThreeEtc() : void from class org.neo4j.ext.udc.impl.PingerTest


    private static List<List<String>> permutations( List<String> list )
    {
        List<List<String>> result = new ArrayList<>();
        permutations( result, new ArrayList<>(), list );
        return result;
    }

    private static List<List<String>> permutations( List<String> list )
    {
        List<List<String>> result = new ArrayList<>();
        permutations( result, new ArrayList<String>(), list );
        return result;
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method private permutations(list List<String>) : List<List<String>> from class org.neo4j.backup.BackupToolCmdArgumentsAcceptanceTest


    private int dump( String filenameOrDirectory, PrintStream out )
            throws IOException, DamagedLogStorageException, DisposedException
    {
        LogProvider logProvider = NullLogProvider.getInstance();
        final int[] logsFound = {0};
        FileNames fileNames = new FileNames( new File( filenameOrDirectory ) );
        ReaderPool readerPool = new ReaderPool( 0, logProvider, fileNames, fileSystem, Clocks.systemClock() );
        RecoveryProtocol recoveryProtocol =
                new RecoveryProtocol( fileSystem, fileNames, readerPool, marshal, logProvider );
        Segments segments = recoveryProtocol.run().segments;

        segments.visit( segment -> {
                logsFound[0]++;
                out.println( "=== " + segment.getFilename() + " ===" );

                SegmentHeader header = segment.header();

                out.println( header.toString() );

                try ( IOCursor<EntryRecord> cursor = segment.getCursor( header.prevIndex() + 1 ) )
                {
                    while ( cursor.next() )
                    {
                        out.println( cursor.get().toString() );
                    }
                }
                catch ( DisposedException | IOException e )
                {
                    e.printStackTrace();
                    System.exit( -1 );
                    return true;
                }

            return false;
        } );

        return logsFound[0];
    }

    private int dump( String filenameOrDirectory, PrintStream out )
            throws IOException, DamagedLogStorageException, DisposedException
    {
        LogProvider logProvider = NullLogProvider.getInstance();
        final int[] logsFound = {0};
        FileNames fileNames = new FileNames( new File( filenameOrDirectory ) );
        ReaderPool readerPool = new ReaderPool( 0, logProvider, fileNames, fileSystem, Clocks.systemClock() );
        RecoveryProtocol recoveryProtocol =
                new RecoveryProtocol( fileSystem, fileNames, readerPool, marshal, logProvider );
        Segments segments = recoveryProtocol.run().segments;

        segments.visit( segment ->
        {
                logsFound[0]++;
                out.println( "=== " + segment.getFilename() + " ===" );

                SegmentHeader header = segment.header();

                out.println( header.toString() );

                try ( IOCursor<EntryRecord> cursor = segment.getCursor( header.prevIndex() + 1 ) )
                {
                    while ( cursor.next() )
                    {
                        out.println( cursor.get().toString() );
                    }
                }
                catch ( DisposedException e )
                {
                    e.printStackTrace();
                    System.exit( -1 );
                    return true;
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                    System.exit( -1 );
                    return true;
                }

                return false;
        } );

        return logsFound[0];
    }

Merge Catch [catch(DisposedException e), catch(IOException e)] to catch(DisposedException|IOException e) in method private dump(filenameOrDirectory String, out PrintStream) : int from class org.neo4j.causalclustering.core.consensus.log.segmented.DumpSegmentedRaftLog


    @Test( timeout = 3_000 )
    public void shouldGiveUpQueueingOnStop() throws Throwable
    {
        // given
        for ( int i = 1; i <= maxBatchSize; i++ ) // fell the queue
        {
            txApplier.queue( createTxWithId( startTxId + i ) );
        }

        // when
        CountDownLatch latch = new CountDownLatch( 1 );
        Thread thread = new Thread( () -> {
            latch.countDown();
            try
            {
                txApplier.queue( createTxWithId( startTxId + maxBatchSize + 1 ) );
            }
            catch ( Exception e )
            {
                throw new RuntimeException( e );
            }
        } );

        thread.start();

        latch.await();
        txApplier.stop();

        // then we don't get stuck
        thread.join();
    }

    @Test( timeout = 3_000 )
    public void shouldGiveUpQueueingOnStop() throws Throwable
    {
        // given
        for ( int i = 1; i <= maxBatchSize; i++ ) // fell the queue
        {
            txApplier.queue( createTxWithId( startTxId + i ) );
        }

        // when
        CountDownLatch latch = new CountDownLatch( 1 );
        Thread thread = new Thread()
        {
            @Override
            public void run()
            {
                latch.countDown();
                try
                {
                    txApplier.queue( createTxWithId( startTxId + maxBatchSize + 1 ) );
                }
                catch ( Exception e )
                {
                    throw new RuntimeException( e );
                }
            }
        };

        thread.start();

        latch.await();
        txApplier.stop();

        // then we don't get stuck
        thread.join();
    }

Replace Anonymous With Lambda org.neo4j.causalclustering.catchup.tx.BatchingTxApplierTest.shouldGiveUpQueueingOnStop.thread.new Thread with () -> {latch.countDown(); in method public shouldGiveUpQueueingOnStop() : void from class org.neo4j.causalclustering.catchup.tx.BatchingTxApplierTest


    @Override
    public Timer create( TimerName name, JobScheduler.Group group, TimeoutHandler handler )
    {
        TimeoutHandler countingHandler = timer -> {
            long count = counts.getOrDefault( name.name(), 0L );
            counts.put( name.name(), count + 1 );
            handler.onTimeout( timer );
        };
        return super.create( name, group, countingHandler );
    }

    @Override
    public Timer create( TimerName name, JobScheduler.Group group, TimeoutHandler handler )
    {
        TimeoutHandler countingHandler = new TimeoutHandler()
        {
            @Override
            public void onTimeout( Timer timer ) throws Exception
            {
                long count = counts.getOrDefault( name.name(), 0L );
                counts.put( name.name(), count + 1 );
                handler.onTimeout( timer );
            }
        };
        return super.create( name, group, countingHandler );
    }

Replace Anonymous With Lambda org.neo4j.causalclustering.core.consensus.schedule.CountingTimerService.create.countingHandler.new TimeoutHandler with timer -> {long count=counts.getOrDefault(name.name(),0L); in method public create(name TimerName, group JobScheduler.Group, handler TimeoutHandler) : Timer from class org.neo4j.causalclustering.core.consensus.schedule.CountingTimerService


    public void drain()
    {
        List<Runnable> currentRunnables;
        synchronized ( this )
        {
            currentRunnables = runnables;
            runnables = new ArrayList<>();
        }
        for ( Runnable runnable : currentRunnables )
        {
            try
            {
                runnable.run();
            }
            catch ( Throwable t )
            {
                log.error( "Runnable failed", t );
            }
        }
    }

    public void drain()
    {
        List<Runnable> currentRunnables;
        synchronized ( this )
        {
            currentRunnables = runnables;
            runnables = new ArrayList<Runnable>();
        }
        for ( Runnable runnable : currentRunnables )
        {
            try
            {
                runnable.run();
            }
            catch ( Throwable t )
            {
                log.error( "Runnable failed", t );
            }
        }
    }

Replace Generic With Diamond ArrayList<Runnable> with ArrayList<> in method public drain() : void from class org.neo4j.cluster.DelayedDirectExecutor


    @Override
    public String toString()
    {
        List<String> states = new ArrayList<>();
        for ( StateMachine stateMachine : stateMachines.values() )
        {
            states.add( stateMachine.getState().getClass().getSuperclass().getSimpleName() + ":" + stateMachine
                    .getState().toString() );
        }
        return states.toString();
    }

    @Override
    public String toString()
    {
        List<String> states = new ArrayList<String>();
        for ( StateMachine stateMachine : stateMachines.values() )
        {
            states.add( stateMachine.getState().getClass().getSuperclass().getSimpleName() + ":" + stateMachine
                    .getState().toString() );
        }
        return states.toString();
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public toString() : String from class org.neo4j.cluster.StateMachines


    public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> to( MESSAGETYPE messageType, URI to,
                                                                             Object payload )
    {
        return new Message<>( messageType, payload ).setHeader( TO, to.toString() );
    }

    public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> to( MESSAGETYPE messageType, URI to,
                                                                             Object payload )
    {
        return new Message<MESSAGETYPE>( messageType, payload ).setHeader( TO, to.toString() );
    }

Replace Generic With Diamond Message<MESSAGETYPE> with Message<> in method public to(messageType MESSAGETYPE, to URI, payload Object) : Message<MESSAGETYPE> from class org.neo4j.cluster.com.message.Message


    public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> internal( MESSAGETYPE message, Object payload )
    {
        return new Message<>( message, payload );
    }

    public static <MESSAGETYPE extends MessageType> Message<MESSAGETYPE> internal( MESSAGETYPE message, Object payload )
    {
        return new Message<MESSAGETYPE>( message, payload );
    }

Replace Generic With Diamond Message<MESSAGETYPE> with Message<> in method public internal(message MESSAGETYPE, payload Object) : Message<MESSAGETYPE> from class org.neo4j.cluster.com.message.Message


    private void updateWirePayloadSuid( ObjectStreamClass wirePayload )
    {
        try
        {
            Field field = getAccessibleSuidField( wirePayload );
            field.set( wirePayload, versionMapper.mappingFor( wirePayload.getName() ) );
        }
        catch ( NoSuchFieldException | IllegalAccessException e )
        {
            throw new RuntimeException( e );
        }
    }

    private void updateWirePayloadSuid( ObjectStreamClass wirePayload )
    {
        try
        {
            Field field = getAccessibleSuidField( wirePayload );
            field.set( wirePayload, versionMapper.mappingFor( wirePayload.getName() ) );
        }
        catch ( NoSuchFieldException e )
        {
            throw new RuntimeException( e );
        }
        catch ( IllegalAccessException e )
        {
            throw new RuntimeException( e );
        }
    }

Merge Catch [catch(NoSuchFieldException e), catch(IllegalAccessException e)] to catch(NoSuchFieldException|IllegalAccessException e) in method private updateWirePayloadSuid(wirePayload ObjectStreamClass) : void from class org.neo4j.cluster.protocol.atomicbroadcast.LenientObjectOutputStream


    private static List<URI> determineAcceptorSet( Message<ProposerMessage> message, ProposerContext context )
    {
        Object payload = message.getPayload();

        if ( payload instanceof ClusterMessage.ConfigurationChangeState )
        {
            ClusterMessage.ConfigurationChangeState state = message.getPayload();
            List<URI> acceptors = context.getAcceptors();

            Map<org.neo4j.cluster.InstanceId, URI> currentMembers = context.getMembers();

            // Never include node that is leaving
            if ( state.getLeave() != null )
            {
                acceptors = new ArrayList<>( acceptors );
                acceptors.remove( currentMembers.get(state.getLeave()) );
            }

            if ( state.getJoin() != null && currentMembers.containsKey( state.getJoin() ) )
            {
                acceptors.remove( currentMembers.get( state.getJoin() ) );
                if ( !acceptors.contains( state.getJoinUri() ) )
                {
                    acceptors.add( state.getJoinUri() );
                }
            }
            return acceptors;
        }
        else
        {
            return context.getAcceptors();
        }
    }

    private static List<URI> determineAcceptorSet( Message<ProposerMessage> message, ProposerContext context )
    {
        Object payload = message.getPayload();

        if ( payload instanceof ClusterMessage.ConfigurationChangeState )
        {
            ClusterMessage.ConfigurationChangeState state = message.getPayload();
            List<URI> acceptors = context.getAcceptors();

            Map<org.neo4j.cluster.InstanceId, URI> currentMembers = context.getMembers();

            // Never include node that is leaving
            if ( state.getLeave() != null )
            {
                acceptors = new ArrayList<URI>( acceptors );
                acceptors.remove( currentMembers.get(state.getLeave()) );
            }

            if ( state.getJoin() != null && currentMembers.containsKey( state.getJoin() ) )
            {
                acceptors.remove( currentMembers.get( state.getJoin() ) );
                if ( !acceptors.contains( state.getJoinUri() ) )
                {
                    acceptors.add( state.getJoinUri() );
                }
            }
            return acceptors;
        }
        else
        {
            return context.getAcceptors();
        }
    }

Replace Generic With Diamond ArrayList<URI> with ArrayList<> in method private determineAcceptorSet(message Message<ProposerMessage>, context ProposerContext) : List<URI> from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.ProposerState


        private Election( WinnerStrategy winnerStrategy )
        {
            this.winnerStrategy = winnerStrategy;
            this.votes = new HashMap<>();
        }

        private Election( WinnerStrategy winnerStrategy )
        {
            this.winnerStrategy = winnerStrategy;
            this.votes = new HashMap<InstanceId,Vote>();
        }

Replace Generic With Diamond HashMap<InstanceId,Vote> with HashMap<> in method private Election(winnerStrategy WinnerStrategy) from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.context.ElectionContextImpl.Election


    public void addStateTransitionListener( StateTransitionListener listener )
    {
        List<StateTransitionListener> newlisteners = new ArrayList<>( listeners );
        newlisteners.add( listener );
        listeners = newlisteners;
    }

    public void addStateTransitionListener( StateTransitionListener listener )
    {
        List<StateTransitionListener> newlisteners = new ArrayList<StateTransitionListener>( listeners );
        newlisteners.add( listener );
        listeners = newlisteners;
    }

Replace Generic With Diamond ArrayList<StateTransitionListener> with ArrayList<> in method public addStateTransitionListener(listener StateTransitionListener) : void from class org.neo4j.cluster.statemachine.StateMachine


    public void removeStateTransitionListener( StateTransitionListener listener )
    {
        List<StateTransitionListener> newlisteners = new ArrayList<>( listeners );
        newlisteners.remove( listener );
        listeners = newlisteners;
    }

    public void removeStateTransitionListener( StateTransitionListener listener )
    {
        List<StateTransitionListener> newlisteners = new ArrayList<StateTransitionListener>( listeners );
        newlisteners.remove( listener );
        listeners = newlisteners;
    }

Replace Generic With Diamond ArrayList<StateTransitionListener> with ArrayList<> in method public removeStateTransitionListener(listener StateTransitionListener) : void from class org.neo4j.cluster.statemachine.StateMachine


    public ClusterAssertion failed( final int failed )
    {
        final Map<Integer, InstanceAssertion> newIn = new HashMap<>( in );
        final InstanceAssertion current = in.get( failed );

        InstanceAssertion failedInstance = new InstanceAssertion()
        {{
            copy( current );
            this.isFailed = true;
        }};

        newIn.put( failed, failedInstance );

        final ClusterAssertion realThis = this;
        return new ClusterAssertion()
        {{
            copy( realThis );
            this.in = newIn;
        }};
    }

    public ClusterAssertion failed( final int failed )
    {
        final Map<Integer, InstanceAssertion> newIn = new HashMap<Integer, InstanceAssertion>( in );
        final InstanceAssertion current = in.get( failed );

        InstanceAssertion failedInstance = new InstanceAssertion()
        {{
            copy( current );
            this.isFailed = true;
        }};

        newIn.put( failed, failedInstance );

        final ClusterAssertion realThis = this;
        return new ClusterAssertion()
        {{
            copy( realThis );
            this.in = newIn;
        }};
    }

Replace Generic With Diamond HashMap<Integer,InstanceAssertion> with HashMap<> in method public failed(failed int) : ClusterAssertion from class org.neo4j.cluster.ClusterAssertion


    public ClusterAssertion elected( final int elected, final String atRole )
    {
        final Map<Integer, InstanceAssertion> newIn = new HashMap<>();
        for ( final Map.Entry<Integer, InstanceAssertion> instanceAssertionEntry : in.entrySet() )
        {
            final InstanceAssertion assertion = instanceAssertionEntry.getValue();
            if ( !instanceAssertionEntry.getValue().isFailed )
            {
                newIn.put( instanceAssertionEntry.getKey(), new InstanceAssertion()
                {{
                    copy( assertion );
                    this.roles.put( atRole, elected );
                }});
            }
            else
            {
                newIn.put( instanceAssertionEntry.getKey(), instanceAssertionEntry.getValue() );
            }
        }
        final ClusterAssertion realThis = this;
        return new ClusterAssertion()
        {{
                copy( realThis );
                this.in = newIn;
        }};
    }

    public ClusterAssertion elected( final int elected, final String atRole )
    {
        final Map<Integer, InstanceAssertion> newIn = new HashMap<Integer, InstanceAssertion>();
        for ( final Map.Entry<Integer, InstanceAssertion> instanceAssertionEntry : in.entrySet() )
        {
            final InstanceAssertion assertion = instanceAssertionEntry.getValue();
            if ( !instanceAssertionEntry.getValue().isFailed )
            {
                newIn.put( instanceAssertionEntry.getKey(), new InstanceAssertion()
                {{
                    copy( assertion );
                    this.roles.put( atRole, elected );
                }});
            }
            else
            {
                newIn.put( instanceAssertionEntry.getKey(), instanceAssertionEntry.getValue() );
            }
        }
        final ClusterAssertion realThis = this;
        return new ClusterAssertion()
        {{
                copy( realThis );
                this.in = newIn;
        }};
    }

Replace Generic With Diamond HashMap<Integer,InstanceAssertion> with HashMap<> in method public elected(elected int, atRole String) : ClusterAssertion from class org.neo4j.cluster.ClusterAssertion


    public NetworkMock( LogService logService, Monitors monitors, long tickDuration, MultipleFailureLatencyStrategy strategy,
                        MessageTimeoutStrategy timeoutStrategy )
    {
        this.monitors = monitors;
        this.tickDuration = tickDuration;
        this.strategy = strategy;
        this.timeoutStrategy = timeoutStrategy;
        this.logService = logService;
        this.log = logService.getInternalLog( NetworkMock.class );
        futureWaiter = new LinkedList<>();
    }

    public NetworkMock( LogService logService, Monitors monitors, long tickDuration, MultipleFailureLatencyStrategy strategy,
                        MessageTimeoutStrategy timeoutStrategy )
    {
        this.monitors = monitors;
        this.tickDuration = tickDuration;
        this.strategy = strategy;
        this.timeoutStrategy = timeoutStrategy;
        this.logService = logService;
        this.log = logService.getInternalLog( NetworkMock.class );
        futureWaiter = new LinkedList<Pair<Future<?>, Runnable>>();
    }

Replace Generic With Diamond LinkedList<Pair<Future<?>,Runnable>> with LinkedList<> in method public NetworkMock(logService LogService, monitors Monitors, tickDuration long, strategy MultipleFailureLatencyStrategy, timeoutStrategy MessageTimeoutStrategy) from class org.neo4j.cluster.NetworkMock


    public int tick()
    {
        // Deliver messages whose delivery time has passed
        now += tickDuration;

        //       logger.debug( "tick:"+now );

        Iterator<MessageDelivery> iter = messageDeliveries.iterator();
        while ( iter.hasNext() )
        {
            MessageDelivery messageDelivery = iter.next();
            if ( messageDelivery.getMessageDeliveryTime() <= now )
            {
                long delay = strategy.messageDelay( messageDelivery.getMessage(),
                        messageDelivery.getServer().getServer().boundAt().toString() );
                if ( delay != NetworkLatencyStrategy.LOST )
                {
                    messageDelivery.getServer().process( messageDelivery.getMessage() );
                }
                iter.remove();
            }
        }

        // Check and trigger timeouts
        for ( TestProtocolServer testServer : participants.values() )
        {
            testServer.tick( now );
        }

        // Get all sent messages from all test servers
        List<Message> messages = new ArrayList<>();
        for ( TestProtocolServer testServer : participants.values() )
        {
            testServer.sendMessages( messages );
        }

        // Now send them and figure out latency
        for ( Message message : messages )
        {
            String to = message.getHeader( Message.TO );
            long delay = 0;
            if ( message.getHeader( Message.TO ).equals( message.getHeader( Message.FROM ) ) )
            {
                log.debug( "Sending message to itself; zero latency" );
            }
            else
            {
                delay = strategy.messageDelay( message, to );
            }

            if ( delay == NetworkLatencyStrategy.LOST )
            {
                log.debug( "Send message to " + to + " was lost" );
            }
            else
            {
                TestProtocolServer server = participants.get( to );
                log.debug( "Send to " + to + ": " + message );
                messageDeliveries.add( new MessageDelivery( now + delay, message, server ) );
            }
        }

        Iterator<Pair<Future<?>, Runnable>> waiters = futureWaiter.iterator();
        while ( waiters.hasNext() )
        {
            Pair<Future<?>, Runnable> next = waiters.next();
            if ( next.first().isDone() )
            {
                next.other().run();
                waiters.remove();
            }
        }

        return messageDeliveries.size();
    }

    public int tick()
    {
        // Deliver messages whose delivery time has passed
        now += tickDuration;

        //       logger.debug( "tick:"+now );

        Iterator<MessageDelivery> iter = messageDeliveries.iterator();
        while ( iter.hasNext() )
        {
            MessageDelivery messageDelivery = iter.next();
            if ( messageDelivery.getMessageDeliveryTime() <= now )
            {
                long delay = strategy.messageDelay( messageDelivery.getMessage(),
                        messageDelivery.getServer().getServer().boundAt().toString() );
                if ( delay != NetworkLatencyStrategy.LOST )
                {
                    messageDelivery.getServer().process( messageDelivery.getMessage() );
                }
                iter.remove();
            }
        }

        // Check and trigger timeouts
        for ( TestProtocolServer testServer : participants.values() )
        {
            testServer.tick( now );
        }

        // Get all sent messages from all test servers
        List<Message> messages = new ArrayList<Message>();
        for ( TestProtocolServer testServer : participants.values() )
        {
            testServer.sendMessages( messages );
        }

        // Now send them and figure out latency
        for ( Message message : messages )
        {
            String to = message.getHeader( Message.TO );
            long delay = 0;
            if ( message.getHeader( Message.TO ).equals( message.getHeader( Message.FROM ) ) )
            {
                log.debug( "Sending message to itself; zero latency" );
            }
            else
            {
                delay = strategy.messageDelay( message, to );
            }

            if ( delay == NetworkLatencyStrategy.LOST )
            {
                log.debug( "Send message to " + to + " was lost" );
            }
            else
            {
                TestProtocolServer server = participants.get( to );
                log.debug( "Send to " + to + ": " + message );
                messageDeliveries.add( new MessageDelivery( now + delay, message, server ) );
            }
        }

        Iterator<Pair<Future<?>, Runnable>> waiters = futureWaiter.iterator();
        while ( waiters.hasNext() )
        {
            Pair<Future<?>, Runnable> next = waiters.next();
            if ( next.first().isDone() )
            {
                next.other().run();
                waiters.remove();
            }
        }

        return messageDeliveries.size();
    }

Replace Generic With Diamond ArrayList<Message> with ArrayList<> in method public tick() : int from class org.neo4j.cluster.NetworkMock


    public List<TestProtocolServer> getServers()
    {
        return new ArrayList<>( participants.values() );
    }

    public List<TestProtocolServer> getServers()
    {
        return new ArrayList<TestProtocolServer>( participants.values() );
    }

Replace Generic With Diamond ArrayList<TestProtocolServer> with ArrayList<> in method public getServers() : List<TestProtocolServer> from class org.neo4j.cluster.NetworkMock


    @Test
    public void shouldAlwaysAddItsInstanceIdToOutgoingMessages() throws Exception
    {
        InstanceId me = new InstanceId( 42 );
        final List<Message> sentOut = new LinkedList<>();

        /*
         * Lots of setup required. Must have a sender that keeps messages so we can see what the machine sent out.
         * We must have the StateMachines actually delegate the incoming message and retrieve the generated outgoing.
         * That means we need an actual StateMachine with a registered MessageType. And most of those are void
         * methods, which means lots of Answer objects.
         */
        // Given
        MessageSender sender = mock( MessageSender.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( invocation ->
        {
            sentOut.addAll( invocation.getArgument( 0 ) );
            return null;
        } ).when( sender ).process( ArgumentMatchers.<List<Message<? extends MessageType>>>any() );

        StateMachines stateMachines = new StateMachines( NullLogProvider.getInstance(), mock( StateMachines.Monitor.class ),
                mock( MessageSource.class ), sender,
                mock( Timeouts.class ), mock( DelayedDirectExecutor.class ), Runnable::run, me
        );

        // The state machine, which has a TestMessage message type and simply adds a TO header to the messages it
        // is handed to handle.
        StateMachine machine = mock( StateMachine.class );
        when( machine.getMessageType() ).then( (Answer<Object>) invocation -> TestMessage.class );
        doAnswer( invocation ->
        {
            Message message = invocation.getArgument( 0 );
            MessageHolder holder = invocation.getArgument( 1 );
            message.setHeader( Message.TO, "to://neverland" );
            holder.offer( message );
            return null;
        } ).when( machine ).handle( any( Message.class ), any( MessageHolder.class ) );
        stateMachines.addStateMachine( machine );

        // When
        stateMachines.process( Message.internal( TestMessage.message1 ) );

        // Then
        assertEquals( "StateMachines should not make up messages from thin air", 1, sentOut.size() );
        Message sent = sentOut.get( 0 );
        assertTrue( "StateMachines should add the instance-id header", sent.hasHeader( Message.INSTANCE_ID ) );
        assertEquals( "StateMachines should add instance-id header that has the correct value",
                me.toString(), sent.getHeader( Message.INSTANCE_ID ) );
    }

    @Test
    public void shouldAlwaysAddItsInstanceIdToOutgoingMessages() throws Exception
    {
        InstanceId me = new InstanceId( 42 );
        final List<Message> sentOut = new LinkedList<Message>();

        /*
         * Lots of setup required. Must have a sender that keeps messages so we can see what the machine sent out.
         * We must have the StateMachines actually delegate the incoming message and retrieve the generated outgoing.
         * That means we need an actual StateMachine with a registered MessageType. And most of those are void
         * methods, which means lots of Answer objects.
         */
        // Given
        MessageSender sender = mock( MessageSender.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( invocation ->
        {
            sentOut.addAll( invocation.getArgument( 0 ) );
            return null;
        } ).when( sender ).process( ArgumentMatchers.<List<Message<? extends MessageType>>>any() );

        StateMachines stateMachines = new StateMachines( NullLogProvider.getInstance(), mock( StateMachines.Monitor.class ),
                mock( MessageSource.class ), sender,
                mock( Timeouts.class ), mock( DelayedDirectExecutor.class ), Runnable::run, me
        );

        // The state machine, which has a TestMessage message type and simply adds a TO header to the messages it
        // is handed to handle.
        StateMachine machine = mock( StateMachine.class );
        when( machine.getMessageType() ).then( (Answer<Object>) invocation -> TestMessage.class );
        doAnswer( invocation ->
        {
            Message message = invocation.getArgument( 0 );
            MessageHolder holder = invocation.getArgument( 1 );
            message.setHeader( Message.TO, "to://neverland" );
            holder.offer( message );
            return null;
        } ).when( machine ).handle( any( Message.class ), any( MessageHolder.class ) );
        stateMachines.addStateMachine( machine );

        // When
        stateMachines.process( Message.internal( TestMessage.message1 ) );

        // Then
        assertEquals( "StateMachines should not make up messages from thin air", 1, sentOut.size() );
        Message sent = sentOut.get( 0 );
        assertTrue( "StateMachines should add the instance-id header", sent.hasHeader( Message.INSTANCE_ID ) );
        assertEquals( "StateMachines should add instance-id header that has the correct value",
                me.toString(), sent.getHeader( Message.INSTANCE_ID ) );
    }

Replace Generic With Diamond LinkedList<Message> with LinkedList<> in method public shouldAlwaysAddItsInstanceIdToOutgoingMessages() : void from class org.neo4j.cluster.StateMachinesTest


    public static Iterable<InstanceId> ids( int size )
    {
        List<InstanceId> ids = new ArrayList<>();
        for ( int i = 1; i <= size; i++ )
        {
            ids.add( new InstanceId( i ) );
        }
        return ids;
    }

    public static Iterable<InstanceId> ids( int size )
    {
        List<InstanceId> ids = new ArrayList<InstanceId>();
        for ( int i = 1; i <= size; i++ )
        {
            ids.add( new InstanceId( i ) );
        }
        return ids;
    }

Replace Generic With Diamond ArrayList<InstanceId> with ArrayList<> in method public ids(size int) : Iterable<InstanceId> from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.ClusterProtocolAtomicbroadcastTestUtil


    public static Map<InstanceId,URI> members( int size )
    {
        Map<InstanceId,URI> members = new HashMap<>();
        for ( int i = 1; i <= size; i++ )
        {
            members.put( new InstanceId( i ), URI.create( "http://localhost:" + (6000 + i) + "?serverId=" + i ) );
        }
        return members;
    }

    public static Map<InstanceId,URI> members( int size )
    {
        Map<InstanceId,URI> members = new HashMap<InstanceId,URI>();
        for ( int i = 1; i <= size; i++ )
        {
            members.put( new InstanceId( i ), URI.create( "http://localhost:" + (6000 + i) + "?serverId=" + i ) );
        }
        return members;
    }

Replace Generic With Diamond HashMap<InstanceId,URI> with HashMap<> in method public members(size int) : Map<InstanceId,URI> from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.ClusterProtocolAtomicbroadcastTestUtil


    @Test
    public void testFailure() throws Exception
    {
        ScriptableNetworkFailureLatencyStrategy networkLatency = new ScriptableNetworkFailureLatencyStrategy();
        NetworkMock network = new NetworkMock( NullLogService.getInstance(), new Monitors(), 50,
                new MultipleFailureLatencyStrategy( networkLatency ),
                new MessageTimeoutStrategy( new FixedTimeoutStrategy( 1000 ) ) );

        List<TestProtocolServer> nodes = new ArrayList<>();

        TestProtocolServer server = network.addServer( 1, URI.create( "cluster://server1" ) );
        server.newClient( Cluster.class ).create( "default" );
        network.tickUntilDone();
        nodes.add( server );

        for ( int i = 1; i < 3; i++ )
        {
            TestProtocolServer protocolServer = network.addServer( i + 1, new URI( "cluster://server" + (i + 1) ) );
            protocolServer.newClient( Cluster.class ).join( "default", new URI( "cluster://server1" ) );
            network.tick( 10 );
            nodes.add( protocolServer );
        }

        final AtomicBroadcast atomicBroadcast = nodes.get( 0 ).newClient( AtomicBroadcast.class );
        ObjectStreamFactory objectStreamFactory = new ObjectStreamFactory();
        final AtomicBroadcastSerializer serializer = new AtomicBroadcastSerializer( objectStreamFactory,
                objectStreamFactory );
        atomicBroadcast.broadcast( serializer.broadcast( new DaPayload() ) );

        networkLatency.nodeIsDown( "cluster://server2" );
        networkLatency.nodeIsDown( "cluster://server3" );

        atomicBroadcast.broadcast( serializer.broadcast( new DaPayload() ) );
        network.tick( 100 );
        networkLatency.nodeIsUp( "cluster://server3" );
        network.tick( 1000 );

        for ( TestProtocolServer node : nodes )
        {
            node.newClient( Cluster.class ).leave();
            network.tick( 10 );
        }

    }

    @Test
    public void testFailure() throws Exception
    {
        ScriptableNetworkFailureLatencyStrategy networkLatency = new ScriptableNetworkFailureLatencyStrategy();
        NetworkMock network = new NetworkMock( NullLogService.getInstance(), new Monitors(), 50,
                new MultipleFailureLatencyStrategy( networkLatency ),
                new MessageTimeoutStrategy( new FixedTimeoutStrategy( 1000 ) ) );

        List<TestProtocolServer> nodes = new ArrayList<TestProtocolServer>();

        TestProtocolServer server = network.addServer( 1, URI.create( "cluster://server1" ) );
        server.newClient( Cluster.class ).create( "default" );
        network.tickUntilDone();
        nodes.add( server );

        for ( int i = 1; i < 3; i++ )
        {
            TestProtocolServer protocolServer = network.addServer( i + 1, new URI( "cluster://server" + (i + 1) ) );
            protocolServer.newClient( Cluster.class ).join( "default", new URI( "cluster://server1" ) );
            network.tick( 10 );
            nodes.add( protocolServer );
        }

        final AtomicBroadcast atomicBroadcast = nodes.get( 0 ).newClient( AtomicBroadcast.class );
        ObjectStreamFactory objectStreamFactory = new ObjectStreamFactory();
        final AtomicBroadcastSerializer serializer = new AtomicBroadcastSerializer( objectStreamFactory,
                objectStreamFactory );
        atomicBroadcast.broadcast( serializer.broadcast( new DaPayload() ) );

        networkLatency.nodeIsDown( "cluster://server2" );
        networkLatency.nodeIsDown( "cluster://server3" );

        atomicBroadcast.broadcast( serializer.broadcast( new DaPayload() ) );
        network.tick( 100 );
        networkLatency.nodeIsUp( "cluster://server3" );
        network.tick( 1000 );

        for ( TestProtocolServer node : nodes )
        {
            node.newClient( Cluster.class ).leave();
            network.tick( 10 );
        }

    }

Replace Generic With Diamond ArrayList<TestProtocolServer> with ArrayList<> in method public testFailure() : void from class org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.MultiPaxosTest


    @Test
    public void threeNodesJoinAndThenCoordinatorDiesForReal()
            throws URISyntaxException, ExecutionException, TimeoutException, InterruptedException
    {
        final Map<String, InstanceId> roles = new HashMap<>();

        testCluster( 3, DEFAULT_NETWORK(), new ClusterTestScriptDSL().
                rounds( 1000 ).
                join( 100, 1, 1 ).
                join( 100, 2, 1 ).
                join( 100, 3, 1 ).
                message( 3000, "*** All nodes up and ok" ).
                getRoles( roles ).
                down( 800, 1 ).
                message( 2000, "*** Should have seen failure by now" ).
                verifyCoordinatorRoleSwitched( roles ).
                leave( 0, 1 ).
                leave( 300, 2 ).
                leave( 300, 3 ) );
    }

    @Test
    public void threeNodesJoinAndThenCoordinatorDiesForReal()
            throws URISyntaxException, ExecutionException, TimeoutException, InterruptedException
    {
        final Map<String, InstanceId> roles = new HashMap<String, InstanceId>();

        testCluster( 3, DEFAULT_NETWORK(), new ClusterTestScriptDSL().
                rounds( 1000 ).
                join( 100, 1, 1 ).
                join( 100, 2, 1 ).
                join( 100, 3, 1 ).
                message( 3000, "*** All nodes up and ok" ).
                getRoles( roles ).
                down( 800, 1 ).
                message( 2000, "*** Should have seen failure by now" ).
                verifyCoordinatorRoleSwitched( roles ).
                leave( 0, 1 ).
                leave( 300, 2 ).
                leave( 300, 3 ) );
    }

Replace Generic With Diamond HashMap<String,InstanceId> with HashMap<> in method public threeNodesJoinAndThenCoordinatorDiesForReal() : void from class org.neo4j.cluster.protocol.cluster.ClusterHeartbeatTest


                @Override
                public void run()
                {
                    HashMap<String, InstanceId> roles = new HashMap<>();
                    ClusterMockTest.this.getRoles( roles );
                    InstanceId oldCoordinator = comparedTo.get( ClusterConfiguration.COORDINATOR );
                    InstanceId newCoordinator = roles.get( ClusterConfiguration.COORDINATOR );
                    assertNotNull( "Should have had a coordinator before bringing it down", oldCoordinator );
                    assertNotNull( "Should have a new coordinator after the previous failed", newCoordinator );
                    assertTrue( "Should have elected a new coordinator", !oldCoordinator.equals( newCoordinator ) );
                }

                @Override
                public void run()
                {
                    HashMap<String, InstanceId> roles = new HashMap<String, InstanceId>();
                    ClusterMockTest.this.getRoles( roles );
                    InstanceId oldCoordinator = comparedTo.get( ClusterConfiguration.COORDINATOR );
                    InstanceId newCoordinator = roles.get( ClusterConfiguration.COORDINATOR );
                    assertNotNull( "Should have had a coordinator before bringing it down", oldCoordinator );
                    assertNotNull( "Should have a new coordinator after the previous failed", newCoordinator );
                    assertTrue( "Should have elected a new coordinator", !oldCoordinator.equals( newCoordinator ) );
                }

Replace Generic With Diamond HashMap<String,InstanceId> with HashMap<> in method public run() : void from class org.neo4j.cluster.protocol.cluster.ClusterMockTest.ClusterTestScriptDSL.verifyCoordinatorRoleSwitched.addAction.new ClusterAction


        public ClusterTestScriptDSL verifyCoordinatorRoleSwitched( final Map<String, InstanceId> comparedTo )
        {
            return addAction( new ClusterAction()
            {
                @Override
                public void run()
                {
                    HashMap<String, InstanceId> roles = new HashMap<>();
                    ClusterMockTest.this.getRoles( roles );
                    InstanceId oldCoordinator = comparedTo.get( ClusterConfiguration.COORDINATOR );
                    InstanceId newCoordinator = roles.get( ClusterConfiguration.COORDINATOR );
                    assertNotNull( "Should have had a coordinator before bringing it down", oldCoordinator );
                    assertNotNull( "Should have a new coordinator after the previous failed", newCoordinator );
                    assertTrue( "Should have elected a new coordinator", !oldCoordinator.equals( newCoordinator ) );
                }
            }, 0 );
        }

        public ClusterTestScriptDSL verifyCoordinatorRoleSwitched( final Map<String, InstanceId> comparedTo )
        {
            return addAction( new ClusterAction()
            {
                @Override
                public void run()
                {
                    HashMap<String, InstanceId> roles = new HashMap<String, InstanceId>();
                    ClusterMockTest.this.getRoles( roles );
                    InstanceId oldCoordinator = comparedTo.get( ClusterConfiguration.COORDINATOR );
                    InstanceId newCoordinator = roles.get( ClusterConfiguration.COORDINATOR );
                    assertNotNull( "Should have had a coordinator before bringing it down", oldCoordinator );
                    assertNotNull( "Should have a new coordinator after the previous failed", newCoordinator );
                    assertTrue( "Should have elected a new coordinator", !oldCoordinator.equals( newCoordinator ) );
                }
            }, 0 );
        }

Replace Generic With Diamond HashMap<String,InstanceId> with HashMap<> in method public verifyCoordinatorRoleSwitched(comparedTo Map<String,InstanceId>) : ClusterTestScriptDSL from class org.neo4j.cluster.protocol.cluster.ClusterMockTest.ClusterTestScriptDSL


                @Override
                public void receive( Payload value )
                {
                    try
                    {
                        logger.getLogger().fine( uri + " received: " + serializer.receive( value ) );
                    }
                    catch ( IOException | ClassNotFoundException e )
                    {
                        e.printStackTrace();
                    }
                }

                @Override
                public void receive( Payload value )
                {
                    try
                    {
                        logger.getLogger().fine( uri + " received: " + serializer.receive( value ) );
                    }
                    catch ( IOException e )
                    {
                        e.printStackTrace();
                    }
                    catch ( ClassNotFoundException e )
                    {
                        e.printStackTrace();
                    }
                }

Merge Catch [catch(IOException e), catch(ClassNotFoundException e)] to catch(IOException|ClassNotFoundException e) in method public receive(value Payload) : void from class org.neo4j.cluster.protocol.cluster.ClusterMockTest.testCluster.addAtomicBroadcastListener.new AtomicBroadcastListener


    public void verifyConfigurations( VerifyInstanceConfiguration[] toCheckAgainst )
    {
        logger.getLogger().fine( "Verify configurations against given" );

        List<URI> members;
        Map<String, InstanceId> roles;
        Set<InstanceId> failed;

        List<AssertionError> errors = new LinkedList<>();

        List<TestProtocolServer> protocolServers = network.getServers();

        assertEquals( "You must provide a configuration for all instances",
                protocolServers.size(), toCheckAgainst.length );

        for ( int j = 0; j < protocolServers.size(); j++ )
        {
            members = toCheckAgainst[j].members;
            roles = toCheckAgainst[j].roles;
            failed = toCheckAgainst[j].failed;
            StateMachines stateMachines = protocolServers.get( j ).getServer().getStateMachines();

            State<?, ?> clusterState = stateMachines.getStateMachine( ClusterMessage.class ).getState();
            if ( !clusterState.equals( ClusterState.entered ) )
            {
                logger.getLogger().warning( "Instance " + ( j + 1 ) + " is not in the cluster (" + clusterState + ")" );
                continue;
            }

            ClusterContext context = (ClusterContext) stateMachines.getStateMachine( ClusterMessage.class )
                    .getContext();
            HeartbeatContext heartbeatContext = (HeartbeatContext) stateMachines.getStateMachine(
                    HeartbeatMessage.class ).getContext();
            ClusterConfiguration clusterConfiguration = context.getConfiguration();
            if ( !clusterConfiguration.getMemberURIs().isEmpty() )
            {
                logger.getLogger().fine( "   Server " + ( j + 1 ) + ": Cluster:" + clusterConfiguration.getMemberURIs() +
                        ", Roles:" + clusterConfiguration.getRoles() + ", Failed:" + heartbeatContext.getFailed() );
                verifyConfigurations( stateMachines, members, roles, failed, errors );
            }
        }

//        assertEquals( "In:" + in + ", Out:" + out, protocolServers.size(), Iterables.count( Iterables.<Cluster,
//                List<Cluster>>flatten( in, out ) ) );

        if ( !errors.isEmpty() )
        {
            for ( AssertionError error : errors )
            {
                logger.getLogger().severe( error.toString() );
            }
            throw errors.get( 0 );
        }
    }

    public void verifyConfigurations( VerifyInstanceConfiguration[] toCheckAgainst )
    {
        logger.getLogger().fine( "Verify configurations against given" );

        List<URI> members;
        Map<String, InstanceId> roles;
        Set<InstanceId> failed;

        List<AssertionError> errors = new LinkedList<AssertionError>();

        List<TestProtocolServer> protocolServers = network.getServers();

        assertEquals( "You must provide a configuration for all instances",
                protocolServers.size(), toCheckAgainst.length );

        for ( int j = 0; j < protocolServers.size(); j++ )
        {
            members = toCheckAgainst[j].members;
            roles = toCheckAgainst[j].roles;
            failed = toCheckAgainst[j].failed;
            StateMachines stateMachines = protocolServers.get( j ).getServer().getStateMachines();

            State<?, ?> clusterState = stateMachines.getStateMachine( ClusterMessage.class ).getState();
            if ( !clusterState.equals( ClusterState.entered ) )
            {
                logger.getLogger().warning( "Instance " + ( j + 1 ) + " is not in the cluster (" + clusterState + ")" );
                continue;
            }

            ClusterContext context = (ClusterContext) stateMachines.getStateMachine( ClusterMessage.class )
                    .getContext();
            HeartbeatContext heartbeatContext = (HeartbeatContext) stateMachines.getStateMachine(
                    HeartbeatMessage.class ).getContext();
            ClusterConfiguration clusterConfiguration = context.getConfiguration();
            if ( !clusterConfiguration.getMemberURIs().isEmpty() )
            {
                logger.getLogger().fine( "   Server " + ( j + 1 ) + ": Cluster:" + clusterConfiguration.getMemberURIs() +
                        ", Roles:" + clusterConfiguration.getRoles() + ", Failed:" + heartbeatContext.getFailed() );
                verifyConfigurations( stateMachines, members, roles, failed, errors );
            }
        }

//        assertEquals( "In:" + in + ", Out:" + out, protocolServers.size(), Iterables.count( Iterables.<Cluster,
//                List<Cluster>>flatten( in, out ) ) );

        if ( !errors.isEmpty() )
        {
            for ( AssertionError error : errors )
            {
                logger.getLogger().severe( error.toString() );
            }
            throw errors.get( 0 );
        }
    }

Replace Generic With Diamond LinkedList<AssertionError> with LinkedList<> in method public verifyConfigurations(toCheckAgainst VerifyInstanceConfiguration[]) : void from class org.neo4j.cluster.protocol.cluster.ClusterMockTest


    public void verifyConfigurations( String description )
    {
        logger.getLogger().fine( "Verify configurations" );

        List<URI> members = null;
        Map<String, InstanceId> roles = null;
        Set<InstanceId> failed = null;

        List<AssertionError> errors = new LinkedList<>();

        List<TestProtocolServer> protocolServers = network.getServers();

        for ( int j = 0; j < protocolServers.size(); j++ )
        {
            StateMachines stateMachines = protocolServers.get( j ).getServer().getStateMachines();

            State<?, ?> clusterState = stateMachines.getStateMachine( ClusterMessage.class ).getState();
            if ( !clusterState.equals( ClusterState.entered ) )
            {
                logger.getLogger().fine( "Instance " + ( j + 1 ) + " is not in the cluster (" + clusterState + ")" );
                continue;
            }

            ClusterContext context = (ClusterContext) stateMachines.getStateMachine( ClusterMessage.class )
                    .getContext();
            HeartbeatContext heartbeatContext = (HeartbeatContext) stateMachines.getStateMachine(
                    HeartbeatMessage.class ).getContext();
            ClusterConfiguration clusterConfiguration = context.getConfiguration();
            if ( !clusterConfiguration.getMemberURIs().isEmpty() )
            {
                logger.getLogger().fine( "   Server " + ( j + 1 ) + ": Cluster:" + clusterConfiguration.getMemberURIs() +
                        ", Roles:" + clusterConfiguration.getRoles() + ", Failed:" + heartbeatContext.getFailed() );
                if ( members == null )
                {
                    members = clusterConfiguration.getMemberURIs();
                    roles = clusterConfiguration.getRoles();
                    failed = heartbeatContext.getFailed();
                }
                else
                {
                    verifyConfigurations( stateMachines, members, roles, failed, errors );
                }
            }
        }

        assertEquals( description + ": In:" + in + ", Out:" + out, protocolServers.size(),
                Iterables.count( Iterables.flatten( in, out ) ) );

        if ( !errors.isEmpty() )
        {
            for ( AssertionError error : errors )
            {
                logger.getLogger().severe( error.toString() );
            }
            throw errors.get( 0 );
        }
    }

    public void verifyConfigurations( String description )
    {
        logger.getLogger().fine( "Verify configurations" );

        List<URI> members = null;
        Map<String, InstanceId> roles = null;
        Set<InstanceId> failed = null;

        List<AssertionError> errors = new LinkedList<AssertionError>();

        List<TestProtocolServer> protocolServers = network.getServers();

        for ( int j = 0; j < protocolServers.size(); j++ )
        {
            StateMachines stateMachines = protocolServers.get( j ).getServer().getStateMachines();

            State<?, ?> clusterState = stateMachines.getStateMachine( ClusterMessage.class ).getState();
            if ( !clusterState.equals( ClusterState.entered ) )
            {
                logger.getLogger().fine( "Instance " + ( j + 1 ) + " is not in the cluster (" + clusterState + ")" );
                continue;
            }

            ClusterContext context = (ClusterContext) stateMachines.getStateMachine( ClusterMessage.class )
                    .getContext();
            HeartbeatContext heartbeatContext = (HeartbeatContext) stateMachines.getStateMachine(
                    HeartbeatMessage.class ).getContext();
            ClusterConfiguration clusterConfiguration = context.getConfiguration();
            if ( !clusterConfiguration.getMemberURIs().isEmpty() )
            {
                logger.getLogger().fine( "   Server " + ( j + 1 ) + ": Cluster:" + clusterConfiguration.getMemberURIs() +
                        ", Roles:" + clusterConfiguration.getRoles() + ", Failed:" + heartbeatContext.getFailed() );
                if ( members == null )
                {
                    members = clusterConfiguration.getMemberURIs();
                    roles = clusterConfiguration.getRoles();
                    failed = heartbeatContext.getFailed();
                }
                else
                {
                    verifyConfigurations( stateMachines, members, roles, failed, errors );
                }
            }
        }

        assertEquals( description + ": In:" + in + ", Out:" + out, protocolServers.size(),
                Iterables.count( Iterables.flatten( in, out ) ) );

        if ( !errors.isEmpty() )
        {
            for ( AssertionError error : errors )
            {
                logger.getLogger().severe( error.toString() );
            }
            throw errors.get( 0 );
        }
    }

Replace Generic With Diamond LinkedList<AssertionError> with LinkedList<> in method public verifyConfigurations(description String) : void from class org.neo4j.cluster.protocol.cluster.ClusterMockTest


    @Test
    public void twoVotesFromSameInstanceForSameRoleShouldBeConsolidated() throws Exception
    {
        // Given
        final String coordinatorRole = "coordinator";
        HeartbeatContext heartbeatContext = mock(HeartbeatContext.class);
        when( heartbeatContext.getFailed() ).thenReturn( Collections.emptySet() );

        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( coordinatorRole ) ),
                        clusterConfiguration, mock( Executor.class ), NullLogProvider.getInstance(),
                        mock( ObjectInputStreamFactory.class ), mock( ObjectOutputStreamFactory.class ),
                        mock( AcceptorInstanceStore.class ), mock( Timeouts.class ),
                        mock( ElectionCredentialsProvider.class ), config );

        ElectionContext toTest = context.getElectionContext();

        // When
        toTest.startElectionProcess( coordinatorRole );
        toTest.voted( coordinatorRole, new InstanceId( 1 ), new IntegerElectionCredentials( 100 ), ClusterContext.NO_ELECTOR_VERSION );
        toTest.voted( coordinatorRole, new InstanceId( 2 ), new IntegerElectionCredentials( 100 ), ClusterContext.NO_ELECTOR_VERSION );
        toTest.voted( coordinatorRole, new InstanceId( 2 ), new IntegerElectionCredentials( 101 ), ClusterContext.NO_ELECTOR_VERSION );

        // Then
        assertNull( toTest.getElectionWinner( coordinatorRole ) );
        assertEquals( 2, toTest.getVoteCount( coordinatorRole ) );
    }

    @Test
    public void twoVotesFromSameInstanceForSameRoleShouldBeConsolidated() throws Exception
    {
        // Given
        final String coordinatorRole = "coordinator";
        HeartbeatContext heartbeatContext = mock(HeartbeatContext.class);
        when( heartbeatContext.getFailed() ).thenReturn( Collections.emptySet() );

        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( coordinatorRole ) ),
                        clusterConfiguration, mock( Executor.class ), NullLogProvider.getInstance(),
                        mock( ObjectInputStreamFactory.class ), mock( ObjectOutputStreamFactory.class ),
                        mock( AcceptorInstanceStore.class ), mock( Timeouts.class ),
                        mock( ElectionCredentialsProvider.class ), config );

        ElectionContext toTest = context.getElectionContext();

        // When
        toTest.startElectionProcess( coordinatorRole );
        toTest.voted( coordinatorRole, new InstanceId( 1 ), new IntegerElectionCredentials( 100 ), ClusterContext.NO_ELECTOR_VERSION );
        toTest.voted( coordinatorRole, new InstanceId( 2 ), new IntegerElectionCredentials( 100 ), ClusterContext.NO_ELECTOR_VERSION );
        toTest.voted( coordinatorRole, new InstanceId( 2 ), new IntegerElectionCredentials( 101 ), ClusterContext.NO_ELECTOR_VERSION );

        // Then
        assertNull( toTest.getElectionWinner( coordinatorRole ) );
        assertEquals( 2, toTest.getVoteCount( coordinatorRole ) );
    }

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