    @Test
    public void shouldWriteEntriesToTheCountsStore() throws IOException
    {
        // given
        final CountsStoreWriter writer = new CountsStoreWriter( fs, pageCache, emptyHeader, file, lastTxId );

        // when
        DoubleLongRegister valueRegister = Registers.newDoubleLongRegister();
        valueRegister.write( 0, 42 );
        writer.visit( nodeKey( 0 ), valueRegister );
        valueRegister.write( 0, 24 );
        writer.visit( relationshipKey( 1, 2, 3 ), valueRegister );
        valueRegister.write( 9, 11 );
        writer.visit( indexCountsKey( 4, 5 ), valueRegister );
        valueRegister.write( 24, 84 );
        writer.visit( indexSampleKey( 4, 5 ), valueRegister );
        writer.close();

        // then
        try ( SortedKeyValueStore counts = writer.openForReading() )
        {
            assertEquals( lastTxId, counts.lastTxId() );
            assertEquals( 4, counts.totalRecordsStored() );
            assertEquals( file, counts.file() );
            counts.accept( new KeyValueRecordVisitor<CountsKey, DoubleLongRegister>()
            {
                @Override
                public void visit( CountsKey key, DoubleLongRegister valueRegister )
                {
                    key.accept( new CountsVisitor()
                    {
                        @Override
                        public void visitNodeCount( int labelId, long count )
                        {
                            assertEquals( 0, labelId );
                            assertEquals( 42, count );
                        }

                        @Override
                        public void visitRelationshipCount( int startLabelId, int typeId, int endLabelId, long count )
                        {
                            assertEquals( 1, startLabelId );
                            assertEquals( 2, typeId );
                            assertEquals( 3, endLabelId );
                            assertEquals( 24, count );
                        }

                        @Override
                        public void visitIndexCounts( int labelId, int propertyKeyId, long updates, long size )
                        {
                            assertEquals( 4, labelId );
                            assertEquals( 5, propertyKeyId );
                            assertEquals( 9, updates );
                            assertEquals( 11, size );
                        }

                        @Override
                        public void visitIndexSample( int labelId, int propertyKeyId, long unique, long size )
                        {
                            assertEquals( 4, labelId );
                            assertEquals( 5, propertyKeyId );
                            assertEquals( 24, unique );
                            assertEquals( 84, size );
                        }
                    }, valueRegister.readFirst(), valueRegister.readSecond() );
                }
            }, Registers.newDoubleLongRegister() );

        }
    }

    @Test
    public void shouldWriteEntriesToTheCountsStore() throws IOException
    {
        // given
        final CountsStoreWriter writer = new CountsStoreWriter( fs, pageCache, emptyHeader, file, lastTxId );

        // when
        DoubleLongRegister valueRegister = Registers.newDoubleLongRegister();
        valueRegister.write( 0, 42 );
        writer.visit( nodeKey( 0 ), valueRegister );
        valueRegister.write( 0, 24 );
        writer.visit( relationshipKey( 1, 2, 3 ), valueRegister );
        valueRegister.write( 9, 11 );
        writer.visit( indexCountsKey( 4, 5 ), valueRegister );
        valueRegister.write( 24, 84 );
        writer.visit( indexSampleKey( 4, 5 ), valueRegister );
        writer.close();

        // then
        try
        {
            final SortedKeyValueStore counts = writer.openForReading();

            assertEquals( lastTxId, counts.lastTxId() );
            assertEquals( 4, counts.totalRecordsStored() );
            assertEquals( file, counts.file() );
            counts.accept( new KeyValueRecordVisitor<CountsKey, DoubleLongRegister>()
            {
                @Override
                public void visit( CountsKey key, DoubleLongRegister valueRegister )
                {
                    key.accept( new CountsVisitor()
                    {
                        @Override
                        public void visitNodeCount( int labelId, long count )
                        {
                            assertEquals( 0, labelId );
                            assertEquals( 42, count );
                        }

                        @Override
                        public void visitRelationshipCount( int startLabelId, int typeId, int endLabelId, long count )
                        {
                            assertEquals( 1, startLabelId );
                            assertEquals( 2, typeId );
                            assertEquals( 3, endLabelId );
                            assertEquals( 24, count );
                        }

                        @Override
                        public void visitIndexCounts( int labelId, int propertyKeyId, long updates, long size )
                        {
                            assertEquals( 4, labelId );
                            assertEquals( 5, propertyKeyId );
                            assertEquals( 9, updates );
                            assertEquals( 11, size );
                        }

                        @Override
                        public void visitIndexSample( int labelId, int propertyKeyId, long unique, long size )
                        {
                            assertEquals( 4, labelId );
                            assertEquals( 5, propertyKeyId );
                            assertEquals( 24, unique );
                            assertEquals( 84, size );
                        }
                    }, valueRegister.readFirst(), valueRegister.readSecond() );
                }
            }, Registers.newDoubleLongRegister() );

        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(SortedKeyValueStore counts=writer.openForReading()) in method public shouldWriteEntriesToTheCountsStore() : void from class org.neo4j.kernel.impl.store.counts.CountsStoreWriterTest


    @Test
    public void shouldWriteHeaderInPageFile() throws IOException
    {
        // given
        SortedKeyValueStoreHeader header =
                with( RECORD_SIZE, ALL_STORES_VERSION, BASE_TX_ID, BASE_MINOR_VERSION ).update( 42, 24, 12 );

        // when
        try ( PagedFile pagedFile = pageCache.map( file, pageCache.pageSize() ) )
        {
            header.write( pagedFile );
            pagedFile.flush();

            // then
            assertEquals( header, SortedKeyValueStoreHeader.read( RECORD_SIZE, pagedFile ) );
        }
    }

    @Test
    public void shouldWriteHeaderInPageFile() throws IOException
    {
        // given
        SortedKeyValueStoreHeader header =
                with( RECORD_SIZE, ALL_STORES_VERSION, BASE_TX_ID, BASE_MINOR_VERSION ).update( 42, 24, 12 );

        // when
        try
        {
            final PagedFile pagedFile = pageCache.map( file, pageCache.pageSize() );
            header.write( pagedFile );
            pagedFile.flush();

            // then
            assertEquals( header, SortedKeyValueStoreHeader.read( RECORD_SIZE, pagedFile ) );
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=pageCache.map(file,pageCache.pageSize())) in method public shouldWriteHeaderInPageFile() : void from class org.neo4j.kernel.impl.store.kvstore.SortedKeyValueStoreHeaderTest


    void releaseVoices( Voice[] voices, boolean failure )
    {
        List<Throwable> failures = null;
        try
        {
            failures = new ArrayList<>( voices.length );
        }
        catch ( Throwable oom )
        {
            // nothing we can do...
        }
        for ( Voice voice : voices )
        {
            if ( voice != null )
            {
                try
                {
                    voice.restore( failure );
                }
                catch ( Throwable exception )
                {
                    if ( failures != null )
                    {
                        failures.add( exception );
                    }
                }
            }
        }
        if ( failures != null && !failures.isEmpty() )
        {
            for ( Throwable exception : failures )
            {
                exception.printStackTrace();
            }
        }
    }

    void releaseVoices( Voice[] voices, boolean failure )
    {
        List<Throwable> failures = null;
        try
        {
            failures = new ArrayList<Throwable>( voices.length );
        }
        catch ( Throwable oom )
        {
            // nothing we can do...
        }
        for ( Voice voice : voices )
        {
            if ( voice != null )
            {
                try
                {
                    voice.restore( failure );
                }
                catch ( Throwable exception )
                {
                    if ( failures != null )
                    {
                        failures.add( exception );
                    }
                }
            }
        }
        if ( failures != null && !failures.isEmpty() )
        {
            for ( Throwable exception : failures )
            {
                exception.printStackTrace();
            }
        }
    }

Replace Generic With Diamond ArrayList<Throwable> with ArrayList<> in method package releaseVoices(voices Voice[], failure boolean) : void from class org.neo4j.test.Mute


    private long createACoupleOfNodes( GraphDatabaseService db, int count )
    {
        try ( Transaction tx = db.beginTx() )
        {
            long last = 0;
            for ( int i = 0; i < count; i++ )
            {
                Node node = db.createNode();
                node.setProperty( "key", "A very very very loooooooooooooooooooooooooooooooooooooooooooooong string " +
                                         "that should spill over into a dynamic record" );
                last = node.getId();
            }
            tx.success();
            return last;
        }
    }

    private long createACoupleOfNodes( GraphDatabaseService db, int count )
    {
        Transaction tx = db.beginTx();
        try
        {
            long last = 0;
            for ( int i = 0; i < count; i++ )
            {
                Node node = db.createNode();
                node.setProperty( "key", "A very very very loooooooooooooooooooooooooooooooooooooooooooooong string " +
                        "that should spill over into a dynamic record" );
                last = node.getId();
            }
            tx.success();
            return last;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createACoupleOfNodes(db GraphDatabaseService, count int) : long from class org.neo4j.kernel.impl.nioneo.store.StoreHighIdInflationTest


    @Override
    public int write( String path, ReadableByteChannel data, ByteBuffer temporaryBuffer,
            boolean hasData ) throws IOException
    {
        try
        {
            temporaryBuffer.clear();
            File file = new File( basePath, path );

            file.getParentFile().mkdirs();
            try ( RandomAccessFile randomAccessFile = new RandomAccessFile( file, "rw" ) )
            {
                int totalWritten = 0;
                if ( hasData )
                {
                    FileChannel channel = randomAccessFile.getChannel();
                    while ( data.read( temporaryBuffer ) >= 0 )
                    {
                        temporaryBuffer.flip();
                        totalWritten += temporaryBuffer.limit();
                        channel.write( temporaryBuffer );
                        temporaryBuffer.clear();
                    }
                }
                return totalWritten;
            }
        }
        catch ( Throwable t )
        {
            throw new IOException( t );
        }
    }

    @Override
    public int write( String path, ReadableByteChannel data, ByteBuffer temporaryBuffer,
            boolean hasData ) throws IOException
    {
        try
        {
            temporaryBuffer.clear();
            File file = new File( basePath, path );

            RandomAccessFile randomAccessFile = null;
            try
            {
                file.getParentFile().mkdirs();
                randomAccessFile = new RandomAccessFile( file, "rw" );
                int totalWritten = 0;
                if ( hasData )
                {
                    FileChannel channel = randomAccessFile.getChannel();
                    while ( data.read( temporaryBuffer ) >= 0 )
                    {
                        temporaryBuffer.flip();
                        totalWritten += temporaryBuffer.limit();
                        channel.write( temporaryBuffer );
                        temporaryBuffer.clear();
                    }
                }
                return totalWritten;
            }
            finally
            {
                if ( randomAccessFile != null )
                {
                    randomAccessFile.close();
                }
            }
        }
        catch ( Throwable t )
        {
            throw new IOException( t );
        }
    }

Try With Resources try(RandomAccessFile randomAccessFile=new RandomAccessFile(file,"rw")) in method public write(path String, data ReadableByteChannel, temporaryBuffer ByteBuffer, hasData boolean) : int from class org.neo4j.com.storecopy.ToFileStoreWriter


    private Config config( int lockReadTimeout )
    {
        Map<String, String> params = new HashMap<>();
        params.put( HaSettings.lock_read_timeout.name(), lockReadTimeout + "s" );
        params.put( ClusterSettings.server_id.name(), "1" );
        return new Config( params, HaSettings.class );
    }

    private Config config( int lockReadTimeout )
    {
        Map<String, String> params = new HashMap<String, String>();
        params.put( HaSettings.lock_read_timeout.name(), lockReadTimeout + "s" );
        params.put( ClusterSettings.server_id.name(), "1" );
        return new Config( params, HaSettings.class );
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method private config(lockReadTimeout int) : Config from class org.neo4j.kernel.ha.com.master.MasterImplTest


    private MBeanAttributeInfo[] keys()
    {
        List<MBeanAttributeInfo> keys = new ArrayList<>();
        for ( String key : config.keySet() )
        {
            keys.add( new MBeanAttributeInfo( key, String.class.getName(),
                                              describeConfigParameter( key ), true, false, false ) );
        }
        return keys.toArray( new MBeanAttributeInfo[keys.size()] );
    }

    private MBeanAttributeInfo[] keys()
    {
        List<MBeanAttributeInfo> keys = new ArrayList<MBeanAttributeInfo>();
        for ( String key : config.keySet() )
        {
            keys.add( new MBeanAttributeInfo( key, String.class.getName(),
                                              describeConfigParameter( key ), true, false, false ) );
        }
        return keys.toArray( new MBeanAttributeInfo[keys.size()] );
    }

Replace Generic With Diamond ArrayList<MBeanAttributeInfo> with ArrayList<> in method private keys() : MBeanAttributeInfo[] from class org.neo4j.jmx.impl.ConfigurationBean


    @Override
    public void init() throws Throwable
    {
        support = ManagementSupport.load();
        url = support.getJMXServiceURL( kernelData );
        mbs = support.getMBeanServer();
        beans = new LinkedList<>();
        try
        {
            Neo4jMBean bean = new KernelBean( kernelData, support );
            mbs.registerMBean( bean, bean.objectName );
            beans.add( bean );
        }
        catch ( Exception e )
        {
            logger.info( "Failed to register Kernel JMX Bean" );
        }

        for ( ManagementBeanProvider provider : Service.load( ManagementBeanProvider.class ) )
        {
            try
            {
                for ( Neo4jMBean bean : provider.loadBeans( kernelData, support ) )
                {
                    mbs.registerMBean( bean, bean.objectName );
                    beans.add( bean );
                }
            }
            catch ( Exception e )
            { // Unexpected exception
                logger.info( "Failed to register JMX Bean " + provider + " (" + e + ")" );
            }
        }
        try
        {
            Neo4jMBean bean = new ConfigurationBean( kernelData, support );
            mbs.registerMBean( bean, bean.objectName );
            beans.add( bean );
        }
        catch ( Exception e )
        {
            logger.info( "Failed to register Configuration JMX Bean" );
        }
    }

    @Override
    public void init() throws Throwable
    {
        support = ManagementSupport.load();
        url = support.getJMXServiceURL( kernelData );
        mbs = support.getMBeanServer();
        beans = new LinkedList<Neo4jMBean>();
        try
        {
            Neo4jMBean bean = new KernelBean( kernelData, support );
            mbs.registerMBean( bean, bean.objectName );
            beans.add( bean );
        }
        catch ( Exception e )
        {
            logger.info( "Failed to register Kernel JMX Bean" );
        }

        for ( ManagementBeanProvider provider : Service.load( ManagementBeanProvider.class ) )
        {
            try
            {
                for ( Neo4jMBean bean : provider.loadBeans( kernelData, support ) )
                {
                    mbs.registerMBean( bean, bean.objectName );
                    beans.add( bean );
                }
            }
            catch ( Exception e )
            { // Unexpected exception
                logger.info( "Failed to register JMX Bean " + provider + " (" + e + ")" );
            }
        }
        try
        {
            Neo4jMBean bean = new ConfigurationBean( kernelData, support );
            mbs.registerMBean( bean, bean.objectName );
            beans.add( bean );
        }
        catch ( Exception e )
        {
            logger.info( "Failed to register Configuration JMX Bean" );
        }
    }

Replace Generic With Diamond LinkedList<Neo4jMBean> with LinkedList<> in method public init() : void from class org.neo4j.jmx.impl.JmxKernelExtension


    @Override
    public Node findNode( final Label myLabel, final String key, final Object value )
    {
        try ( ResourceIterator<Node> iterator = findNodes( myLabel, key, value ) )
        {
            if ( !iterator.hasNext() )
            {
                return null;
            }
            Node node = iterator.next();
            if ( iterator.hasNext() )
            {
                throw new MultipleFoundException();
            }
            return node;
        }
    }

    @Override
    public Node findNode( final Label myLabel, final String key, final Object value )
    {
        ResourceIterator<Node> iterator = findNodes( myLabel, key, value );

        try
        {
            if ( !iterator.hasNext() )
            {
                return null;
            }
            Node node = iterator.next();
            if ( iterator.hasNext() )
            {
                throw new MultipleFoundException();
            }
            return node;
        }
        finally
        {
            iterator.close();
        }
    }

Try With Resources try(ResourceIterator<Node> iterator=findNodes(myLabel,key,value)) in method public findNode(myLabel Label, key String, value Object) : Node from class org.neo4j.kernel.InternalAbstractGraphDatabase


    private static Node createNodeOn( HighlyAvailableGraphDatabase db )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            node.setProperty( "key", String.valueOf( System.currentTimeMillis() ) );
            tx.success();
            return node;
        }
    }

    private static Node createNodeOn( HighlyAvailableGraphDatabase db )
    {
        Node node;
        Transaction tx = db.beginTx();
        try
        {
            node = db.createNode();
            node.setProperty( "key", String.valueOf( System.currentTimeMillis() ) );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
        return node;
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createNodeOn(db HighlyAvailableGraphDatabase) : Node from class org.neo4j.kernel.ha.ClusterTopologyChangesIT


    private static NodeRecord nodeRecord( StoreFactory factory, File storeDir, long id )
    {
        try ( NodeStore store = factory.newNodeStore( new File( storeDir, NODESTORE ) ) )
        {
            return store.forceGetRecord( id );
        }
    }

    private static NodeRecord nodeRecord( StoreFactory factory, File storeDir, long id )
    {
        NodeStore store = factory.newNodeStore( new File( storeDir, NODESTORE ) );
        try
        {
            return store.forceGetRecord( id );
        }
        finally
        {
            store.close();
        }
    }

Try With Resources try(NodeStore store=factory.newNodeStore(new File(storeDir,NODESTORE))) in method private nodeRecord(factory StoreFactory, storeDir File, id long) : NodeRecord from class org.neo4j.kernel.impl.store.DumpStoreChain


    public static void main( String[] args ) throws IOException
    {
        if ( args.length != 1 )
        {
            System.out.println( "one argument describing the path to the store" );
            System.exit( 1 );
        }

        final FileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        final File storeFile = new File( args[0] );

        try ( final StandalonePageCache pageCache = createPageCache( fs, "counts-store-dump" ) )
        {
            CountsStore counts = CountsStore.open( fs, pageCache, storeFile );
            System.out.println( "Counts Store: " + counts.file() );
            System.out.println( "\ttxId: " + counts.lastTxId() );
            System.out.println( "\tminor version: " + counts.minorVersion() );
            System.out.println( "\tentries: " + counts.totalRecordsStored() );
            System.out.println( "Entries:" );

            counts.accept( new KeyValueRecordVisitor<CountsKey,CopyableDoubleLongRegister>()
            {
                private final DoubleLongRegister tmp = newDoubleLongRegister();

                @Override
                public void visit( CountsKey key, CopyableDoubleLongRegister register )
                {
                    register.copyTo( tmp );
                    System.out.println( "\t" + key + ": (" + tmp.readFirst() + ", " + tmp.readSecond() + ")" );
                }
            }, newDoubleLongRegister() );
        }
    }

    public static void main( String[] args ) throws IOException
    {
        if ( args.length != 1 )
        {
            System.out.println( "one argument describing the path to the store" );
            System.exit( 1 );
        }

        final FileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        final File storeFile = new File( args[0] );

        final LifeSupport life = new LifeSupport();
        final PageCache pageCache = StandalonePageCacheFactory.createPageCache( fs, "counts-store-dump", life );

        try
        {
            CountsStore counts = CountsStore.open( fs, pageCache, storeFile );
            System.out.println( "Counts Store: " + counts.file() );
            System.out.println( "\ttxId: " + counts.lastTxId() );
            System.out.println( "\tminor version: " + counts.minorVersion() );
            System.out.println( "\tentries: " + counts.totalRecordsStored() );
            System.out.println( "Entries:" );

            counts.accept( new KeyValueRecordVisitor<CountsKey,CopyableDoubleLongRegister>()
            {
                private final DoubleLongRegister tmp = newDoubleLongRegister();

                @Override
                public void visit( CountsKey key, CopyableDoubleLongRegister register )
                {
                    register.copyTo( tmp );
                    System.out.println( "\t" + key + ": (" + tmp.readFirst() + ", " + tmp.readSecond() + ")" );
                }
            }, newDoubleLongRegister() );
        }
        finally
        {
            life.shutdown();
        }
    }

Try With Resources try(final StandalonePageCache pageCache=createPageCache(fs,"counts-store-dump")) in method public main(args String[]) : void from class org.neo4j.kernel.impl.store.counts.DumpCountsStore


    public void run( String legacyStoreDirectory, Config config, Logging logging, StoreUpgrader.Monitor monitor )
    {
        FileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        ConfigMapUpgradeConfiguration upgradeConfiguration = new ConfigMapUpgradeConfiguration( config );
        StoreUpgrader migrationProcess = new StoreUpgrader( upgradeConfiguration, fs, monitor, logging );

        LifeSupport life = new LifeSupport();

        // Add participants from kernel extensions...
        KernelExtensions kernelExtensions = life.add( new KernelExtensions(
                GraphDatabaseDependencies.newDependencies().kernelExtensions(), config,
                kernelExtensionDependencyResolver( fs, config ), ignore() ) );

        // Add the kernel store migrator
        config = StoreFactory.configForStoreDir( config, new File( legacyStoreDirectory ) );
        life.start();
        SchemaIndexProvider schemaIndexProvider = kernelExtensions.resolveDependency( SchemaIndexProvider.class,
                SchemaIndexProvider.HIGHEST_PRIORITIZED_OR_NONE );
        try
        {
            migrationProcess.addParticipant( new StoreMigrator(
                    new VisibleMigrationProgressMonitor( logging.getMessagesLog( StoreMigrationTool.class ), System.out ),
                    fs, new UpgradableDatabase( new StoreVersionCheck( fs ) ), config, logging ) );
            migrationProcess.addParticipant( schemaIndexProvider.storeMigrationParticipant() );
        }
        catch ( IllegalArgumentException e )
        {   // That's fine actually, no schema index provider on the classpath or something
        }

        // Perform the migration
        try ( StandalonePageCache pageCache = createPageCache( fs, config, "migration-tool" ) )
        {
            long startTime = System.currentTimeMillis();
            migrationProcess.migrateIfNeeded( new File( legacyStoreDirectory ), schemaIndexProvider, pageCache );
            long duration = System.currentTimeMillis() - startTime;
            logging.getMessagesLog( StoreMigrationTool.class )
                    .info( format( "Migration completed in %d s%n", duration / 1000 ) );
        }
        finally
        {
            life.shutdown();
        }
    }

    public void run( String legacyStoreDirectory, Config config, Logging logging, StoreUpgrader.Monitor monitor )
    {
        FileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        ConfigMapUpgradeConfiguration upgradeConfiguration = new ConfigMapUpgradeConfiguration( config );
        StoreUpgrader migrationProcess = new StoreUpgrader( upgradeConfiguration, fs, monitor, logging );

        LifeSupport life = new LifeSupport();
        Neo4jJobScheduler jobScheduler = life.add( new Neo4jJobScheduler() );
        SingleFilePageSwapperFactory swapperFactory = new SingleFilePageSwapperFactory( fs );
        LifecycledPageCache pageCache = life.add(
                new LifecycledPageCache( swapperFactory, jobScheduler, config, PageCacheMonitor.NULL ) );

        // Add participants from kernel extensions...
        KernelExtensions kernelExtensions = life.add( new KernelExtensions(
                GraphDatabaseDependencies.newDependencies().kernelExtensions(), config,
                kernelExtensionDependencyResolver( fs, config ), ignore() ) );

        // Add the kernel store migrator
        config = StoreFactory.configForStoreDir( config, new File( legacyStoreDirectory ) );
        life.start();
        SchemaIndexProvider schemaIndexProvider = kernelExtensions.resolveDependency( SchemaIndexProvider.class,
                SchemaIndexProvider.HIGHEST_PRIORITIZED_OR_NONE );
        try
        {
            migrationProcess.addParticipant( new StoreMigrator(
                    new VisibleMigrationProgressMonitor( logging.getMessagesLog( StoreMigrationTool.class ), System.out ),
                    fs, new UpgradableDatabase( new StoreVersionCheck( fs ) ), config, logging ) );
            migrationProcess.addParticipant( schemaIndexProvider.storeMigrationParticipant() );
        }
        catch ( IllegalArgumentException e )
        {   // That's fine actually, no schema index provider on the classpath or something
        }

        // Perform the migration
        try
        {
            long startTime = System.currentTimeMillis();
            migrationProcess.migrateIfNeeded( new File( legacyStoreDirectory ), schemaIndexProvider, pageCache );
            long duration = System.currentTimeMillis() - startTime;
            logging.getMessagesLog( StoreMigrationTool.class )
                    .info( format( "Migration completed in %d s%n", duration / 1000 ) );
        }
        finally
        {
            life.shutdown();
        }
    }

Try With Resources try(StandalonePageCache pageCache=createPageCache(fs,config,"migration-tool")) in method public run(legacyStoreDirectory String, config Config, logging Logging, monitor StoreUpgrader.Monitor) : void from class org.neo4j.kernel.impl.storemigration.StoreMigrationTool


    private static List<String> countRelationshipsOfAllNodes( GraphDatabaseService graphDb )
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            List<String> relationships = new ArrayList<>();
            for ( Node node : GlobalGraphOperations.at( graphDb ).getAllNodes() )
            {
                for ( Relationship relationship : node.getRelationships() )
                {
                    relationships.add( format( "(%d)%s[%d]%s(%d)",
                                               node.getId(),
                                               node.equals( relationship.getStartNode() ) ? "-" : "<-",
                                               relationship.getId(),
                                               node.equals( relationship.getEndNode() ) ? "-" : "->",
                                               relationship.getOtherNode( node ).getId() ) );
                }
            }
            tx.success();
            return relationships;
        }
    }

    private static List<String> countRelationshipsOfAllNodes( GraphDatabaseService graphDb )
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            List<String> relationships = new ArrayList<String>();
            for ( Node node : GlobalGraphOperations.at( graphDb ).getAllNodes() )
            {
                for ( Relationship relationship : node.getRelationships() )
                {
                    relationships.add( format( "(%d)%s[%d]%s(%d)",
                                               node.getId(),
                                               node.equals( relationship.getStartNode() ) ? "-" : "<-",
                                               relationship.getId(),
                                               node.equals( relationship.getEndNode() ) ? "-" : "->",
                                               relationship.getOtherNode( node ).getId() ) );
                }
            }
            tx.success();
            return relationships;
        }
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method private countRelationshipsOfAllNodes(graphDb GraphDatabaseService) : List<String> from class org.neo4j.kernel.impl.cache.CacheRaceTest


    private static void dumpRelationshipGroups( File file, StoreFactory storeFactory ) throws Exception
    {
        try ( RelationshipGroupStore store = storeFactory.newRelationshipGroupStore( file ) )
        {
            new DumpStore<RelationshipGroupRecord,RelationshipGroupStore>( System.out ).dump( store );
        }
    }

    private static void dumpRelationshipGroups( File file, StoreFactory storeFactory ) throws Exception
    {
        RelationshipGroupStore store = storeFactory.newRelationshipGroupStore( file );
        try
        {
            new DumpStore<RelationshipGroupRecord, RelationshipGroupStore>( System.out ).dump( store );
        }
        finally
        {
            store.close();
        }
    }

Try With Resources try(RelationshipGroupStore store=storeFactory.newRelationshipGroupStore(file)) in method private dumpRelationshipGroups(file File, storeFactory StoreFactory) : void from class org.neo4j.kernel.impl.store.DumpStore


    private static void dumpRelationshipStore( File file, StoreFactory storeFactory ) throws Exception
    {
        try ( RelationshipStore store = storeFactory.newRelationshipStore( file ) )
        {
            new DumpStore<RelationshipRecord,RelationshipStore>( System.out ).dump( store );
        }
    }

    private static void dumpRelationshipStore( File file, StoreFactory storeFactory ) throws Exception
    {
        RelationshipStore store = storeFactory.newRelationshipStore( file );
        try
        {
            new DumpStore<RelationshipRecord, RelationshipStore>( System.out ).dump( store );
        }
        finally
        {
            store.close();
        }
    }

Try With Resources try(RelationshipStore store=storeFactory.newRelationshipStore(file)) in method private dumpRelationshipStore(file File, storeFactory StoreFactory) : void from class org.neo4j.kernel.impl.store.DumpStore


    private static void dumpPropertyStore( File file, StoreFactory storeFactory ) throws Exception
    {
        try ( PropertyStore store = storeFactory.newPropertyStore( file ) )
        {
            new DumpStore<PropertyRecord,PropertyStore>( System.out ).dump( store );
        }
    }

    private static void dumpPropertyStore( File file, StoreFactory storeFactory ) throws Exception
    {
        PropertyStore store = storeFactory.newPropertyStore( file );
        try
        {
            new DumpStore<PropertyRecord, PropertyStore>( System.out ).dump( store );
        }
        finally
        {
            store.close();
        }
    }

Try With Resources try(PropertyStore store=storeFactory.newPropertyStore(file)) in method private dumpPropertyStore(file File, storeFactory StoreFactory) : void from class org.neo4j.kernel.impl.store.DumpStore


    private static void dumpSchemaStore( File file, StoreFactory storeFactory ) throws Exception
    {
        try ( SchemaStore store = storeFactory.newSchemaStore( file ) )
        {
            final SchemaStorage storage = new SchemaStorage( store );
            new DumpStore<DynamicRecord,SchemaStore>( System.out )
            {
                @Override
                protected Object transform( DynamicRecord record ) throws Exception
                {
                    return record.inUse() && record.isStartRecord()
                           ? storage.loadSingleSchemaRule( record.getId() )
                           : null;
                }
            }.dump( store );
        }
    }

    private static void dumpSchemaStore( File file, StoreFactory storeFactory ) throws Exception
    {
        SchemaStore store = storeFactory.newSchemaStore( file );
        try
        {
            final SchemaStorage storage = new SchemaStorage( store );
            new DumpStore<DynamicRecord, SchemaStore>( System.out )
            {
                @Override
                protected Object transform( DynamicRecord record ) throws Exception
                {
                    return record.inUse() && record.isStartRecord()
                           ? storage.loadSingleSchemaRule( record.getId() )
                           : null;
                }
            }.dump( store );
        }
        finally
        {
            store.close();
        }
    }

Try With Resources try(SchemaStore store=storeFactory.newSchemaStore(file)) in method private dumpSchemaStore(file File, storeFactory StoreFactory) : void from class org.neo4j.kernel.impl.store.DumpStore


    private static void dumpNodeStore( File file, StoreFactory storeFactory ) throws Exception
    {
        try ( NodeStore store = storeFactory.newNodeStore( file ) )
        {
            new DumpStore<NodeRecord,NodeStore>( System.out )
            {
                @Override
                protected Object transform( NodeRecord record ) throws Exception
                {
                    return record.inUse() ? record : "";
                }
            }.dump( store );
        }
    }

    private static void dumpNodeStore( File file, StoreFactory storeFactory ) throws Exception
    {
        NodeStore store = storeFactory.newNodeStore( file );
        try
        {
            new DumpStore<NodeRecord, NodeStore>( System.out )
            {
                @Override
                protected Object transform( NodeRecord record ) throws Exception
                {
                    return record.inUse() ? record : "";
                }
            }.dump( store );
        }
        finally
        {
            store.close();
        }
    }

Try With Resources try(NodeStore store=storeFactory.newNodeStore(file)) in method private dumpNodeStore(file File, storeFactory StoreFactory) : void from class org.neo4j.kernel.impl.store.DumpStore


            @Override
            public void evaluate() throws Throwable
            {
                try ( ServerControls _ = controls = builder.newServer() )
                {
                    base.evaluate();
                }
            }

            @Override
            public void evaluate() throws Throwable
            {
                controls = builder.newServer();
                try
                {
                    base.evaluate();
                }
                finally
                {
                    controls.close();
                }
            }

Try With Resources try(ServerControls _=controls=builder.newServer()) in method public evaluate() : void from class org.neo4j.harness.junit.Neo4jRule.apply.new Statement


    /**
     * Create a new instance of a service implementation identified with the
     * specified key(s).
     *
     * @param key     the main key for identifying this service implementation
     * @param altKeys alternative spellings of the identifier of this service
     *                implementation
     */
    protected Service( String key, String... altKeys )
    {
        if ( altKeys == null || altKeys.length == 0 )
        {
            this.keys = Collections.singleton( key );
        }
        else
        {
            this.keys = new HashSet<>( Arrays.asList( altKeys ) );
            this.keys.add( key );
        }
    }

    /**
     * Create a new instance of a service implementation identified with the
     * specified key(s).
     *
     * @param key     the main key for identifying this service implementation
     * @param altKeys alternative spellings of the identifier of this service
     *                implementation
     */
    protected Service( String key, String... altKeys )
    {
        if ( altKeys == null || altKeys.length == 0 )
        {
            this.keys = Collections.singleton( key );
        }
        else
        {
            this.keys = new HashSet<String>( Arrays.asList( altKeys ) );
            this.keys.add( key );
        }
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method protected Service(key String, altKeys String...) from class org.neo4j.helpers.Service


    public static void readTextFile( File file, LineListener listener ) throws IOException
    {
        try(BufferedReader reader = new BufferedReader( new FileReader( file ) );)
        {
            String line;
            while ( (line = reader.readLine()) != null )
            {
                listener.line( line );
            }
        }
    }

    public static void readTextFile( File file, LineListener listener ) throws IOException
    {
        BufferedReader reader = new BufferedReader( new FileReader( file ) );
        try
        {
            String line = null;
            while ( (line = reader.readLine()) != null )
            {
                listener.line( line );
            }
        }
        finally
        {
            reader.close();
        }
    }

Try With Resources try(BufferedReader reader=new BufferedReader(new FileReader(file))) in method public readTextFile(file File, listener LineListener) : void from class org.neo4j.kernel.impl.util.FileUtils


    static List<Long> getAllNodes( DirectoryFactory dirFactory, File indexDir, Object propertyValue ) throws IOException
    {
        try ( Directory directory = dirFactory.open( indexDir );
              SearcherManager manager = new SearcherManager( directory, new SearcherFactory() );
              IndexSearcher searcher = manager.acquire() )
        {
            List<Long> nodes = new ArrayList<>();
            LuceneDocumentStructure documentStructure = new LuceneDocumentStructure();
            Query query = documentStructure.newQuery( propertyValue );
            searcher.search( query, new AllNodesCollector( documentStructure, nodes ) );
            return nodes;
        }
    }

    static List<Long> getAllNodes( DirectoryFactory directoryFactory, File indexDir, Object propertyValue ) throws IOException
    {
        Directory directory = directoryFactory.open( indexDir );
        SearcherManager manager = new SearcherManager( directory, new SearcherFactory() );
        IndexSearcher searcher = manager.acquire();
        try
        {
            List<Long> nodes = new ArrayList<Long>();
            LuceneDocumentStructure documentStructure = new LuceneDocumentStructure();
            searcher.search( documentStructure.newQuery( propertyValue ), new AllNodesCollector( documentStructure, nodes ) );
            return nodes;
        }
        finally
        {
            manager.release( searcher );
            manager.close();
            directory.close();
        }
    }

Try With Resources try(Directory directory=dirFactory.open(indexDir); SearcherManager manager=new SearcherManager(directory,new SearcherFactory()); IndexSearcher searcher=manager.acquire()) in method package getAllNodes(dirFactory DirectoryFactory, indexDir File, propertyValue Object) : List<Long> from class org.neo4j.kernel.api.impl.index.AllNodesCollector


    @Override
    public Response<Integer> multiply( int value1, int value2 )
    {
        gotCalled = true;
        return new TransactionStreamResponse<>( value1 * value2, storeIdToRespondWith,
                TransactionStream.EMPTY, ResourceReleaser.NO_OP );
    }

    @Override
    public Response<Integer> multiply( int value1, int value2 )
    {
        gotCalled = true;
        return new Response<Integer>( value1 * value2, storeIdToRespondWith,
                TransactionStream.EMPTY, ResourceReleaser.NO_OP );
    }

Replace Generic With Diamond Response<Integer> with TransactionStreamResponse<> in method public multiply(value1 int, value2 int) : Response<Integer> from class org.neo4j.com.MadeUpServerImplementation


    private Response<Void> emptyResponse()
    {
        return new TransactionStreamResponse<>( null, storeIdToRespondWith,
                TransactionStream.EMPTY, ResourceReleaser.NO_OP );
    }

    private Response<Void> emptyResponse()
    {
        return new Response<Void>( null, storeIdToRespondWith,
                TransactionStream.EMPTY, ResourceReleaser.NO_OP );
    }

Replace Generic With Diamond Response<Void> with TransactionStreamResponse<> in method private emptyResponse() : Response<Void> from class org.neo4j.com.MadeUpServerImplementation


    private void migrateWithBatchImporter( File storeDir, File migrationDir )
            throws IOException
    {
        LegacyStore legacyStore;
        switch ( versionToUpgradeFrom )
        {
            case Legacy19Store.LEGACY_VERSION:
                legacyStore = new Legacy19Store( fileSystem, new File( storeDir, NeoStore.DEFAULT_NAME ) );
                break;
            case Legacy20Store.LEGACY_VERSION:
                legacyStore = new Legacy20Store( fileSystem, new File( storeDir, NeoStore.DEFAULT_NAME ) );
                break;
            default:
                throw new IllegalStateException( "Unknown version to upgrade from: " + versionToUpgradeFrom );
        }

        ExecutionMonitor executionMonitor = new CoarseBoundedProgressExecutionMonitor(
                legacyStore.getNodeStoreReader().getMaxId(), legacyStore.getRelStoreReader().getMaxId() )
        {
            @Override
            protected void percent( int percent )
            {
                progressMonitor.percentComplete( percent );
            }
        };
        BatchImporter importer = new ParallelBatchImporter( migrationDir.getAbsolutePath(), fileSystem,
                new Configuration.OverrideFromConfig( config ), logging,
                executionMonitor );
        Iterable<InputNode> nodes = legacyNodesAsInput( legacyStore );
        Iterable<InputRelationship> relationships = legacyRelationshipsAsInput( legacyStore );
        importer.doImport( nodes, relationships, IdMappings.actual() );
        progressMonitor.finished();

        // Finish the import of nodes and relationships
        if ( legacyStore instanceof Legacy19Store )
        {
            // we may need to upgrade the property keys
            Legacy19Store legacy19Store = (Legacy19Store) legacyStore;
            LifeSupport life = new LifeSupport();
            life.start();
            PageCache pageCache = createPageCache( fileSystem, "migrator-dedup-properties", life );
            try ( PropertyStore propertyStore = storeFactory( pageCache, migrationDir ).newPropertyStore() )
            {
                migratePropertyKeys( legacy19Store, propertyStore );
            }
            finally
            {
                life.shutdown();
            }
        }
        // Close
        legacyStore.close();
    }

    private void migrateWithBatchImporter( File storeDir, File migrationDir )
            throws IOException
    {
        LegacyStore legacyStore;
        switch ( versionToUpgradeFrom )
        {
            case Legacy19Store.LEGACY_VERSION:
                legacyStore = new Legacy19Store( fileSystem, new File( storeDir, NeoStore.DEFAULT_NAME ) );
                break;
            case Legacy20Store.LEGACY_VERSION:
                legacyStore = new Legacy20Store( fileSystem, new File( storeDir, NeoStore.DEFAULT_NAME ) );
                break;
            default:
                throw new IllegalStateException( "Unknown version to upgrade from: " + versionToUpgradeFrom );
        }

        ExecutionMonitor executionMonitor = new CoarseBoundedProgressExecutionMonitor(
                legacyStore.getNodeStoreReader().getMaxId(), legacyStore.getRelStoreReader().getMaxId() )
        {
            @Override
            protected void percent( int percent )
            {
                progressMonitor.percentComplete( percent );
            }
        };
        BatchImporter importer = new ParallelBatchImporter( migrationDir.getAbsolutePath(), fileSystem,
                new Configuration.OverrideFromConfig( config ), logging,
                executionMonitor );
        Iterable<InputNode> nodes = legacyNodesAsInput( legacyStore );
        Iterable<InputRelationship> relationships = legacyRelationshipsAsInput( legacyStore );
        importer.doImport( nodes, relationships, IdMappings.actual() );
        progressMonitor.finished();

        // Finish the import of nodes and relationships
        if ( legacyStore instanceof Legacy19Store )
        {
            // we may need to upgrade the property keys
            Legacy19Store legacy19Store = (Legacy19Store) legacyStore;
            LifeSupport life = new LifeSupport();
            life.start();
            PageCache pageCache = createPageCache( fileSystem, "migrator-dedup-properties", life );
            PropertyStore propertyStore = storeFactory( pageCache, migrationDir ).newPropertyStore();
            try
            {
                migratePropertyKeys( legacy19Store, propertyStore );
            }
            finally
            {
                propertyStore.close();
                life.shutdown();
            }
        }
        // Close
        legacyStore.close();
    }

Try With Resources try(PropertyStore propertyStore=storeFactory(pageCache,migrationDir).newPropertyStore()) in method private migrateWithBatchImporter(storeDir File, migrationDir File) : void from class org.neo4j.kernel.impl.storemigration.StoreMigrator


    private Pair<Map<String, String>, /*was it created now?*/Boolean> getOrCreateIndexConfig(
            IndexEntityType entityType, String indexName, Map<String, String> suppliedConfig )
    {
        Pair<Map<String, String>, Boolean> result = findIndexConfig( entityType.entityClass(),
                indexName, suppliedConfig, config.getParams() );
        boolean createdNow = false;
        if ( result.other() )
        {   // Ok, we need to create this config
            synchronized ( this )
            {   // Were we the first ones to get here?
                Map<String, String> existing = indexStore.get( entityType.entityClass(), indexName );
                if ( existing != null )
                {
                    // No, someone else made it before us, cool
                    assertConfigMatches( indexProviders.lookup( existing.get( PROVIDER ) ), indexName,
                            existing, result.first() );
                    return Pair.of( result.first(), false );
                }

                // We were the first one here, let's create this config
                try ( KernelTransaction transaction = kernel.instance().newTransaction();
                      Statement statement = transaction.acquireStatement() )
                {
                    switch (entityType)
                    {
                        case Node:
                            statement.dataWriteOperations().nodeLegacyIndexCreate( indexName, result.first() );
                            break;

                        case Relationship:
                            statement.dataWriteOperations().relationshipLegacyIndexCreate( indexName, result.first() );
                            break;
                    }

                    transaction.success();
                    createdNow = true;
                } catch (Exception ex)
                {
                    throw new TransactionFailureException( "Index creation failed for " + indexName +
                            ", " + result.first(), ex );
                }
            }
        }
        return Pair.of( result.first(), createdNow );
    }

    private Pair<Map<String, String>, /*was it created now?*/Boolean> getOrCreateIndexConfig(
            IndexEntityType entityType, String indexName, Map<String, String> suppliedConfig )
    {
        Pair<Map<String, String>, Boolean> result = findIndexConfig( entityType.entityClass(),
                indexName, suppliedConfig, config.getParams() );
        boolean createdNow = false;
        if ( result.other() )
        {   // Ok, we need to create this config
            synchronized ( this )
            {   // Were we the first ones to get here?
                Map<String, String> existing = indexStore.get( entityType.entityClass(), indexName );
                if ( existing != null )
                {
                    // No, someone else made it before us, cool
                    assertConfigMatches( indexProviders.lookup( existing.get( PROVIDER ) ), indexName,
                            existing, result.first() );
                    return Pair.of( result.first(), false );
                }

                // We were the first one here, let's create this config
                ExecutorService executorService = Executors.newSingleThreadExecutor();
                try
                {
                    executorService.submit( new IndexCreatorJob( entityType, indexName, result.first() ) ).get();
                    createdNow = true;
                }
                catch ( ExecutionException ex )
                {
                    throw new TransactionFailureException( "Index creation failed for " + indexName +
                            ", " + result.first(), ex.getCause() );
                }
                catch ( InterruptedException ex )
                {
                    Thread.interrupted();
                }
                finally
                {
                    executorService.shutdownNow();
                }
            }
        }
        return Pair.of( result.first(), createdNow );
    }

Try With Resources try(KernelTransaction transaction=kernel.instance().newTransaction(); Statement statement=transaction.acquireStatement()) in method private getOrCreateIndexConfig(entityType IndexEntityType, indexName String, suppliedConfig Map<String,String>) : Pair<Map<String,String>,Boolean> from class org.neo4j.kernel.impl.index.LegacyIndexStore


    protected long findHighIdBackwards() throws IOException
    {
        try ( PageCursor cursor = storeFile.io( 0, PF_SHARED_LOCK ) )
        {
            long lastPageId = storeFile.getLastPageId();
            long nextPageId = lastPageId;
            int recordsPerPage = recordsPerPage();
            int recordSize = getRecordSize();
            while ( nextPageId >= 0 && cursor.next( nextPageId ) )
            {
                nextPageId--;
                do
                {
                    int currentRecord = recordsPerPage;
                    while ( currentRecord --> 0 )
                    {
                        cursor.setOffset( currentRecord * recordSize );
                        long recordId = (cursor.getCurrentPageId() * recordsPerPage) + currentRecord;
                        if ( isRecordInUse( cursor ) )
                        {
                            // We've found the highest id in use
                            return recordId + 1 /*+1 since we return the high id*/;
                        }
                    }
                }
                while ( cursor.shouldRetry() );
            }

            return getNumberOfReservedLowIds();
        }
    }

    protected long findHighIdBackwards()
    {
        try
        {
            return findHighIdBackwards( storeFile );
        }
        catch ( IOException e )
        {
            throw new UnderlyingStorageException(
                    "Unable to find high id by scanning backwards " + getStorageFileName(), e );
        }
    }

Try With Resources try(PageCursor cursor=storeFile.io(0,PF_SHARED_LOCK)) in method protected findHighIdBackwards() : long from class org.neo4j.kernel.impl.store.CommonAbstractStore


            @Override
            public Response<Void> fetchDataStream( MadeUpWriter writer, int dataSize )
            {
                writer.write( new FailingByteChannel( dataSize, failureMessage ) );
                return new Response<>( null, storeIdToUse, TransactionStream.EMPTY, ResourceReleaser.NO_OP );
            }

            @Override
            public Response<Void> fetchDataStream( MadeUpWriter writer, int dataSize )
            {
                writer.write( new FailingByteChannel( dataSize, failureMessage ) );
                return new Response<Void>( null, storeIdToUse,
                        TransactionStream.EMPTY, ResourceReleaser.NO_OP );
            }

Replace Generic With Diamond Response<Void> with Response<> in method public fetchDataStream(writer MadeUpWriter, dataSize int) : Response<Void> from class org.neo4j.com.TestCommunication.clientThrowsServerSideErrorMidwayThroughStreaming.serverImplementation.new MadeUpServerImplementation


                @Override
                public Cache<RelationshipImpl> call() throws Exception
                {
                    return new StrongReferenceCache<>( CacheProvider.RELATIONSHIP_CACHE_NAME );
                }

                @Override
                public Cache<RelationshipImpl> call() throws Exception
                {
                    return new StrongReferenceCache<RelationshipImpl>( CacheProvider.RELATIONSHIP_CACHE_NAME );
                }

Replace Generic With Diamond StrongReferenceCache<RelationshipImpl> with StrongReferenceCache<> in method public call() : Cache<RelationshipImpl> from class org.neo4j.kernel.impl.cache.CacheRaceTest.db.new ImpermanentDatabaseRule.cacheProvider.new CustomCacheProvider.new Callable<Cache<RelationshipImpl>>


        private CacheProvider cacheProvider()
        {
            return new CustomCacheProvider( StrongCacheProvider.NAME, new Callable<Cache<NodeImpl>>()
            {
                @Override
                public Cache<NodeImpl> call() throws Exception
                {
                    return nodeCache;
                }
            }, new Callable<Cache<RelationshipImpl>>()
            {
                @Override
                public Cache<RelationshipImpl> call() throws Exception
                {
                    return new StrongReferenceCache<>( CacheProvider.RELATIONSHIP_CACHE_NAME );
                }
            } );
        }

        private CacheProvider cacheProvider()
        {
            return new CustomCacheProvider( StrongCacheProvider.NAME, new Callable<Cache<NodeImpl>>()
            {
                @Override
                public Cache<NodeImpl> call() throws Exception
                {
                    return nodeCache;
                }
            }, new Callable<Cache<RelationshipImpl>>()
            {
                @Override
                public Cache<RelationshipImpl> call() throws Exception
                {
                    return new StrongReferenceCache<RelationshipImpl>( CacheProvider.RELATIONSHIP_CACHE_NAME );
                }
            } );
        }

Replace Generic With Diamond StrongReferenceCache<RelationshipImpl> with StrongReferenceCache<> in method private cacheProvider() : CacheProvider from class org.neo4j.kernel.impl.cache.CacheRaceTest.db.new ImpermanentDatabaseRule


    public Result runFullConsistencyCheck( String storeDir,
                                                  Config tuningConfiguration,
                                                  ProgressMonitorFactory progressFactory,
                                           StringLogger logger ) throws ConsistencyCheckIncompleteException
    {
        Map<String, String> params = tuningConfiguration.getParams();
        params.put( GraphDatabaseSettings.store_dir.name(), storeDir );
        tuningConfiguration.applyChanges( params );

        DefaultFileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction();
        StoreFactory factory = new StoreFactory(
                tuningConfiguration,
                new DefaultIdGeneratorFactory(),
                tuningConfiguration.get( ConsistencyCheckSettings.consistency_check_window_pool_implementation )
                        .windowPoolFactory( tuningConfiguration, logger ), fileSystem, logger,
                new DefaultTxHook() );

        ConsistencySummaryStatistics summary;
        File reportFile = chooseReportPath( tuningConfiguration );
        StringLogger report = StringLogger.lazyLogger( reportFile );

        try ( NeoStore neoStore = factory.newNeoStore( new File( storeDir, NeoStore.DEFAULT_NAME ) ) )
        {
            neoStore.makeStoreOk();
            StoreAccess store = new StoreAccess( neoStore );
            LabelScanStore labelScanStore = null;
            try
            {

                labelScanStore = new LuceneLabelScanStoreBuilder(
                        storeDir, store.getRawNeoStore(), fileSystem, logger ).build();
                SchemaIndexProvider indexes = new LuceneSchemaIndexProvider(
                        DirectoryFactory.PERSISTENT,
                        tuningConfiguration );
                DirectStoreAccess stores = new DirectStoreAccess( store, labelScanStore, indexes );
                FullCheck check = new FullCheck( tuningConfiguration, progressFactory );
                summary = check.execute( stores, StringLogger.tee( logger, report ) );
            }
            finally
            {
                try
                {
                    if ( null != labelScanStore )
                    {
                        labelScanStore.shutdown();
                    }
                }
                catch ( IOException e )
                {
                    logger.error( "Failure during shutdown of label scan store", e );
                }
            }
        }
        finally
        {
            report.close();

        }

        if ( !summary.isConsistent() )
        {
            logger.logMessage( String.format( "See '%s' for a detailed consistency report.", reportFile.getPath() ) );
            return Result.FAILURE;
        }

        return Result.SUCCESS;
    }

    public Result runFullConsistencyCheck( String storeDir,
                                                  Config tuningConfiguration,
                                                  ProgressMonitorFactory progressFactory,
                                           StringLogger logger ) throws ConsistencyCheckIncompleteException
    {
        Map<String, String> params = tuningConfiguration.getParams();
        params.put( GraphDatabaseSettings.store_dir.name(), storeDir );
        tuningConfiguration.applyChanges( params );

        DefaultFileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction();
        StoreFactory factory = new StoreFactory(
                tuningConfiguration,
                new DefaultIdGeneratorFactory(),
                tuningConfiguration.get( ConsistencyCheckSettings.consistency_check_window_pool_implementation )
                        .windowPoolFactory( tuningConfiguration, logger ), fileSystem, logger,
                new DefaultTxHook() );

        ConsistencySummaryStatistics summary;
        File reportFile = chooseReportPath( tuningConfiguration );
        StringLogger report = StringLogger.lazyLogger( reportFile );

        NeoStore neoStore = factory.newNeoStore( new File( storeDir, NeoStore.DEFAULT_NAME ) );
        try
        {
            neoStore.makeStoreOk();
            StoreAccess store = new StoreAccess( neoStore );
            LabelScanStore labelScanStore = null;
            try {

                labelScanStore =
                    new LuceneLabelScanStoreBuilder( storeDir, store.getRawNeoStore(), fileSystem, logger ).build();
                SchemaIndexProvider indexes = new LuceneSchemaIndexProvider( DirectoryFactory.PERSISTENT, tuningConfiguration );
                DirectStoreAccess stores = new DirectStoreAccess( store, labelScanStore, indexes );
                summary = new FullCheck( tuningConfiguration, progressFactory )
                        .execute( stores, StringLogger.tee( logger, report ) );
            }
            finally
            {
                try
                {
                    if ( null != labelScanStore )
                    {
                        labelScanStore.shutdown();
                    }
                }
                catch ( IOException e )
                {
                    logger.error( "Faiure during shutdown of label scan store", e );
                }
            }
        }
        finally
        {

            report.close();
            neoStore.close();
        }

        if ( !summary.isConsistent() )
        {
            logger.logMessage( String.format( "See '%s' for a detailed consistency report.", reportFile.getPath() ) );
            return Result.FAILURE;
        }

        return Result.SUCCESS;
    }

Try With Resources try(NeoStore neoStore=factory.newNeoStore(new File(storeDir,NeoStore.DEFAULT_NAME))) in method public runFullConsistencyCheck(storeDir String, tuningConfiguration Config, progressFactory ProgressMonitorFactory, logger StringLogger) : Result from class org.neo4j.consistency.ConsistencyCheckService


    private RequestContext slaveContextOf( GraphDatabaseAPI graphDb )
    {
        XaDataSourceManager dsManager = dsManager( graphDb );
        List<Tx> txs = new ArrayList<>();
        for ( XaDataSource ds : dsManager.getAllRegisteredDataSources() )
        {
            txs.add( RequestContext.lastAppliedTx( ds.getName(), ds.getLastCommittedTxId() ) );
        }
        return RequestContext.anonymous( txs.toArray( new Tx[txs.size()] ) );
    }

    private RequestContext slaveContextOf( GraphDatabaseAPI graphDb )
    {
        XaDataSourceManager dsManager = dsManager( graphDb );
        List<Tx> txs = new ArrayList<Tx>();
        for ( XaDataSource ds : dsManager.getAllRegisteredDataSources() )
        {
            txs.add( RequestContext.lastAppliedTx( ds.getName(), ds.getLastCommittedTxId() ) );
        }
        return RequestContext.anonymous( txs.toArray( new Tx[txs.size()] ) );
    }

Replace Generic With Diamond ArrayList<Tx> with ArrayList<> in method private slaveContextOf(graphDb GraphDatabaseAPI) : RequestContext from class org.neo4j.backup.BackupService


    static GraphDatabaseAPI startTemporaryDb( String targetDirectory, ConfigParam... params )
    {
        Map<String, String> config = new HashMap<>();
        config.put( OnlineBackupSettings.online_backup_enabled.name(), Settings.FALSE );
        config.put( InternalAbstractGraphDatabase.Configuration.log_configuration_file.name(),
                "neo4j-backup-logback.xml" );
        for ( ConfigParam param : params )
        {
            if ( param != null )
            {
                param.configure( config );
            }
        }
        return (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( targetDirectory )
                .setConfig( config ).newGraphDatabase();
    }

    static GraphDatabaseAPI startTemporaryDb( String targetDirectory, ConfigParam... params )
    {
        Map<String, String> config = new HashMap<String, String>();
        config.put( OnlineBackupSettings.online_backup_enabled.name(), Settings.FALSE );
        config.put( InternalAbstractGraphDatabase.Configuration.log_configuration_file.name(),
                "neo4j-backup-logback.xml" );
        for ( ConfigParam param : params )
        {
            if ( param != null )
            {
                param.configure( config );
            }
        }
        return (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( targetDirectory )
                .setConfig( config ).newGraphDatabase();
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method package startTemporaryDb(targetDirectory String, params ConfigParam...) : GraphDatabaseAPI from class org.neo4j.backup.BackupService


            @Override
            public void run()
            {
                try
                {
                    firstStoreFinishedStreaming.await();

                    try ( Transaction tx = db.beginTx() )
                    {
                        Node node1 = db.createNode();
                        Node node2 = db.createNode();
                        node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "foobydoo" ) );
                        tx.success();
                    }
                    finally
                    {
                        DependencyResolver resolver = db.getDependencyResolver();
                        XaDataSourceManager xaDsManager = resolver.resolveDependency( XaDataSourceManager.class );
                        xaDsManager.getNeoStoreDataSource().getNeoStore().flushAll();
                        transactionCommitted.countDown();
                    }
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void run()
            {
                try
                {
                    firstStoreFinishedStreaming.await();

                    Transaction tx = db.beginTx();
                    try
                    {
                        Node node1 = db.createNode();
                        Node node2 = db.createNode();
                        node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "foobydoo" ) );
                        tx.success();
                    }
                    finally
                    {
                        tx.finish();
                        db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getNeoStoreDataSource().getNeoStore().flushAll();
                        transactionCommitted.countDown();
                    }
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                }
            }

Try With Resources try(Transaction tx=db.beginTx()) in method public run() : void from class org.neo4j.backup.BackupServiceIT.shouldContainTransactionsThatHappenDuringBackupProcess.execute.new Runnable


    private Map<String, String> defaultBackupPortHostParams()
    {
        Map<String, String> params = new HashMap<>();
        params.put( OnlineBackupSettings.online_backup_server.name(), BACKUP_HOST + ":" + backupPort );
        return params;
    }

    private Map<String, String> defaultBackupPortHostParams()
    {
        Map<String, String> params = new HashMap<String, String>();
        params.put( OnlineBackupSettings.online_backup_server.name(), BACKUP_HOST + ":" + backupPort );
        return params;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method private defaultBackupPortHostParams() : Map<String,String> from class org.neo4j.backup.BackupServiceIT


    private void createAndIndexNode( GraphDatabaseService db, int i )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Index<Node> index = db.index().forNodes( "delete_me" );
            Node node = db.createNode();
            node.setProperty( "id", System.currentTimeMillis() + i );
            index.add( node, "delete", "me" );
            tx.success();
        }
    }

    private void createAndIndexNode( GraphDatabaseService db, int i )
    {
        Transaction tx = db.beginTx();
        try
        {
            Index<Node> index = db.index().forNodes( "delete_me" );
            Node node = db.createNode();
            node.setProperty( "id", System.currentTimeMillis() + i );
            index.add( node, "delete", "me" );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createAndIndexNode(db GraphDatabaseService, i int) : void from class org.neo4j.backup.BackupServiceIT


    private void applyOnePhaseCommitEntry( LogEntry.OnePhaseCommit commit )
            throws IOException
    {
        int identifier = commit.getIdentifier();
        long txId = commit.getTxId();
        LogEntry.Start startEntry = xidIdentMap.get( identifier );
        if ( startEntry == null )
        {
            throw new IOException( "Unknown xid for identifier " + identifier );
        }
        Xid xid = startEntry.getXid();
        try ( LockGroup lockGroup = new LockGroup() )
        {
            XaTransaction xaTx = xaRm.getXaTransaction( xid );
            xaTx.setCommitTxId( txId );
            positionCache.cacheStartPosition( txId, startEntry, logVersion );
            xaRm.injectOnePhaseCommit( xid, lockGroup );
            registerRecoveredTransaction( txId );
        }
        catch ( XAException e )
        {
            throw new IOException( e );
        }
    }

    private void applyOnePhaseCommitEntry( LogEntry.OnePhaseCommit commit )
            throws IOException
    {
        int identifier = commit.getIdentifier();
        long txId = commit.getTxId();
        LogEntry.Start startEntry = xidIdentMap.get( identifier );
        if ( startEntry == null )
        {
            throw new IOException( "Unknown xid for identifier " + identifier );
        }
        Xid xid = startEntry.getXid();
        try
        {
            XaTransaction xaTx = xaRm.getXaTransaction( xid );
            xaTx.setCommitTxId( txId );
            positionCache.cacheStartPosition( txId, startEntry, logVersion );
            xaRm.injectOnePhaseCommit( xid );
            registerRecoveredTransaction( txId );
        }
        catch ( XAException e )
        {
            throw new IOException( e );
        }
    }

Try With Resources try(LockGroup lockGroup=new LockGroup()) in method private applyOnePhaseCommitEntry(commit LogEntry.OnePhaseCommit) : void from class org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog


    private void applyTwoPhaseCommitEntry( LogEntry.TwoPhaseCommit commit ) throws IOException
    {
        int identifier = commit.getIdentifier();
        long txId = commit.getTxId();
        LogEntry.Start startEntry = xidIdentMap.get( identifier );
        if ( startEntry == null )
        {
            throw new IOException( "Unknown xid for identifier " + identifier );
        }
        Xid xid = startEntry.getXid();
        if ( xid == null )
        {
            throw new IOException( "Xid null for identifier " + identifier );
        }
        try ( LockGroup lockGroup = new LockGroup() )
        {
            XaTransaction xaTx = xaRm.getXaTransaction( xid );
            xaTx.setCommitTxId( txId );
            positionCache.cacheStartPosition( txId, startEntry, logVersion );
            xaRm.injectTwoPhaseCommit( xid, lockGroup );
            registerRecoveredTransaction( txId );
        }
        catch ( XAException e )
        {
            throw new IOException( e );
        }
    }

    private void applyTwoPhaseCommitEntry( LogEntry.TwoPhaseCommit commit ) throws IOException
    {
        int identifier = commit.getIdentifier();
        long txId = commit.getTxId();
        LogEntry.Start startEntry = xidIdentMap.get( identifier );
        if ( startEntry == null )
        {
            throw new IOException( "Unknown xid for identifier " + identifier );
        }
        Xid xid = startEntry.getXid();
        if ( xid == null )
        {
            throw new IOException( "Xid null for identifier " + identifier );
        }
        try
        {
            XaTransaction xaTx = xaRm.getXaTransaction( xid );
            xaTx.setCommitTxId( txId );
            positionCache.cacheStartPosition( txId, startEntry, logVersion );
            xaRm.injectTwoPhaseCommit( xid );
            registerRecoveredTransaction( txId );
        }
        catch ( XAException e )
        {
            throw new IOException( e );
        }
    }

Try With Resources try(LockGroup lockGroup=new LockGroup()) in method private applyTwoPhaseCommitEntry(commit LogEntry.TwoPhaseCommit) : void from class org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog


    protected <R> Response<R> sendRequest( RequestType<T> type, RequestContext context,
                                           Serializer serializer, Deserializer<R> deserializer,
                                           StoreId specificStoreId )
    {
        boolean success = true;
        Triplet<Channel, ChannelBuffer, ByteBuffer> channelContext = null;
        Throwable failure = null;
        try
        {
            // Send 'em over the wire
            channelContext = getChannel( type );
            Channel channel = channelContext.first();
            ChannelBuffer output = channelContext.second();
            ByteBuffer input = channelContext.third();

            Map<String, String> requestContext = new HashMap<>();
            requestContext.put( "type", type.toString() );
            requestContext.put( "slaveContext", context.toString() );
            requestContext.put( "serverAddress", channel.getRemoteAddress().toString() );
            requestMonitor.beginRequest( requestContext );

            // Request
            protocol.serializeRequest( channel, output, type, context, serializer );

            // Response
            @SuppressWarnings("unchecked")
            Response<R> response = protocol.deserializeResponse(
                    (BlockingReadHandler<ChannelBuffer>) channel.getPipeline().get( "blockingHandler" ), input,
                    getReadTimeout( type, readTimeout ), deserializer, resourcePoolReleaser );

            if ( shouldCheckStoreId( type ) )
            {
                // specificStoreId is there as a workaround for then the graphDb isn't initialized yet
                if ( specificStoreId != null )
                {
                    assertCorrectStoreId( response.getStoreId(), specificStoreId );
                }
                else
                {
                    assertCorrectStoreId( response.getStoreId(), storeId );
                }
            }

            return response;
        }
        catch ( IllegalProtocolVersionException e )
        {
            failure = e;
            success = false;
            for ( MismatchingVersionHandler handler : mismatchingVersionHandlers )
            {
                handler.versionMismatched( e.getExpected(), e.getReceived() );
            }
            throw e;
        }
        catch ( Throwable e )
        {
            failure = e;
            success = false;
            if ( channelContext != null )
            {
                closeChannel( channelContext );
            }
            throw Exceptions.launderedException( ComException.class, e );
        }
        finally
        {
            /*
             * Otherwise the user must call response.close() to prevent resource leaks.
             */
            if ( !success )
            {
                releaseChannel();
            }
            requestMonitor.endRequest( failure );
        }
    }

    protected <R> Response<R> sendRequest( RequestType<T> type, RequestContext context,
                                           Serializer serializer, Deserializer<R> deserializer,
                                           StoreId specificStoreId )
    {
        boolean success = true;
        Triplet<Channel, ChannelBuffer, ByteBuffer> channelContext = null;
        Throwable failure = null;
        try
        {
            // Send 'em over the wire
            channelContext = getChannel( type );
            Channel channel = channelContext.first();
            ChannelBuffer output = channelContext.second();
            ByteBuffer input = channelContext.third();

            Map<String, String> requestContext = new HashMap<String, String>();
            requestContext.put( "type", type.toString() );
            requestContext.put( "slaveContext", context.toString() );
            requestContext.put( "serverAddress", channel.getRemoteAddress().toString() );
            requestMonitor.beginRequest( requestContext );

            // Request
            protocol.serializeRequest( channel, output, type, context, serializer );

            // Response
            @SuppressWarnings("unchecked")
            Response<R> response = protocol.deserializeResponse(
                    (BlockingReadHandler<ChannelBuffer>) channel.getPipeline().get( "blockingHandler" ), input,
                    getReadTimeout( type, readTimeout ), deserializer, resourcePoolReleaser );

            if ( shouldCheckStoreId( type ) )
            {
                // specificStoreId is there as a workaround for then the graphDb isn't initialized yet
                if ( specificStoreId != null )
                {
                    assertCorrectStoreId( response.getStoreId(), specificStoreId );
                }
                else
                {
                    assertCorrectStoreId( response.getStoreId(), storeId );
                }
            }

            return response;
        }
        catch ( IllegalProtocolVersionException e )
        {
            failure = e;
            success = false;
            for ( MismatchingVersionHandler handler : mismatchingVersionHandlers )
            {
                handler.versionMismatched( e.getExpected(), e.getReceived() );
            }
            throw e;
        }
        catch ( Throwable e )
        {
            failure = e;
            success = false;
            if ( channelContext != null )
            {
                closeChannel( channelContext );
            }
            throw Exceptions.launderedException( ComException.class, e );
        }
        finally
        {
            /*
             * Otherwise the user must call response.close() to prevent resource leaks.
             */
            if ( !success )
            {
                releaseChannel();
            }
            requestMonitor.endRequest( failure );
        }
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method protected sendRequest(type RequestType<T>, context RequestContext, serializer Serializer, deserializer Deserializer<R>, specificStoreId StoreId) : Response<R> from class org.neo4j.com.Client


    @Override
    public ChannelPipeline getPipeline() throws Exception
    {
        ChannelPipeline pipeline = Channels.pipeline();
        addLengthFieldPipes( pipeline, frameLength );
        BlockingReadHandler<ChannelBuffer> reader = new BlockingReadHandler<>(
                new ArrayBlockingQueue<ChannelEvent>( 3, false ) );
        pipeline.addLast( "blockingHandler", reader );
        return pipeline;
    }

    @Override
    public ChannelPipeline getPipeline() throws Exception
    {
        ChannelPipeline pipeline = Channels.pipeline();
        addLengthFieldPipes( pipeline, frameLength );
        BlockingReadHandler<ChannelBuffer> reader = new BlockingReadHandler<ChannelBuffer>(
                new ArrayBlockingQueue<ChannelEvent>( 3, false ) );
        pipeline.addLast( "blockingHandler", reader );
        return pipeline;
    }

Replace Generic With Diamond BlockingReadHandler<ChannelBuffer> with BlockingReadHandler<> in method public getPipeline() : ChannelPipeline from class org.neo4j.com.Client


            @Override
            public void run()
            {
                Map<Channel, Boolean/*starting to get old?*/> channels = new HashMap<>();
                synchronized ( connectedSlaveChannels )
                {
                    for ( Map.Entry<Channel, Pair<RequestContext, AtomicLong>> channel : connectedSlaveChannels
                            .entrySet() )
                    {   // Has this channel been silent for a while?
                        long age = System.currentTimeMillis() - channel.getValue().other().get();
                        if ( age > oldChannelThresholdMillis )
                        {
                            msgLog.logMessage( "Found a silent channel " + channel + ", " + age );
                            channels.put( channel.getKey(), Boolean.TRUE );
                        }
                        else if ( age > oldChannelThresholdMillis / 2 )
                        {   // Then add it to a list to check
                            channels.put( channel.getKey(), Boolean.FALSE );
                        }
                    }
                }
                for ( Map.Entry<Channel, Boolean> channel : channels.entrySet() )
                {
                    if ( channel.getValue() || !channel.getKey().isOpen() || !channel.getKey().isConnected() ||
                            !channel.getKey().isBound() )
                    {
                        tryToFinishOffChannel( channel.getKey() );
                    }
                }
            }

            @Override
            public void run()
            {
                Map<Channel, Boolean/*starting to get old?*/> channels = new HashMap<Channel, Boolean>();
                synchronized ( connectedSlaveChannels )
                {
                    for ( Map.Entry<Channel, Pair<RequestContext, AtomicLong>> channel : connectedSlaveChannels
                            .entrySet() )
                    {   // Has this channel been silent for a while?
                        long age = System.currentTimeMillis() - channel.getValue().other().get();
                        if ( age > oldChannelThresholdMillis )
                        {
                            msgLog.logMessage( "Found a silent channel " + channel + ", " + age );
                            channels.put( channel.getKey(), Boolean.TRUE );
                        }
                        else if ( age > oldChannelThresholdMillis / 2 )
                        {   // Then add it to a list to check
                            channels.put( channel.getKey(), Boolean.FALSE );
                        }
                    }
                }
                for ( Map.Entry<Channel, Boolean> channel : channels.entrySet() )
                {
                    if ( channel.getValue() || !channel.getKey().isOpen() || !channel.getKey().isConnected() ||
                            !channel.getKey().isBound() )
                    {
                        tryToFinishOffChannel( channel.getKey() );
                    }
                }
            }

Replace Generic With Diamond HashMap<Channel,Boolean> with HashMap<> in method public run() : void from class org.neo4j.com.Server.silentChannelFinisher.new Runnable


    private Runnable silentChannelFinisher()
    {
        // This poller is here because sometimes Netty doesn't tell us when channels are
        // closed or disconnected. Most of the time it does, but this acts as a safety
        // net for those we don't get notifications for. When the bug is fixed remove this.
        return new Runnable()
        {
            @Override
            public void run()
            {
                Map<Channel, Boolean/*starting to get old?*/> channels = new HashMap<>();
                synchronized ( connectedSlaveChannels )
                {
                    for ( Map.Entry<Channel, Pair<RequestContext, AtomicLong>> channel : connectedSlaveChannels
                            .entrySet() )
                    {   // Has this channel been silent for a while?
                        long age = System.currentTimeMillis() - channel.getValue().other().get();
                        if ( age > oldChannelThresholdMillis )
                        {
                            msgLog.logMessage( "Found a silent channel " + channel + ", " + age );
                            channels.put( channel.getKey(), Boolean.TRUE );
                        }
                        else if ( age > oldChannelThresholdMillis / 2 )
                        {   // Then add it to a list to check
                            channels.put( channel.getKey(), Boolean.FALSE );
                        }
                    }
                }
                for ( Map.Entry<Channel, Boolean> channel : channels.entrySet() )
                {
                    if ( channel.getValue() || !channel.getKey().isOpen() || !channel.getKey().isConnected() ||
                            !channel.getKey().isBound() )
                    {
                        tryToFinishOffChannel( channel.getKey() );
                    }
                }
            }
        };
    }

    private Runnable silentChannelFinisher()
    {
        // This poller is here because sometimes Netty doesn't tell us when channels are
        // closed or disconnected. Most of the time it does, but this acts as a safety
        // net for those we don't get notifications for. When the bug is fixed remove this.
        return new Runnable()
        {
            @Override
            public void run()
            {
                Map<Channel, Boolean/*starting to get old?*/> channels = new HashMap<Channel, Boolean>();
                synchronized ( connectedSlaveChannels )
                {
                    for ( Map.Entry<Channel, Pair<RequestContext, AtomicLong>> channel : connectedSlaveChannels
                            .entrySet() )
                    {   // Has this channel been silent for a while?
                        long age = System.currentTimeMillis() - channel.getValue().other().get();
                        if ( age > oldChannelThresholdMillis )
                        {
                            msgLog.logMessage( "Found a silent channel " + channel + ", " + age );
                            channels.put( channel.getKey(), Boolean.TRUE );
                        }
                        else if ( age > oldChannelThresholdMillis / 2 )
                        {   // Then add it to a list to check
                            channels.put( channel.getKey(), Boolean.FALSE );
                        }
                    }
                }
                for ( Map.Entry<Channel, Boolean> channel : channels.entrySet() )
                {
                    if ( channel.getValue() || !channel.getKey().isOpen() || !channel.getKey().isConnected() ||
                            !channel.getKey().isBound() )
                    {
                        tryToFinishOffChannel( channel.getKey() );
                    }
                }
            }
        };
    }

Replace Generic With Diamond HashMap<Channel,Boolean> with HashMap<> in method private silentChannelFinisher() : Runnable from class org.neo4j.com.Server


    private static void writeTransactionStreams( TransactionStream txStream, ChannelBuffer buffer, ByteCounterMonitor bufferMonitor )
    {
        if ( !txStream.hasNext() )
        {
            buffer.writeByte( 0 );
            return;
        }

        String[] datasources = txStream.dataSourceNames();
        assert datasources.length <= 255 : "too many data sources";
        buffer.writeByte( datasources.length );
        Map<String, Integer> datasourceId = new HashMap<>();
        for ( int i = 0; i < datasources.length; i++ )
        {
            String datasource = datasources[i];
            writeString( buffer, datasource );
            datasourceId.put( datasource, i + 1/*0 means "no more transactions"*/ );
        }
        for ( Triplet<String, Long, TxExtractor> tx : IteratorUtil.asIterable( txStream ) )
        {
            buffer.writeByte( datasourceId.get( tx.first() ) );
            buffer.writeLong( tx.second() );
            BlockLogBuffer blockBuffer = new BlockLogBuffer( buffer, bufferMonitor );
            tx.third().extract( blockBuffer );
            blockBuffer.done();
        }
        buffer.writeByte( 0/*no more transactions*/ );
    }

    private static void writeTransactionStreams( TransactionStream txStream, ChannelBuffer buffer, ByteCounterMonitor bufferMonitor )
    {
        if ( !txStream.hasNext() )
        {
            buffer.writeByte( 0 );
            return;
        }

        String[] datasources = txStream.dataSourceNames();
        assert datasources.length <= 255 : "too many data sources";
        buffer.writeByte( datasources.length );
        Map<String, Integer> datasourceId = new HashMap<String, Integer>();
        for ( int i = 0; i < datasources.length; i++ )
        {
            String datasource = datasources[i];
            writeString( buffer, datasource );
            datasourceId.put( datasource, i + 1/*0 means "no more transactions"*/ );
        }
        for ( Triplet<String, Long, TxExtractor> tx : IteratorUtil.asIterable( txStream ) )
        {
            buffer.writeByte( datasourceId.get( tx.first() ) );
            buffer.writeLong( tx.second() );
            BlockLogBuffer blockBuffer = new BlockLogBuffer( buffer, bufferMonitor );
            tx.third().extract( blockBuffer );
            blockBuffer.done();
        }
        buffer.writeByte( 0/*no more transactions*/ );
    }

Replace Generic With Diamond HashMap<String,Integer> with HashMap<> in method private writeTransactionStreams(txStream TransactionStream, buffer ChannelBuffer, bufferMonitor ByteCounterMonitor) : void from class org.neo4j.com.Server


    public Map<Channel, RequestContext> getConnectedSlaveChannels()
    {
        Map<Channel, RequestContext> result = new HashMap<>();
        synchronized ( connectedSlaveChannels )
        {
            for ( Map.Entry<Channel, Pair<RequestContext, AtomicLong>> entry : connectedSlaveChannels.entrySet() )
            {
                result.put( entry.getKey(), entry.getValue().first() );
            }
        }
        return result;
    }

    public Map<Channel, RequestContext> getConnectedSlaveChannels()
    {
        Map<Channel, RequestContext> result = new HashMap<Channel, RequestContext>();
        synchronized ( connectedSlaveChannels )
        {
            for ( Map.Entry<Channel, Pair<RequestContext, AtomicLong>> entry : connectedSlaveChannels.entrySet() )
            {
                result.put( entry.getKey(), entry.getValue().first() );
            }
        }
        return result;
    }

Replace Generic With Diamond HashMap<Channel,RequestContext> with HashMap<> in method public getConnectedSlaveChannels() : Map<Channel,RequestContext> from class org.neo4j.com.Server


    @Override
    public void masterIsElected( HighAvailabilityMemberChangeEvent event )
    {
        if ( event.getNewState() == event.getOldState() && event.getOldState() == HighAvailabilityMemberState.MASTER )
        {
            clusterMemberAvailability.memberIsAvailable( MASTER, masterHaURI, resolveStoreId() );
        }
        else
        {
            try
            {
                stateChanged( event );
            }
            catch ( ExecutionException | InterruptedException e )
            {
                throw new RuntimeException( e );
            }
        }
    }

    @Override
    public void masterIsElected( HighAvailabilityMemberChangeEvent event )
    {
        if ( event.getNewState() == event.getOldState() && event.getOldState() == HighAvailabilityMemberState.MASTER )
        {
            clusterMemberAvailability.memberIsAvailable( MASTER, masterHaURI );
        }
        else
        {
            try
            {
                stateChanged( event );
            }
            catch ( ExecutionException e )
            {
                throw new RuntimeException( e );
            }
            catch ( InterruptedException e )
            {
                throw new RuntimeException( e );
            }
        }
    }

Merge Catch [catch(ExecutionException e), catch(InterruptedException e)] to catch(ExecutionException|InterruptedException e) in method public masterIsElected(event HighAvailabilityMemberChangeEvent) : void from class org.neo4j.kernel.ha.cluster.HighAvailabilityModeSwitcher


    @Override
    public void masterIsAvailable( HighAvailabilityMemberChangeEvent event )
    {
        if ( event.getNewState() == event.getOldState() && event.getOldState() == HighAvailabilityMemberState.SLAVE )
        {
            clusterMemberAvailability.memberIsAvailable( SLAVE, slaveHaURI, resolveStoreId() );
        }
        else
        {
            try
            {
                stateChanged( event );
            }
            catch ( ExecutionException | InterruptedException e )
            {
                throw new RuntimeException( e );
            }
        }
    }

    @Override
    public void masterIsAvailable( HighAvailabilityMemberChangeEvent event )
    {
        if ( event.getNewState() == event.getOldState() && event.getOldState() == HighAvailabilityMemberState.SLAVE )
        {
            clusterMemberAvailability.memberIsAvailable( SLAVE, slaveHaURI );
        }
        else
        {
            try
            {
                stateChanged( event );
            }
            catch ( ExecutionException e )
            {
                throw new RuntimeException( e );
            }
            catch ( InterruptedException e )
            {
                throw new RuntimeException( e );
            }
        }
    }

Merge Catch [catch(ExecutionException e), catch(InterruptedException e)] to catch(ExecutionException|InterruptedException e) in method public masterIsAvailable(event HighAvailabilityMemberChangeEvent) : void from class org.neo4j.kernel.ha.cluster.HighAvailabilityModeSwitcher


    @Override
    public void instanceStops( HighAvailabilityMemberChangeEvent event )
    {
        try
        {
            stateChanged( event );
        }
        catch ( ExecutionException | InterruptedException e )
        {
            throw new RuntimeException( e );
        }
    }

    @Override
    public void instanceStops( HighAvailabilityMemberChangeEvent event )
    {
        try
        {
            stateChanged( event );
        }
        catch ( ExecutionException e )
        {
            throw new RuntimeException( e );
        }
        catch ( InterruptedException e )
        {
            throw new RuntimeException( e );
        }
    }

Merge Catch [catch(ExecutionException e), catch(InterruptedException e)] to catch(ExecutionException|InterruptedException e) in method public instanceStops(event HighAvailabilityMemberChangeEvent) : void from class org.neo4j.kernel.ha.cluster.HighAvailabilityModeSwitcher


        @Override
        public void coordinatorIsElected( InstanceId coordinatorId )
        {
            if ( coordinatorId.equals( this.masterId ) )
            {
                return;
            }
            this.masterId = coordinatorId;
            Map<InstanceId, ClusterMember> newMembers = new HashMap<>();
            for ( Map.Entry<InstanceId, ClusterMember> memberEntry : members.entrySet() )
            {
                newMembers.put( memberEntry.getKey(), memberEntry.getValue().unavailableAs(
                        HighAvailabilityModeSwitcher.MASTER ).unavailableAs( HighAvailabilityModeSwitcher.SLAVE ) );
            }
            members.clear();
            members.putAll( newMembers );
        }

        @Override
        public void coordinatorIsElected( InstanceId coordinatorId )
        {
            if ( coordinatorId.equals( this.masterId ) )
            {
                return;
            }
            this.masterId = coordinatorId;
            Map<InstanceId, ClusterMember> newMembers = new CopyOnWriteHashMap<InstanceId, ClusterMember>();
            for ( Map.Entry<InstanceId, ClusterMember> memberEntry : members.entrySet() )
            {
                newMembers.put( memberEntry.getKey(), memberEntry.getValue().unavailableAs(
                        HighAvailabilityModeSwitcher.MASTER ).unavailableAs( HighAvailabilityModeSwitcher.SLAVE ) );
            }
            members.clear();
            members.putAll( newMembers );
        }

Replace Generic With Diamond CopyOnWriteHashMap<InstanceId,ClusterMember> with HashMap<> in method public coordinatorIsElected(coordinatorId InstanceId) : void from class org.neo4j.kernel.ha.cluster.member.ClusterMembers.HAMClusterMemberListener