    private long createNode( HighlyAvailableGraphDatabase author, String key, Object value, boolean index )
    {

        try (Transaction tx = author.beginTx())
        {
            Node node = author.createNode();
            node.setProperty( key, value );
            if ( index )
                author.index().forNodes( key ).add( node, key, value );
            tx.success();
            return node.getId();
        }
        catch( Exception e)
        {
            e.printStackTrace( System.err );
            throw e;
        }
    }

    private long createNode( HighlyAvailableGraphDatabase author, String key, Object value, boolean index )
    {
        Transaction tx = author.beginTx();
        try
        {
            Node node = author.createNode();
            node.setProperty( key, value );
            if ( index )
                author.index().forNodes( key ).add( node, key, value );
            tx.success();
            return node.getId();
        }
        catch( Exception e)
        {
            e.printStackTrace( System.err );
            throw e;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=author.beginTx()) in method private createNode(author HighlyAvailableGraphDatabase, key String, value Object, index boolean) : long from class org.neo4j.kernel.index.IndexOperationsIT


    private void assertNodeAndIndexingExists( HighlyAvailableGraphDatabase db, long nodeId, String key, Object value )
    {
        try (Transaction transaction = db.beginTx())
        {
            Node node = db.getNodeById( nodeId );
            assertEquals( value, node.getProperty( key ) );
            assertTrue( db.index().existsForNodes( key ) );
            assertEquals( node, db.index().forNodes( key ).get( key, value ).getSingle() );
        }
    }

    private void assertNodeAndIndexingExists( HighlyAvailableGraphDatabase db, long nodeId, String key, Object value )
    {
        Transaction transaction = db.beginTx();
        try
        {
            Node node = db.getNodeById( nodeId );
            assertEquals( value, node.getProperty( key ) );
            assertTrue( db.index().existsForNodes( key ) );
            assertEquals( node, db.index().forNodes( key ).get( key, value ).getSingle() );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method private assertNodeAndIndexingExists(db HighlyAvailableGraphDatabase, nodeId long, key String, value Object) : void from class org.neo4j.kernel.index.IndexOperationsIT


    @Test
    public void given4instanceClusterWhenMasterGoesDownThenElectNewMaster() throws Throwable
    {
        ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/fourinstances.xml" ).toURI() ),
                testDirectory.directory( "4instances" ), MapUtil.stringMap() );
        try
        {
            clusterManager.start();
            ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();
            cluster.await( allSeesAllAsAvailable() );

            logging.getLogger().info( "STOPPING MASTER" );
            cluster.shutdown( cluster.getMaster() );
            logging.getLogger().info( "STOPPED MASTER" );

            cluster.await( ClusterManager.masterAvailable() );

            GraphDatabaseService master = cluster.getMaster();
            logging.getLogger().info( "CREATE NODE" );
            try ( Transaction tx = master.beginTx() )
            {
                master.createNode();
                logging.getLogger().info( "CREATED NODE" );
                tx.success();
            }

            logging.getLogger().info( "STOPPING CLUSTER" );
        }
        finally
        {
            clusterManager.stop();
        }
    }

    @Test
    public void given4instanceClusterWhenMasterGoesDownThenElectNewMaster() throws Throwable
    {
        ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/fourinstances.xml" ).toURI() ),
                TargetDirectory.forTest( getClass() ).cleanDirectory( "4instances" ), MapUtil.stringMap() );
        try
        {
            clusterManager.start();
            ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();
            cluster.await( allSeesAllAsAvailable() );

            logging.getLogger().info( "STOPPING MASTER" );
            cluster.shutdown( cluster.getMaster() );
            logging.getLogger().info( "STOPPED MASTER" );

            cluster.await( ClusterManager.masterAvailable() );

            GraphDatabaseService master = cluster.getMaster();
            logging.getLogger().info( "CREATE NODE" );
            Transaction tx = master.beginTx();
            master.createNode();
            logging.getLogger().info( "CREATED NODE" );
            tx.success();
            tx.finish();

            logging.getLogger().info( "STOPPING CLUSTER" );
        }
        finally
        {
            clusterManager.stop();
        }
    }

Try With Resources try(Transaction tx=master.beginTx()) in method public given4instanceClusterWhenMasterGoesDownThenElectNewMaster() : void from class org.neo4j.test.ha.ClusterTest


    @Test
    public void shouldUseConfiguredPageSizeAndFitAsManyPagesAsItCan() throws Throwable
    {
        // Given
        Config config = new Config();
        config.applyChanges( stringMap(
                mapped_memory_page_size.name(), "4096",
                pagecache_memory.name(), Integer.toString( 4096 * 16 ) ) );

        // When
        ConfiguringPageCacheFactory pageCacheFactory = new ConfiguringPageCacheFactory(
                fsRule.get(), config, PageCacheTracer.NULL, NullLog.getInstance() );

        // Then
        try ( PageCache cache = pageCacheFactory.getOrCreatePageCache() )
        {
            assertThat( cache.pageSize(), equalTo( 4096 ) );
            assertThat( cache.maxCachedPages(), equalTo( 16 ) );
        }
    }

    @Test
    public void shouldUseConfiguredPageSizeAndFitAsManyPagesAsItCan() throws Throwable
    {
        // Given
        Config config = new Config();
        config.applyChanges( stringMap(
                mapped_memory_page_size.name(), "4096",
                pagecache_memory.name(), Integer.toString( 4096 * 16 ) ) );

        // When
        ConfiguringPageCacheFactory pageCacheFactory = new ConfiguringPageCacheFactory(
                fsRule.get(), config, PageCacheTracer.NULL, NullLog.getInstance() );
        PageCache cache = pageCacheFactory.getOrCreatePageCache();

        // Then
        try
        {
            assertThat( cache.pageSize(), equalTo( 4096 ) );
            assertThat( cache.maxCachedPages(), equalTo( 16 ) );
        }
        finally
        {
            cache.close();
        }
    }

Try With Resources try(PageCache cache=pageCacheFactory.getOrCreatePageCache()) in method public shouldUseConfiguredPageSizeAndFitAsManyPagesAsItCan() : void from class org.neo4j.kernel.impl.pagecache.ConfiguringPageCacheFactoryTest


            @Override
            public void run( Sender sender )
            {
                assertHealthy();
                sender.initialize( ticket );
                try
                {
                    // If we're ordering tickets we will force calls to #permit to be ordered by ticket
                    // since grabbing a permit may include locking.
                    if ( guarantees( ORDER_PROCESS ) )
                    {
                        await( rightBeginTicket, ticket );
                    }
                    try ( Resource precondition = permit( batch ) )
                    {
                        begunBatches.incrementAndGet();
                        long startTime = currentTimeMillis();
                        process( batch, sender );
                        if ( downstream == null )
                        {
                            // No batches were emmitted so we couldn't track done batches in that way.
                            // We can see that we're the last step so increment here instead
                            doneBatches.incrementAndGet();
                        }
                        totalProcessingTime.add( currentTimeMillis()-startTime-sender.sendTime );
                    }

                    decrementQueue();
                    checkNotifyEndDownstream();
                }
                catch ( Throwable e )
                {
                    issuePanic( e );
                }
            }

            @Override
            public void run( Sender sender )
            {
                assertHealthy();
                sender.initialize( ticket );
                long startTime = currentTimeMillis();
                try
                {
                    process( batch, sender );
                    if ( downstream == null )
                    {
                        // No batches were emmitted so we couldn't track done batches in that way.
                        // We can see that we're the last step so increment here instead
                        doneBatches.incrementAndGet();
                    }
                    totalProcessingTime.add( currentTimeMillis()-startTime-sender.sendTime );
                    decrementQueue();
                    checkNotifyEndDownstream();
                }
                catch ( Throwable e )
                {
                    issuePanic( e );
                }
            }

Try With Resources try(Resource precondition=permit(batch)) in method public run(sender Sender) : void from class org.neo4j.unsafe.impl.batchimport.staging.ProcessorStep.receive.submit.new Task<Sender>


    private boolean serverResponds( String host, int port ) throws IOException, InterruptedException
    {
        try
        {
            try(Socket socket = new Socket())
            {
                // Ok, we can connect - can we perform the version handshake?
                socket.connect( new InetSocketAddress( host, port ) );
                OutputStream out = socket.getOutputStream();
                InputStream in = socket.getInputStream();

                // Hard-coded handshake, a general "test client" would be useful further on.
                out.write( new byte[]{ 0,0,0,1, 0,0,0,0, 0,0,0,0, 0,0,0,0 } );

                byte[] accepted = new byte[4];
                in.read( accepted );

                return Arrays.equals( accepted, new byte[]{0,0,0,1} );
            }
        }
        catch(ConnectException e)
        {
            return false;
        }
    }

    private boolean serverResponds( String host, int port ) throws IOException, InterruptedException
    {
        try
        {
            URI.create( "http://"+host+":"+port ).toURL().openStream().close();
            return true;
        }
        catch(FileNotFoundException e)
        {
            // ok, 404, which is fine for now
            return true;
        }
        catch(ConnectException e)
        {
            return false;
        }
    }

Try With Resources try(Socket socket=new Socket()) in method private serverResponds(host String, port int) : boolean from class org.neo4j.ext.NDPExtensionIT


    @SuppressWarnings( { "unchecked", "rawtypes" } )
    private Collection<Long> toLongs( Set<Object> ids )
    {
        if (ids.isEmpty()) return Collections.emptySet();

        if ( ids.iterator().next() instanceof Long )
        {
            return (Collection) ids;
        }
        else
        {
            Collection<Long> longs = new ArrayList<>(ids.size());
            for ( Object id : ids )
            {
                longs.add( ((RelationshipId) id).id );
            }
            return longs;
        }
    }

    @SuppressWarnings( { "unchecked", "rawtypes" } )
    private Collection<Long> toLongs( Set<Object> ids )
    {
        if (ids.isEmpty()) return Collections.emptySet();

        if ( ids.iterator().next() instanceof Long )
        {
            return (Collection) ids;
        }
        else
        {
            Collection<Long> longs = new ArrayList<Long>(ids.size());
            for ( Object id : ids )
            {
                longs.add( ((RelationshipId) id).id );
            }
            return longs;
        }
    }

Replace Generic With Diamond ArrayList<Long> with ArrayList<> in method private toLongs(ids Set<Object>) : Collection<Long> from class org.neo4j.index.impl.lucene.ExactTxData


    private void addOrphan( String key )
    {
        if ( orphans == null )
        {
            orphans = new HashSet<>();
        }
        orphans.add( key );
    }

    private void addOrphan( String key )
    {
        if ( orphans == null )
        {
            orphans = new HashSet<String>();
        }
        orphans.add( key );
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method private addOrphan(key String) : void from class org.neo4j.index.impl.lucene.FullTxData


    public static <T> Iterator<T> notNull( Iterator<T> source )
    {
        return new FilteringIterator<>( source, Predicates.<T>notNull() );
    }

    public static <T> Iterator<T> notNull( Iterator<T> source )
    {
        return new FilteringIterator<T>( source, FilteringIterable.<T>notNullPredicate() );
    }

Replace Generic With Diamond FilteringIterator<T> with FilteringIterator<> in method public notNull(source Iterator<T>) : Iterator<T> from class org.neo4j.helpers.collection.FilteringIterator


    public static <T> Iterator<T> noDuplicates( Iterator<T> source )
    {
        return new FilteringIterator<>( source, Predicates.<T>noDuplicates() );
    }

    public static <T> Iterator<T> noDuplicates( Iterator<T> source )
    {
        return new FilteringIterator<T>( source, FilteringIterable.<T>noDuplicatesPredicate() );
    }

Replace Generic With Diamond FilteringIterator<T> with FilteringIterator<> in method public noDuplicates(source Iterator<T>) : Iterator<T> from class org.neo4j.helpers.collection.FilteringIterator


    /**
     * Obtains lock on store file so that we can ensure the store is not shared between database instances
     * <p/>
     * Creates store dir if necessary, creates store lock file if necessary
     *
     * @throws StoreLockException if lock could not be acquired
     */
    public void checkLock( File storeDir ) throws StoreLockException
    {
        File storeLockFile = new File( storeDir, STORE_LOCK_FILENAME );

        try
        {
            if ( !fileSystemAbstraction.fileExists( storeLockFile ) )
            {
                fileSystemAbstraction.mkdirs( storeLockFile.getParentFile() );
            }
        }
        catch ( IOException e )
        {
            throw new StoreLockException( "Unable to create path for store dir: " + storeDir+". Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)", e );
        }

        try
        {
            storeLockFileChannel = fileSystemAbstraction.open( storeLockFile, "rw" );
            storeLockFileLock = fileSystemAbstraction.tryLock( storeLockFile, storeLockFileChannel );
        }
        catch ( OverlappingFileLockException | IOException e )
        {
            throw new StoreLockException( "Unable to obtain lock on store lock file: " + storeLockFile+". Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)", e );
        }
    }

    /**
     * Obtains lock on store file so that we can ensure the store is not shared between database instances
     * <p/>
     * Creates store dir if necessary, creates store lock file if necessary
     *
     * @throws StoreLockException if lock could not be acquired
     */
    public void checkLock( File storeDir ) throws StoreLockException
    {
        File storeLockFile = new File( storeDir, STORE_LOCK_FILENAME );

        try
        {
            if ( !fileSystemAbstraction.fileExists( storeLockFile ) )
            {
                fileSystemAbstraction.mkdirs( storeLockFile.getParentFile() );
            }
        }
        catch ( IOException e )
        {
            throw new StoreLockException( "Unable to create path for store dir: " + storeDir+". Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)", e );
        }

        try
        {
            storeLockFileChannel = fileSystemAbstraction.open( storeLockFile, "rw" );
            storeLockFileLock = fileSystemAbstraction.tryLock( storeLockFile, storeLockFileChannel );
        }
        catch ( OverlappingFileLockException e )
        {
            throw new StoreLockException( "Unable to obtain lock on store lock file: " + storeLockFile+". Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)", e );
        }
        catch ( IOException e )
        {
            throw new StoreLockException( "Unable to obtain lock on store lock file: " + storeLockFile+". Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)", e );
        }
    }

Merge Catch [catch(OverlappingFileLockException e), catch(IOException e)] to catch(OverlappingFileLockException|IOException e) in method public checkLock(storeDir File) : void from class org.neo4j.kernel.StoreLocker


    BackupOutcome doFullBackup( final String sourceHostNameOrIp, final int sourcePort, String targetDirectory,
            boolean checkConsistency, Config tuningConfiguration, final long timeout, final boolean forensics )
    {
        if ( directoryContainsDb( targetDirectory ) )
        {
            throw new RuntimeException( targetDirectory + " already contains a database" );
        }
        Map<String, String> params = tuningConfiguration.getParams();
        params.put( GraphDatabaseSettings.store_dir.name(), targetDirectory );
        tuningConfiguration.applyChanges( params );
        long timestamp = System.currentTimeMillis();
        long lastCommittedTx = -1;
        boolean consistent = !checkConsistency; // default to true if we're not checking consistency
        GraphDatabaseAPI targetDb = null;
        try ( StandalonePageCache pageCache = createPageCache( fileSystem, "BackupService PageCache" ) )
        {
            StoreCopyClient storeCopier = new StoreCopyClient( tuningConfiguration, loadKernelExtensions(),
                    new ConsoleLogger( StringLogger.SYSTEM ), new DevNullLoggingService(),
                    new DefaultFileSystemAbstraction(), pageCache, new Monitors().newMonitor( StoreCopyMonitor.class, getClass() ) );
            storeCopier.copyStore( new StoreCopyClient.StoreCopyRequester()

            {
                private BackupClient client;

                @Override
                public Response<?> copyStore( StoreWriter writer )
                {
                    Monitors monitors = new Monitors();
                    client = new BackupClient( sourceHostNameOrIp, sourcePort, new DevNullLoggingService(),
                            StoreId.DEFAULT, timeout, ResponseUnpacker.NO_OP_RESPONSE_UNPACKER,
                            monitors.newMonitor( ByteCounterMonitor.class ),
                            monitors.newMonitor( RequestMonitor.class ) );
                    client.start();
                    return client.fullBackup( writer, forensics );
                }

                @Override
                public void done()
                {
                    client.stop();
                }
            }, CancellationRequest.NEVER_CANCELLED );

            targetDb = startTemporaryDb( targetDirectory );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
        finally
        {
            if ( targetDb != null )
            {
                targetDb.shutdown();
            }
        }
        bumpMessagesDotLogFile( targetDirectory, timestamp );
        if ( checkConsistency )
        {
            try
            {
                consistent = new ConsistencyCheckService().runFullConsistencyCheck( targetDirectory,
                        tuningConfiguration, ProgressMonitorFactory.textual( System.err ), logger ).isSuccessful();
            }
            catch ( ConsistencyCheckIncompleteException e )
            {
                logger.error( "Consistency check incomplete", e );
            }
            finally
            {
                logger.flush();
            }
        }
        return new BackupOutcome( lastCommittedTx, consistent );
    }

    BackupOutcome doFullBackup( final String sourceHostNameOrIp, final int sourcePort, String targetDirectory,
            boolean checkConsistency, Config tuningConfiguration, final long timeout, final boolean forensics )
    {
        if ( directoryContainsDb( targetDirectory ) )
        {
            throw new RuntimeException( targetDirectory + " already contains a database" );
        }
        Map<String, String> params = tuningConfiguration.getParams();
        params.put( GraphDatabaseSettings.store_dir.name(), targetDirectory );
        tuningConfiguration.applyChanges( params );
        long timestamp = System.currentTimeMillis();
        long lastCommittedTx = -1;
        boolean consistent = !checkConsistency; // default to true if we're not checking consistency
        GraphDatabaseAPI targetDb = null;
        try
        {
            StoreCopyClient storeCopier = new StoreCopyClient( tuningConfiguration, loadKernelExtensions(),
                    new ConsoleLogger( StringLogger.SYSTEM ), new DevNullLoggingService(),
                    new DefaultFileSystemAbstraction(), new Monitors().newMonitor( StoreCopyMonitor.class, getClass() ) );
            storeCopier.copyStore( new StoreCopyClient.StoreCopyRequester()

            {
                private BackupClient client;

                @Override
                public Response<?> copyStore( StoreWriter writer )
                {
                    Monitors monitors = new Monitors();
                    client = new BackupClient( sourceHostNameOrIp, sourcePort, new DevNullLoggingService(),
                            StoreId.DEFAULT, timeout, ResponseUnpacker.NO_OP_RESPONSE_UNPACKER,
                            monitors.newMonitor( ByteCounterMonitor.class ),
                            monitors.newMonitor( RequestMonitor.class ) );
                    client.start();
                    return client.fullBackup( writer, forensics );
                }

                @Override
                public void done()
                {
                    client.stop();
                }
            }, CancellationRequest.NEVER_CANCELLED );

            targetDb = startTemporaryDb( targetDirectory );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
        finally
        {
            if ( targetDb != null )
            {
                targetDb.shutdown();
            }
        }
        bumpMessagesDotLogFile( targetDirectory, timestamp );
        if ( checkConsistency )
        {
            try
            {
                consistent = new ConsistencyCheckService().runFullConsistencyCheck( targetDirectory,
                        tuningConfiguration, ProgressMonitorFactory.textual( System.err ), logger ).isSuccessful();
            }
            catch ( ConsistencyCheckIncompleteException e )
            {
                logger.error( "Consistency check incomplete", e );
            }
            finally
            {
                logger.flush();
            }
        }
        return new BackupOutcome( lastCommittedTx, consistent );
    }

Try With Resources try(StandalonePageCache pageCache=createPageCache(fileSystem,"BackupService PageCache")) in method package doFullBackup(sourceHostNameOrIp String, sourcePort int, targetDirectory String, checkConsistency boolean, tuningConfiguration Config, timeout long, forensics boolean) : BackupOutcome from class org.neo4j.backup.BackupService


    /**
     * Load Properties file from a given URL, and add the settings to
     * the builder.
     *
     * @return the builder
     */
    public GraphDatabaseBuilder loadPropertiesFromURL( URL url )
            throws IllegalArgumentException
    {
        Properties props = new Properties();
        try
        {
            try ( InputStream stream = url.openStream() )
            {
                props.load( stream );
            }
        }
        catch ( Exception e )
        {
            throw new IllegalArgumentException( "Unable to load " + url, e );
        }
        Set<Map.Entry<Object, Object>> entries = props.entrySet();
        for ( Map.Entry<Object, Object> entry : entries )
        {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            setConfig( key, value );
        }

        return this;
    }

    /**
     * Load Properties file from a given URL, and add the settings to
     * the builder.
     *
     * @return the builder
     */
    public GraphDatabaseBuilder loadPropertiesFromURL( URL url )
            throws IllegalArgumentException
    {
        Properties props = new Properties();
        try
        {
            InputStream stream = url.openStream();
            try
            {
                props.load( stream );
            }
            finally
            {
                stream.close();
            }
        }
        catch ( Exception e )
        {
            throw new IllegalArgumentException( "Unable to load " + url, e );
        }
        Set<Map.Entry<Object, Object>> entries = props.entrySet();
        for ( Map.Entry<Object, Object> entry : entries )
        {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            setConfig( key, value );
        }

        return this;
    }

Try With Resources try(InputStream stream=url.openStream()) in method public loadPropertiesFromURL(url URL) : GraphDatabaseBuilder from class org.neo4j.graphdb.factory.GraphDatabaseBuilder


    private void createDbIfNecessary()
    {
        if ( !new File( dbRule.getStoreDir(), "neostore" ).exists() )
        {
            db = dbRule.getGraphDatabaseService();
            try ( BatchTransaction tx = beginBatchTx( db ) )
            {
                Node node = db.createNode();
                createRelationships( tx, node, MyRelTypes.TEST, INCOMING, 1 );
                createRelationships( tx, node, MyRelTypes.TEST, OUTGOING, 3_000_000 );
                createRelationships( tx, node, MyRelTypes.TEST2, OUTGOING, 5 );
                createRelationships( tx, node, MyRelTypes.TEST2, BOTH, 5 );
                createRelationships( tx, node, MyRelTypes.TEST_TRAVERSAL, OUTGOING, 2_000_000 );
                createRelationships( tx, node, MyRelTypes.TEST_TRAVERSAL, INCOMING, 2 );
            }
            finally
            {
                dbRule.stopAndKeepFiles();
            }
        }
    }

    private void createDbIfNecessary()
    {
        if ( !new File( storeDir, "neostore" ).exists() )
        {
            db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getPath() );
            BatchTransaction tx = beginBatchTx( db );
            try
            {
                Node node = db.createNode();
                createRelationships( tx, node, MyRelTypes.TEST, INCOMING, 1 );
                createRelationships( tx, node, MyRelTypes.TEST, OUTGOING, 3_000_000 );
                createRelationships( tx, node, MyRelTypes.TEST2, OUTGOING, 5 );
                createRelationships( tx, node, MyRelTypes.TEST2, BOTH, 5 );
                createRelationships( tx, node, MyRelTypes.TEST_TRAVERSAL, OUTGOING, 2_000_000 );
                createRelationships( tx, node, MyRelTypes.TEST_TRAVERSAL, INCOMING, 2 );
            }
            finally
            {
                tx.close();
                db.shutdown();
            }
        }
    }

Try With Resources try(BatchTransaction tx=beginBatchTx(db)) in method private createDbIfNecessary() : void from class examples.CreateAndLoadDenseNodeIT


        private void compareIndex( NodeRep other, DiffReport diff )
        {
            if ( other.index == index )
                return;
            Collection<String> allIndexes = new HashSet<>();
            allIndexes.addAll( index.keySet() );
            allIndexes.addAll( other.index.keySet() );
            for ( String indexName : allIndexes )
            {
                if ( !index.containsKey( indexName ) )
                {
                    diff.add( this + " isn't indexed in " + indexName + " for mine" );
                    continue;
                }
                if ( !other.index.containsKey( indexName ) )
                {
                    diff.add( this + " isn't indexed in " + indexName + " for other" );
                    continue;
                }

                Map<String, Serializable> thisIndex = index.get( indexName );
                Map<String, Serializable> otherIndex = other.index.get( indexName );

                if ( thisIndex.size() != otherIndex.size() )
                {
                    diff.add( "other index had a different mapping count than me for node " + this + " mine:" + thisIndex + ", other:" + otherIndex );
                    continue;
                }

                for ( Map.Entry<String, Serializable> indexEntry : thisIndex.entrySet() )
                {
                    if ( !indexEntry.getValue().equals(
                            otherIndex.get( indexEntry.getKey() ) ) )
                    {
                        diff.add( "other index had a different value indexed for " + indexEntry.getKey() + "=" +
                                indexEntry.getValue() + ", namely " + otherIndex.get( indexEntry.getKey() ) + " for " + this );
                    }
                }
            }
        }

        private void compareIndex( NodeRep other, DiffReport diff )
        {
            if ( other.index == index )
                return;
            Collection<String> allIndexes = new HashSet<String>();
            allIndexes.addAll( index.keySet() );
            allIndexes.addAll( other.index.keySet() );
            for ( String indexName : allIndexes )
            {
                if ( !index.containsKey( indexName ) )
                {
                    diff.add( this + " isn't indexed in " + indexName + " for mine" );
                    continue;
                }
                if ( !other.index.containsKey( indexName ) )
                {
                    diff.add( this + " isn't indexed in " + indexName + " for other" );
                    continue;
                }

                Map<String, Serializable> thisIndex = index.get( indexName );
                Map<String, Serializable> otherIndex = other.index.get( indexName );

                if ( thisIndex.size() != otherIndex.size() )
                {
                    diff.add( "other index had a different mapping count than me for node " + this + " mine:" + thisIndex + ", other:" + otherIndex );
                    continue;
                }

                for ( Map.Entry<String, Serializable> indexEntry : thisIndex.entrySet() )
                {
                    if ( !indexEntry.getValue().equals(
                            otherIndex.get( indexEntry.getKey() ) ) )
                    {
                        diff.add( "other index had a different value indexed for " + indexEntry.getKey() + "=" +
                                indexEntry.getValue() + ", namely " + otherIndex.get( indexEntry.getKey() ) + " for " + this );
                    }
                }
            }
        }

Replace Generic With Diamond HashSet<String> with HashSet<> in method private compareIndex(other NodeRep, diff DiffReport) : void from class org.neo4j.test.DbRepresentation.NodeRep


        PropertiesRep( PropertyContainer entity, long id )
        {
            this.entityId = id;
            this.entityToString = entity.toString();
            for ( String key : entity.getPropertyKeys() )
            {
                Serializable value = (Serializable) entity.getProperty( key, null );
                // We do this because the node may have changed since we did getPropertyKeys()
                if ( value != null )
                {
                    if ( value.getClass().isArray() )
                    {
                        props.put( key, new ArrayList<>( Arrays.asList( IoPrimitiveUtils.asArray( value ) ) ) );
                    }
                    else
                    {
                        props.put( key, value );
                    }
                }
            }
        }

        PropertiesRep( PropertyContainer entity, long id )
        {
            this.entityId = id;
            this.entityToString = entity.toString();
            for ( String key : entity.getPropertyKeys() )
            {
                Serializable value = (Serializable) entity.getProperty( key, null );
                // We do this because the node may have changed since we did getPropertyKeys()
                if ( value != null )
                {
                    if ( value.getClass().isArray() )
                    {
                        props.put( key, new ArrayList<Object>( Arrays.asList( IoPrimitiveUtils.asArray( value ) ) ) );
                    }
                    else
                    {
                        props.put( key, value );
                    }
                }
            }
        }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method package PropertiesRep(entity PropertyContainer, id long) from class org.neo4j.test.DbRepresentation.PropertiesRep


    public static DbRepresentation of( GraphDatabaseService db, boolean includeIndexes )
    {
        try ( Transaction ignore = db.beginTx() )
        {
            DbRepresentation result = new DbRepresentation();
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
            {
                NodeRep nodeRep = new NodeRep( db, node, includeIndexes );
                result.nodes.put( node.getId(), nodeRep );
                result.highestNodeId = Math.max( node.getId(), result.highestNodeId );
                result.highestRelationshipId = Math.max( nodeRep.highestRelationshipId, result.highestRelationshipId );
            }
            return result;
        }
    }

    public static DbRepresentation of( GraphDatabaseService db, boolean includeIndexes )
    {
        Transaction tx = db.beginTx();
        try
        {
            DbRepresentation result = new DbRepresentation();
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
            {
                NodeRep nodeRep = new NodeRep( db, node, includeIndexes );
                result.nodes.put( node.getId(), nodeRep );
                result.highestNodeId = Math.max( node.getId(), result.highestNodeId );
                result.highestRelationshipId = Math.max( nodeRep.highestRelationshipId, result.highestRelationshipId );
            }
            return result;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction ignore=db.beginTx()) in method public of(db GraphDatabaseService, includeIndexes boolean) : DbRepresentation from class org.neo4j.test.DbRepresentation


    public Collection<String> compareWith( DbRepresentation other )
    {
        Collection<String> diffList = new ArrayList<>();
        DiffReport diff = new CollectionDiffReport( diffList );
        for ( NodeRep node : nodes.values() )
        {
            NodeRep otherNode = other.nodes.get( node.id );
            if ( otherNode == null )
            {
                diff.add( "I have node " + node.id + " which other don't" );
                continue;
            }
            node.compareWith( otherNode, diff );
        }

        for ( Long id : other.nodes.keySet() )
        {
            if ( !nodes.containsKey( id ) )
                diff.add( "Other has node " + id + " which I don't" );
        }
        return diffList;
    }

    public Collection<String> compareWith( DbRepresentation other )
    {
        Collection<String> diffList = new ArrayList<String>();
        DiffReport diff = new CollectionDiffReport( diffList );
        for ( NodeRep node : nodes.values() )
        {
            NodeRep otherNode = other.nodes.get( node.id );
            if ( otherNode == null )
            {
                diff.add( "I have node " + node.id + " which other don't" );
                continue;
            }
            node.compareWith( otherNode, diff );
        }

        for ( Long id : other.nodes.keySet() )
        {
            if ( !nodes.containsKey( id ) )
                diff.add( "Other has node " + id + " which I don't" );
        }
        return diffList;
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public compareWith(other DbRepresentation) : Collection<String> from class org.neo4j.test.DbRepresentation


    @Test
    public void canReadAndUpgradeOldIndexStoreFormat() throws Exception
    {
        File path = new File( "target/var/old-index-store" );
        Neo4jTestCase.deleteFileOrDirectory( path );
        startDatabase( path ).shutdown();
        InputStream stream = getClass().getClassLoader().getResourceAsStream( "old-index.db" );
        writeFile( stream, new File( path, "index.db" ) );
        GraphDatabaseService db = startDatabase( path );
        try ( Transaction ignore = db.beginTx() )
        {
            assertTrue( db.index().existsForNodes( "indexOne" ) );
            Index<Node> indexOne = db.index().forNodes( "indexOne" );
            verifyConfiguration( db, indexOne, LuceneIndexImplementation.EXACT_CONFIG );
            assertTrue( db.index().existsForNodes( "indexTwo" ) );
            Index<Node> indexTwo = db.index().forNodes( "indexTwo" );
            verifyConfiguration( db, indexTwo, LuceneIndexImplementation.FULLTEXT_CONFIG );
            assertTrue( db.index().existsForRelationships( "indexThree" ) );
            Index<Relationship> indexThree = db.index().forRelationships( "indexThree" );
            verifyConfiguration( db, indexThree, LuceneIndexImplementation.EXACT_CONFIG );
        }
        db.shutdown();
    }

    @Test
    public void canReadAndUpgradeOldIndexStoreFormat() throws Exception
    {
        String path = "target/var/old-index-store";
        Neo4jTestCase.deleteFileOrDirectory( new File( path ) );
        GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( path );
        db.shutdown();
        InputStream stream = getClass().getClassLoader().getResourceAsStream( "old-index.db" );
        writeFile( stream, new File( path, "index.db" ) );
        db = new GraphDatabaseFactory().newEmbeddedDatabase( path );
        Transaction transaction = db.beginTx();
        try
        {
            assertTrue( db.index().existsForNodes( "indexOne" ) );
            Index<Node> indexOne = db.index().forNodes( "indexOne" );
            verifyConfiguration( db, indexOne, LuceneIndexImplementation.EXACT_CONFIG );
            assertTrue( db.index().existsForNodes( "indexTwo" ) );
            Index<Node> indexTwo = db.index().forNodes( "indexTwo" );
            verifyConfiguration( db, indexTwo, LuceneIndexImplementation.FULLTEXT_CONFIG );
            assertTrue( db.index().existsForRelationships( "indexThree" ) );
            Index<Relationship> indexThree = db.index().forRelationships( "indexThree" );
            verifyConfiguration( db, indexThree, LuceneIndexImplementation.EXACT_CONFIG );
        }
        finally
        {
            transaction.finish();
        }
        db.shutdown();
    }

Try With Resources try(Transaction ignore=db.beginTx()) in method public canReadAndUpgradeOldIndexStoreFormat() : void from class org.neo4j.index.impl.lucene.TestMigration


    public static int runBackupToolFromOtherJvmToGetExitCode( String... args )
            throws Exception
    {
        List<String> allArgs = new ArrayList<>( Arrays.asList( "java", "-cp", System.getProperty( "java.class.path" ), BackupTool.class.getName() ) );
        allArgs.addAll( Arrays.asList( args ) );

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

    public static int runBackupToolFromOtherJvmToGetExitCode( String... args )
            throws Exception
    {
        List<String> allArgs = new ArrayList<String>( Arrays.asList( "java", "-cp", System.getProperty( "java.class.path" ), BackupTool.class.getName() ) );
        allArgs.addAll( Arrays.asList( args ) );

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

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public runBackupToolFromOtherJvmToGetExitCode(args String...) : int from class org.neo4j.backup.BackupEmbeddedIT


    public void rebuildCounts()
    {
        NodeLabelsCache cache = new NodeLabelsCache( NumberArrayFactory.AUTO, highLabelId );
        try ( CountsAccessor.Updater countsUpdater = countsTracker.reset() )
        {
            // Count nodes
            superviseDynamicExecution( new NodeStoreProcessorStage( "COUNT NODES", Configuration.DEFAULT, nodes,
                    new NodeCountsProcessor( nodes, cache, highLabelId, countsUpdater ) ) );
            // Count relationships
            superviseDynamicExecution( new RelationshipCountsStage( Configuration.DEFAULT, cache, relationships,
                    highLabelId, highRelationshipTypeId, countsUpdater ) );
        }
        finally
        {
            cache.close();
        }
    }

    public void rebuildCounts()
    {
        NodeLabelsCache cache = new NodeLabelsCache( NumberArrayFactory.AUTO, highLabelId );
        try
        {
            // Count nodes
            superviseDynamicExecution( new NodeStoreProcessorStage( "COUNT NODES", Configuration.DEFAULT, nodes,
                    new NodeCountsProcessor( nodes, cache, highLabelId, countsTracker ) ) );
            // Count relationships
            superviseDynamicExecution( new RelationshipCountsStage( Configuration.DEFAULT, cache, relationships,
                    highLabelId, highRelationshipTypeId, countsTracker ) );
        }
        finally
        {
            cache.close();
        }
    }

Try With Resources try(CountsAccessor.Updater countsUpdater=countsTracker.reset()) in method public rebuildCounts() : void from class org.neo4j.kernel.impl.store.CountsComputer


    public final R acquire()
    {
        Thread thread = Thread.currentThread();
        R resource = current.get( thread );
        if ( resource == null )
        {
            List<R> garbage = null;
            synchronized ( unused )
            {
                for (; ; )
                {
                    resource = unused.poll();
                    if ( resource == null )
                    {
                        break;
                    }
                    if ( isAlive( resource ) )
                    {
                        break;
                    }
                    if ( garbage == null )
                    {
                        garbage = new LinkedList<>();
                    }
                    garbage.add( resource );
                }
            }
            if ( resource == null )
            {
                resource = create();
                monitor.created( resource );
            }
            current.put( thread, resource );
            monitor.acquired( resource );
            if ( garbage != null )
            {
                for ( R dead : garbage )
                {
                    dispose( dead );
                    monitor.disposed( dead );
                }
            }
        }
        currentPeakSize = Math.max( currentPeakSize, current.size() );
        if ( checkStrategy.shouldCheck() )
        {
            targetSize = Math.max( minSize, currentPeakSize );
            monitor.updatedCurrentPeakSize( currentPeakSize );
            currentPeakSize = 0;
            monitor.updatedTargetSize( targetSize );
        }

        return resource;
    }

    public final R acquire()
    {
        Thread thread = Thread.currentThread();
        R resource = current.get( thread );
        if ( resource == null )
        {
            List<R> garbage = null;
            synchronized ( unused )
            {
                for (; ; )
                {
                    resource = unused.poll();
                    if ( resource == null )
                    {
                        break;
                    }
                    if ( isAlive( resource ) )
                    {
                        break;
                    }
                    if ( garbage == null )
                    {
                        garbage = new LinkedList<R>();
                    }
                    garbage.add( resource );
                }
            }
            if ( resource == null )
            {
                resource = create();
                monitor.created( resource );
            }
            current.put( thread, resource );
            monitor.acquired( resource );
            if ( garbage != null )
            {
                for ( R dead : garbage )
                {
                    dispose( dead );
                    monitor.disposed( dead );
                }
            }
        }
        currentPeakSize = Math.max( currentPeakSize, current.size() );
        if ( checkStrategy.shouldCheck() )
        {
            targetSize = Math.max( minSize, currentPeakSize );
            monitor.updatedCurrentPeakSize( currentPeakSize );
            currentPeakSize = 0;
            monitor.updatedTargetSize( targetSize );
        }

        return resource;
    }

Replace Generic With Diamond LinkedList<R> with LinkedList<> in method public acquire() : R from class org.neo4j.com.ResourcePool


    public final void close( boolean force )
    {
        List<R> dead = new LinkedList<>();
        synchronized ( unused )
        {
            dead.addAll( unused );
            unused.clear();
        }
        if ( force )
        {
            dead.addAll( current.values() );
        }
        for ( R resource : dead )
        {
            dispose( resource );
        }
    }

    public final void close( boolean force )
    {
        List<R> dead = new LinkedList<R>();
        synchronized ( unused )
        {
            dead.addAll( unused );
            unused.clear();
        }
        if ( force )
        {
            dead.addAll( current.values() );
        }
        for ( R resource : dead )
        {
            dispose( resource );
        }
    }

Replace Generic With Diamond LinkedList<R> with LinkedList<> in method public close(force boolean) : void from class org.neo4j.com.ResourcePool


    private void commit() throws TransactionFailureException
    {
        boolean success = false;

        try ( CommitEvent commitEvent = transactionEvent.beginCommitEvent() )
        {
            // Trigger transaction "before" hooks
            if ( (hooksState = hooks.beforeCommit( txState, this, storeLayer )) != null && hooksState.failed() )
            {
                throw new TransactionFailureException( Status.Transaction.HookFailed, hooksState.failure(), "" );
            }

            prepareRecordChangesFromTransactionState();

            // Convert changes into commands and commit
            if ( hasChanges() )
            {
                try ( LockGroup lockGroup = new LockGroup() )
                {
                    // Gather up commands from the various sources
                    extractedCommands.clear();
                    recordState.extractCommands( extractedCommands );
                    legacyIndexTransactionState.extractCommands( extractedCommands );
                    counts.extractCommands( extractedCommands );

                    /* Here's the deal: we track a quick-to-access hasChanges in transaction state which is true
                     * if there are any changes imposed by this transaction. Some changes made inside a transaction undo
                     * previously made changes in that same transaction, and so at some point a transaction may have
                     * changes and at another point, after more changes seemingly,
                     * the transaction may not have any changes.
                     * However, to track that "undoing" of the changes is a bit tedious, intrusive and hard to maintain
                     * and get right.... So to really make sure the transaction has changes we re-check by looking if we
                     * have produced any commands to add to the logical log.
                     */
                    if ( !extractedCommands.isEmpty() )
                    {
                        // Finish up the whole transaction representation
                        PhysicalTransactionRepresentation transactionRepresentation =
                                new PhysicalTransactionRepresentation( extractedCommands );
                        TransactionHeaderInformation headerInformation = headerInformationFactory.create();
                        transactionRepresentation.setHeader( headerInformation.getAdditionalHeader(),
                                headerInformation.getMasterId(),
                                headerInformation.getAuthorId(),
                                startTimeMillis, lastTransactionIdWhenStarted, clock.currentTimeMillis(),
                                locks.getLockSessionId() );

                        // Commit the transaction
                        commitProcess.commit( transactionRepresentation, lockGroup, commitEvent );
                    }

                    if ( hasTxStateWithChanges() )
                    {
                        persistenceCache.apply( txState, recordStateForCache );
                    }
                }
            }
            success = true;
        }
        finally
        {
            if ( !success )
            {
                rollback();
            }
            else
            {
                afterCommit();
            }
        }
    }

    private void commit() throws TransactionFailureException
    {
        boolean success = false;

        try
        {
            // Trigger transaction "before" hooks
            if ( (hooksState = hooks.beforeCommit( txState, this, storeLayer )) != null && hooksState.failed() )
            {
                throw new TransactionFailureException( Status.Transaction.HookFailed, hooksState.failure(), "" );
            }

            prepareRecordChangesFromTransactionState();

            // Convert changes into commands and commit
            if ( hasChanges() )
            {
                try ( LockGroup lockGroup = new LockGroup() )
                {
                    // Gather up commands from the various sources
                    extractedCommands.clear();
                    recordState.extractCommands( extractedCommands );
                    legacyIndexTransactionState.extractCommands( extractedCommands );
                    counts.extractCommands( extractedCommands );

                    /* Here's the deal: we track a quick-to-access hasChanges in transaction state which is true
                     * if there are any changes imposed by this transaction. Some changes made inside a transaction undo
                     * previously made changes in that same transaction, and so at some point a transaction may have
                     * changes and at another point, after more changes seemingly,
                     * the transaction may not have any changes.
                     * However, to track that "undoing" of the changes is a bit tedious, intrusive and hard to maintain
                     * and get right.... So to really make sure the transaction has changes we re-check by looking if we
                     * have produced any commands to add to the logical log.
                     */
                    if ( !extractedCommands.isEmpty() )
                    {
                        // Finish up the whole transaction representation
                        PhysicalTransactionRepresentation transactionRepresentation =
                                new PhysicalTransactionRepresentation( extractedCommands );
                        TransactionHeaderInformation headerInformation = headerInformationFactory.create();
                        transactionRepresentation.setHeader( headerInformation.getAdditionalHeader(),
                                headerInformation.getMasterId(),
                                headerInformation.getAuthorId(),
                                startTimeMillis, lastTransactionIdWhenStarted, clock.currentTimeMillis(),
                                locks.getLockSessionId() );

                        // Commit the transaction
                        commitProcess.commit( transactionRepresentation, lockGroup );
                    }

                    if ( hasTxStateWithChanges() )
                    {
                        persistenceCache.apply( txState, recordStateForCache );
                    }
                }
            }
            success = true;
        }
        finally
        {
            if ( !success )
            {
                rollback();
            }
            else
            {
                afterCommit();
            }
        }
    }

Try With Resources try(CommitEvent commitEvent=transactionEvent.beginCommitEvent()) in method private commit() : void from class org.neo4j.kernel.impl.api.KernelTransactionImplementation


    @Override
    public long commit( TransactionRepresentation transaction, LockGroup locks, CommitEvent commitEvent ) throws TransactionFailureException
    {
        // serialise commands to the log
        long transactionId = commitTransaction( transaction, commitEvent );
        commitEvent.setTransactionId( transactionId );

        // apply changes to the store
        try ( StoreApplyEvent storeApplyEvent = commitEvent.beginStoreApply() )
        {
            storeApplier.apply( transaction, locks, transactionId, mode );
        }
        // TODO catch different types of exceptions here, some which are OK
        catch ( Throwable e )
        {
            throw exception( Status.Transaction.CouldNotCommit, e,
                    "Could not apply the transaction to the store after written to log" );
        }
        finally
        {
            transactionIdStore.transactionClosed( transactionId );
        }
        return transactionId;
    }

    @Override
    public long commit( TransactionRepresentation transaction, LockGroup locks ) throws TransactionFailureException
    {
        long transactionId = commitTransaction( transaction );

        // apply changes to the store
        try
        {
            storeApplier.apply( transaction, locks, transactionId, mode );
        }
        // TODO catch different types of exceptions here, some which are OK
        catch ( Throwable e )
        {
            throw exception( Status.Transaction.CouldNotCommit, e,
                    "Could not apply the transaction to the store after written to log" );
        }
        finally
        {
            transactionIdStore.transactionClosed( transactionId );
        }
        return transactionId;
    }

Try With Resources try(StoreApplyEvent storeApplyEvent=commitEvent.beginStoreApply()) in method public commit(transaction TransactionRepresentation, locks LockGroup, commitEvent CommitEvent) : long from class org.neo4j.kernel.impl.api.TransactionRepresentationCommitProcess


    private long commitTransaction( TransactionRepresentation tx, CommitEvent commitEvent ) throws TransactionFailureException
    {
        try ( LogAppendEvent logAppendEvent = commitEvent.beginLogAppend() )
        {
            return logicalTransactionStore.getAppender().append( tx, logAppendEvent );
        }
        catch ( Throwable e )
        {
            throw exception( Status.Transaction.CouldNotWriteToLog, e,
                    "Could not append transaction representation to log" );
        }
    }

    private long commitTransaction( TransactionRepresentation tx ) throws TransactionFailureException
    {
        try
        {
            return logicalTransactionStore.getAppender().append( tx );
        }
        catch ( Throwable e )
        {
            throw exception( Status.Transaction.CouldNotWriteToLog, e,
                    "Could not append transaction representation to log" );
        }
    }

Try With Resources try(LogAppendEvent logAppendEvent=commitEvent.beginLogAppend()) in method private commitTransaction(tx TransactionRepresentation, commitEvent CommitEvent) : long from class org.neo4j.kernel.impl.api.TransactionRepresentationCommitProcess


    private void rebuildCountsStore( long txId )
    {
        try( StandalonePageCache pageCache = createPageCache( fileSystemAbstraction, "build-counts" ) )
        {
            final File storeFileBase = storeFileName( COUNTS_STORE );
            final String storeVersion = buildTypeDescriptorAndVersion( CountsTracker.STORE_DESCRIPTOR );
            CountsTracker.createEmptyCountsStore( pageCache, storeFileBase, storeVersion );

            try ( NodeStore nodeStore = newNodeStore();
                  RelationshipStore relationshipStore = newRelationshipStore();
                  CountsTracker tracker =
                          new CountsTracker( stringLogger, fileSystemAbstraction, pageCache, storeFileBase ) )
            {
                CountsComputer.computeCounts( nodeStore, relationshipStore )
                              .accept( new CountsAccessor.Initializer( tracker ) );
                try
                {
                    tracker.rotate( txId );
                }
                catch ( IOException e )
                {
                    throw new UnderlyingStorageException( "Unable to recreate CountsStore", e );
                }
            }
        }
    }

    private void rebuildCountsStore( long txId )
    {
        final LifeSupport life = new LifeSupport();
        life.start();
        try
        {
            final StandalonePageCache pageCache = createPageCache( fileSystemAbstraction, new Config(), "build-counts" );
            final File storeFileBase = storeFileName( COUNTS_STORE );
            CountsTracker.createEmptyCountsStore( pageCache, storeFileBase,
                    buildTypeDescriptorAndVersion( CountsTracker.STORE_DESCRIPTOR ) );

            try ( NodeStore nodeStore = newNodeStore();
                  RelationshipStore relationshipStore = newRelationshipStore();
                  CountsTracker tracker = new CountsTracker(
                          stringLogger, fileSystemAbstraction, pageCache, storeFileBase ) )
            {
                CountsComputer.computeCounts( nodeStore, relationshipStore ).
                        accept( new CountsAccessor.Initializer( tracker ) );
                try
                {
                    tracker.rotate( txId );
                }
                catch ( IOException e )
                {
                    throw new UnderlyingStorageException( "Unable to recreate CountsStore", e );
                }
            }
        }
        finally
        {
            life.shutdown();
        }
    }

Try With Resources try(StandalonePageCache pageCache=createPageCache(fileSystemAbstraction,"build-counts")) in method private rebuildCountsStore(txId long) : void from class org.neo4j.kernel.impl.store.StoreFactory


        public void setState( SnapshotProvider provider, ObjectInputStreamFactory objectInputStreamFactory )
                throws IOException
        {
            ByteArrayInputStream bin = new ByteArrayInputStream( buf );

            try ( ObjectInputStream oin = objectInputStreamFactory.create( bin ) )
            {
                provider.setState( oin );
            }
            catch ( Throwable e )
            {
                e.printStackTrace();
            }
        }

        public void setState( SnapshotProvider provider, ObjectInputStreamFactory objectInputStreamFactory )
                throws IOException
        {
            ByteArrayInputStream bin = new ByteArrayInputStream( buf );

            ObjectInputStream oin = objectInputStreamFactory.create( bin );
            try
            {
                provider.setState( oin );
            }
            catch ( Throwable e )
            {
                e.printStackTrace();
            }
            finally
            {
                oin.close();
            }
        }

Try With Resources try(ObjectInputStream oin=objectInputStreamFactory.create(bin)) in method public setState(provider SnapshotProvider, objectInputStreamFactory ObjectInputStreamFactory) : void from class org.neo4j.cluster.protocol.snapshot.SnapshotMessage.SnapshotState


    @Test( timeout = 30000 )
    public void writesFlushedFromPageFileMustBeObservableEvenWhenRacingWithEviction() throws IOException
    {
        PageCache cache = getPageCache( fs, 20, pageCachePageSize, PageCacheMonitor.NULL );

        long startPageId = 0;
        long endPageId = 21;
        int iterations = 10000;
        int shortsPerPage = pageCachePageSize / 2;

        try ( PagedFile pagedFile = cache.map( file, pageCachePageSize ) )
        {
            for ( int i = 1; i <= iterations; i++ )
            {
                try ( PageCursor cursor = pagedFile.io( startPageId, PF_EXCLUSIVE_LOCK ) )
                {
                    while ( cursor.getCurrentPageId() < endPageId && cursor.next() )
                    {
                        for ( int j = 0; j < shortsPerPage; j++ )
                        {
                            cursor.putShort( (short) i );
                        }
                    }
                }

                // There are 20 pages in the cache and we've overwritten 20 pages.
                // This means eviction has probably fallen behind and is likely
                // running concurrently right now.
                // Therefor, a flush right now would have a high chance of racing
                // with eviction.
                pagedFile.flush();

                // Race or not, a flush should still put all changes in storage,
                // so we should be able to verify the contents of the file.
                try ( DataInputStream stream = new DataInputStream( fs.openAsInputStream( file ) ) )
                {
                    for ( int j = 0; j < shortsPerPage; j++ )
                    {
                        int value = stream.readShort();
                        assertThat( "short pos = " + j + ", iteration = " + i, value, is( i ) );
                    }
                }
            }
        }
    }

    @Test( timeout = 30000 )
    public void writesFlushedFromPageFileMustBeObservableEvenWhenRacingWithEviction() throws IOException
    {
        PageCache cache = getPageCache( fs, 20, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, pageCachePageSize );

        long startPageId = 0;
        long endPageId = 21;
        int iterations = 10000;
        int shortsPerPage = pageCachePageSize / 2;

        try
        {
            for ( int i = 1; i <= iterations; i++ )
            {
                try ( PageCursor cursor = pagedFile.io( startPageId, PF_EXCLUSIVE_LOCK ) )
                {
                    while ( cursor.getCurrentPageId() < endPageId && cursor.next() )
                    {
                        for ( int j = 0; j < shortsPerPage; j++ )
                        {
                            cursor.putShort( (short) i );
                        }
                    }
                }

                // There are 20 pages in the cache and we've overwritten 20 pages.
                // This means eviction has probably fallen behind and is likely
                // running concurrently right now.
                // Therefor, a flush right now would have a high chance of racing
                // with eviction.
                pagedFile.flush();

                // Race or not, a flush should still put all changes in storage,
                // so we should be able to verify the contents of the file.
                try ( DataInputStream stream = new DataInputStream( fs.openAsInputStream( file ) ) )
                {
                    for ( int j = 0; j < shortsPerPage; j++ )
                    {
                        int value = stream.readShort();
                        assertThat( "short pos = " + j + ", iteration = " + i, value, is( i ) );
                    }
                }
            }
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=cache.map(file,pageCachePageSize)) in method public writesFlushedFromPageFileMustBeObservableEvenWhenRacingWithEviction() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000 )
    public void closingWithoutCallingNextMustLeavePageUnpinnedAndUntouched() throws IOException
    {
        int numberOfRecordsToGenerate = recordsPerFilePage; // one page worth
        generateFileWithRecords( file, numberOfRecordsToGenerate, recordSize );

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = pageCache.map( file, filePageSize ) )
        {
            //noinspection EmptyTryBlock
            try ( PageCursor ignore = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
            {
                // No call to next, so the page should never get pinned in the first place, nor
                // should the page corruption take place.
            }

            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
            {
                // We didn't call next before, so the page and its records should still be fine
                cursor.next();
                verifyRecordsMatchExpected( cursor );
            }
        }
    }

    @Test( timeout = 1000 )
    public void closingWithoutCallingNextMustLeavePageUnpinnedAndUntouched() throws IOException
    {
        int numberOfRecordsToGenerate = recordsPerFilePage; // one page worth
        generateFileWithRecords( file, numberOfRecordsToGenerate, recordSize );

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );

        try
        {
            //noinspection EmptyTryBlock
            try ( PageCursor ignore = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
            {
                // No call to next, so the page should never get pinned in the first place, nor
                // should the page corruption take place.
            }

            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
            {
                // We didn't call next before, so the page and its records should still be fine
                cursor.next();
                verifyRecordsMatchExpected( cursor );
            }
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=pageCache.map(file,filePageSize)) in method public closingWithoutCallingNextMustLeavePageUnpinnedAndUntouched() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void notSpecifyingAnyPfFlagsMustThrow() throws IOException
    {
        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        try ( PagedFile pagedFile = cache.map( file, filePageSize ) )
        {
            pagedFile.io( 0, 0 ); // this must throw
        }
    }

    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void notSpecifyingAnyPfFlagsMustThrow() throws IOException
    {
        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );
        try
        {
            pagedFile.io( 0, 0 ); // this must throw
        }
        finally
        {
            cache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=cache.map(file,filePageSize)) in method public notSpecifyingAnyPfFlagsMustThrow() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void notSpecifyingAnyPfLockFlagsMustThrow() throws IOException
    {
        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        try ( PagedFile pagedFile = cache.map( file, filePageSize ) )
        {
            pagedFile.io( 0, PF_NO_FAULT ); // this must throw
        }
    }

    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void notSpecifyingAnyPfLockFlagsMustThrow() throws IOException
    {
        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );
        try
        {
            pagedFile.io( 0, PF_NO_FAULT ); // this must throw
        }
        finally
        {
            cache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=cache.map(file,filePageSize)) in method public notSpecifyingAnyPfLockFlagsMustThrow() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void specifyingBothSharedAndExclusiveLocksMustThrow() throws IOException
    {
        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        try ( PagedFile pagedFile = cache.map( file, filePageSize ) )
        {
            pagedFile.io( 0, PF_EXCLUSIVE_LOCK | PF_SHARED_LOCK ); // this must throw
        }
    }

    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void specifyingBothSharedAndExclusiveLocksMustThrow() throws IOException
    {
        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );
        try
        {
            pagedFile.io( 0, PF_EXCLUSIVE_LOCK | PF_SHARED_LOCK ); // this must throw
        }
        finally
        {
            cache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=cache.map(file,filePageSize)) in method public specifyingBothSharedAndExclusiveLocksMustThrow() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000 )
    public void lastPageMustBeAccessibleWithNoGrowSpecified() throws IOException
    {
        generateFileWithRecords( file, recordsPerFilePage * 2, recordSize );

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = pageCache.map( file, filePageSize ) )
        {
            try ( PageCursor cursor = pagedFile.io( 0L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursor.next() );
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 0L, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 2L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 2L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 3L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 3L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }
        }
    }

    @Test( timeout = 1000 )
    public void lastPageMustBeAccessibleWithNoGrowSpecified() throws IOException
    {
        generateFileWithRecords( file, recordsPerFilePage * 2, recordSize );

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );

        try
        {
            try ( PageCursor cursor = pagedFile.io( 0L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursor.next() );
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 0L, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 2L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 2L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 3L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 3L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }
        }
        finally
        {
            cache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=pageCache.map(file,filePageSize)) in method public lastPageMustBeAccessibleWithNoGrowSpecified() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000 )
    public void firstPageMustBeAccessibleWithNoGrowSpecifiedIfItIsTheOnlyPage() throws IOException
    {
        generateFileWithRecords( file, recordsPerFilePage, recordSize );

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = cache.map( file, filePageSize ) )
        {
            try ( PageCursor cursor = pagedFile.io( 0L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 0L, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }
        }
    }

    @Test( timeout = 1000 )
    public void firstPageMustBeAccessibleWithNoGrowSpecifiedIfItIsTheOnlyPage() throws IOException
    {
        generateFileWithRecords( file, recordsPerFilePage, recordSize );

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );

        try
        {
            try ( PageCursor cursor = pagedFile.io( 0L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 0L, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=cache.map(file,filePageSize)) in method public firstPageMustBeAccessibleWithNoGrowSpecifiedIfItIsTheOnlyPage() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000 )
    public void firstPageMustBeAccessibleEvenIfTheFileIsNonEmptyButSmallerThanFilePageSize() throws IOException
    {
        generateFileWithRecords( file, 1, recordSize );

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = cache.map( file, filePageSize ) )
        {
            try ( PageCursor cursor = pagedFile.io( 0L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 0L, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }
        }
    }

    @Test( timeout = 1000 )
    public void firstPageMustBeAccessibleEvenIfTheFileIsNonEmptyButSmallerThanFilePageSize() throws IOException
    {
        generateFileWithRecords( file, 1, recordSize );

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );

        try
        {
            try ( PageCursor cursor = pagedFile.io( 0L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 0L, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=cache.map(file,filePageSize)) in method public firstPageMustBeAccessibleEvenIfTheFileIsNonEmptyButSmallerThanFilePageSize() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000 )
    public void firstPageMustNotBeAccessibleIfFileIsEmptyAndNoGrowSpecified() throws IOException
    {
        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = cache.map( file, filePageSize ) )
        {
            try ( PageCursor cursor = pagedFile.io( 0L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 0L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }
        }
    }

    @Test( timeout = 1000 )
    public void firstPageMustNotBeAccessibleIfFileIsEmptyAndNoGrowSpecified() throws IOException
    {
        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );

        try
        {
            try ( PageCursor cursor = pagedFile.io( 0L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 0L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next() );
            }

            try ( PageCursor cursor = pagedFile.io( 1L, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next() );
            }
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=cache.map(file,filePageSize)) in method public firstPageMustNotBeAccessibleIfFileIsEmptyAndNoGrowSpecified() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000 )
    public void nextWithPageIdMustReturnFalseIfPageIdIsBeyondFilePageRangeAndNoGrowSpecified() throws IOException
    {
        generateFileWithRecords( file, recordsPerFilePage * 2, recordSize );

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = pageCache.map( file, filePageSize ) )
        {
            try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next( 2 ) );
                assertTrue( cursor.next( 1 ) );
            }

            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next( 2 ) );
                assertTrue( cursor.next( 1 ) );
            }
        }
    }

    @Test( timeout = 1000 )
    public void nextWithPageIdMustReturnFalseIfPageIdIsBeyondFilePageRangeAndNoGrowSpecified() throws IOException
    {
        generateFileWithRecords( file, recordsPerFilePage * 2, recordSize );

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = cache.map( file, filePageSize );

        try
        {
            try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertFalse( cursor.next( 2 ) );
                assertTrue( cursor.next( 1 ) );
            }

            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
            {
                assertFalse( cursor.next( 2 ) );
                assertTrue( cursor.next( 1 ) );
            }
        }
        finally
        {
            cache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=pageCache.map(file,filePageSize)) in method public nextWithPageIdMustReturnFalseIfPageIdIsBeyondFilePageRangeAndNoGrowSpecified() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void mappingFileSecondTimeWithLesserPageSizeMustThrow() throws Exception
    {
        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        try ( PagedFile ignore = pageCache.map( file, filePageSize ) )
        {
            pageCache.map( file, filePageSize - 1 );
        }
    }

    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void mappingFileSecondTimeWithLesserPageSizeMustThrow() throws Exception
    {
        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        pageCache.map( file, filePageSize );
        try
        {
            pageCache.map( file, filePageSize - 1 );
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile ignore=pageCache.map(file,filePageSize)) in method public mappingFileSecondTimeWithLesserPageSizeMustThrow() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void mappingFileSecondTimeWithGreaterPageSizeMustThrow() throws Exception
    {
        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        try ( PagedFile ignore = pageCache.map( file, filePageSize ) )
        {
            pageCache.map( file, filePageSize + 1 );
        }
    }

    @Test( timeout = 1000, expected = IllegalArgumentException.class )
    public void mappingFileSecondTimeWithGreaterPageSizeMustThrow() throws Exception
    {
        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        pageCache.map( file, filePageSize );
        try
        {
            pageCache.map( file, filePageSize + 1 );
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile ignore=pageCache.map(file,filePageSize)) in method public mappingFileSecondTimeWithGreaterPageSizeMustThrow() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test
    public void lastPageIdOfEmptyFileIsMinusOne() throws IOException
    {
        fs.create( file ).close();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = pageCache.map( file, filePageSize ) )
        {
            assertThat( pagedFile.getLastPageId(), is( -1L ) );
        }
    }

    @Test
    public void lastPageIdOfEmptyFileIsMinusOne() throws IOException
    {
        fs.create( file ).close();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        PagedFile pagedFile = pageCache.map( file, filePageSize );
        try
        {
            assertThat( pagedFile.getLastPageId(), is( -1L ) );
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=pageCache.map(file,filePageSize)) in method public lastPageIdOfEmptyFileIsMinusOne() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test
    public void lastPageIdOfFileWithExactlyTwoPagesWorthOfDataIsOne() throws IOException
    {
        int twoPagesWorthOfRecords = recordsPerFilePage * 2;
        generateFileWithRecords( file, twoPagesWorthOfRecords, recordSize );

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = pageCache.map( file, filePageSize ) )
        {
            assertThat( pagedFile.getLastPageId(), is( 1L ) );
        }
    }

    @Test
    public void lastPageIdOfFileWithExactlyTwoPagesWorthOfDataIsOne() throws IOException
    {
        int twoPagesWorthOfRecords = recordsPerFilePage * 2;
        generateFileWithRecords( file, twoPagesWorthOfRecords, recordSize );

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        PagedFile pagedFile = pageCache.map( file, filePageSize );
        try
        {
            assertThat( pagedFile.getLastPageId(), is( 1L ) );
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=pageCache.map(file,filePageSize)) in method public lastPageIdOfFileWithExactlyTwoPagesWorthOfDataIsOne() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test
    public void lastPageIdOfFileWithExactlyTwoPagesAndOneByteWorthOfDataIsTwo() throws IOException
    {
        int twoPagesWorthOfRecords = recordsPerFilePage * 2;
        generateFileWithRecords( file, twoPagesWorthOfRecords, recordSize );
        OutputStream outputStream = fs.openAsOutputStream( file, true );
        outputStream.write( 'a' );
        outputStream.close();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = pageCache.map( file, filePageSize ) )
        {
            assertThat( pagedFile.getLastPageId(), is( 2L ) );
        }
    }

    @Test
    public void lastPageIdOfFileWithExactlyTwoPagesAndOneByteWorthOfDataIsTwo() throws IOException
    {
        int twoPagesWorthOfRecords = recordsPerFilePage * 2;
        generateFileWithRecords( file, twoPagesWorthOfRecords, recordSize );
        OutputStream outputStream = fs.openAsOutputStream( file, true );
        outputStream.write( 'a' );
        outputStream.close();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        PagedFile pagedFile = pageCache.map( file, filePageSize );
        try
        {
            assertThat( pagedFile.getLastPageId(), is( 2L ) );
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=pageCache.map(file,filePageSize)) in method public lastPageIdOfFileWithExactlyTwoPagesAndOneByteWorthOfDataIsTwo() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test
    public void cursorOffsetMustBeUpdatedReadAndWrite() throws IOException
    {
        fs.create( file ).close();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile pagedFile = pageCache.map( file, filePageSize ) )
        {
            try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
            {
                assertTrue( cursor.next() );
                verifyWriteOffsets( cursor );

                cursor.setOffset( 0 );
                verifyReadOffsets( cursor );
            }

            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                verifyReadOffsets( cursor );
            }
        }
    }

    @Test
    public void cursorOffsetMustBeUpdatedReadAndWrite() throws IOException
    {
        fs.create( file ).close();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        PagedFile pagedFile = pageCache.map( file, filePageSize );

        try
        {
            try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
            {
                assertTrue( cursor.next() );
                verifyWriteOffsets( cursor );

                cursor.setOffset( 0 );
                verifyReadOffsets( cursor );
            }

            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                verifyReadOffsets( cursor );
            }
        }
        finally
        {
            pageCache.unmap( file );
        }
    }

Try With Resources try(PagedFile pagedFile=pageCache.map(file,filePageSize)) in method public cursorOffsetMustBeUpdatedReadAndWrite() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = 1000, expected = IllegalStateException.class )
    public void pageCacheCloseMustThrowIfFilesAreStillMapped() throws IOException
    {
        fs.create( file ).close();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );

        try ( PagedFile ignore = pageCache.map( file, filePageSize ) )
        {
            pageCache.close();
        }
    }

    @Test( timeout = 1000, expected = IllegalStateException.class )
    public void pageCacheCloseMustThrowIfFilesAreStillMapped() throws IOException
    {
        fs.create( file ).close();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheMonitor.NULL );
        pageCache.map( file, filePageSize );

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

Try With Resources try(PagedFile ignore=pageCache.map(file,filePageSize)) in method public pageCacheCloseMustThrowIfFilesAreStillMapped() : void from class org.neo4j.io.pagecache.PageCacheTest


    public static void createEmpty( PageCache pageCache, File storeFile, SortedKeyValueStoreHeader header )
    {
        try
        {
            try ( PagedFile pages = mapCountsStore( pageCache, storeFile ) )
            {
                header.write( pages );
            }
        }
        catch ( IOException e )
        {
            throw new UnderlyingStorageException( e );
        }
    }

    public static void createEmpty( PageCache pageCache, File storeFile, SortedKeyValueStoreHeader header )
    {
        try
        {
            PagedFile pages = mapCountsStore( pageCache, storeFile );
            try
            {
                header.write( pages );
            }
            finally
            {
                pages.flush();
                pageCache.unmap( storeFile );
            }
        }
        catch ( IOException e )
        {
            throw new UnderlyingStorageException( e );
        }
    }

Try With Resources try(PagedFile pages=mapCountsStore(pageCache,storeFile)) in method public createEmpty(pageCache PageCache, storeFile File, header SortedKeyValueStoreHeader) : void from class org.neo4j.kernel.impl.store.counts.CountsStore