    @Test
    public void givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() throws Throwable
    {
        // Given
        ClusterManager clusterManager =
                new ClusterManager( fromXml( getClass().getResource( "/threeinstances.xml" ).toURI() ),
                        TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ),
                        MapUtil.stringMap( HaSettings.ha_server.name(), ":6001-6005",
                                HaSettings.tx_push_factor.name(), "2" ) );
        try
        {
            clusterManager.start();

            clusterManager.getDefaultCluster().await( ClusterManager.allSeesAllAsAvailable() );

            GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
            final GraphDatabaseAPI slave = clusterManager.getDefaultCluster().getAnySlave();

            // When
            final FutureTask<Boolean> result = new FutureTask<>( new Callable<Boolean>()
            {
                @Override
                public Boolean call() throws Exception
                {
                    try ( Transaction tx = slave.beginTx() )
                    {
                        tx.acquireWriteLock( slave.getNodeById( 0 ) );
                        // Fail
                        return false;
                    }
                    catch ( Exception e )
                    {
                        // Ok!
                        return true;
                    }
                }
            } );
            master.getDependencyResolver()
                    .resolveDependency( LifeSupport.class )
                    .addLifecycleListener( new LifecycleListener()
                    {
                        @Override
                        public void notifyStatusChanged( Object instance, LifecycleStatus from, LifecycleStatus to )
                        {
                            if ( instance.getClass().getName().contains( "DatabaseAvailability" ) &&
                                    to == LifecycleStatus.STOPPED )
                            {
                                result.run();
                            }
                        }
                    } );

            master.shutdown();

            // Then
            assertThat( result.get(), equalTo( true ) );
        }
        finally
        {
            clusterManager.stop();
        }
    }

    @Test
    public void givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() throws Throwable
    {
        // Given
        ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/threeinstances.xml" )
                .toURI() ),
                TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ),
                MapUtil.stringMap( HaSettings.ha_server.name(), ":6001-6005",
                        HaSettings.tx_push_factor.name(), "2" ) );
        try
        {
            clusterManager.start();

            clusterManager.getDefaultCluster().await( ClusterManager.allSeesAllAsAvailable() );

            GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
            final GraphDatabaseAPI slave = clusterManager.getDefaultCluster().getAnySlave();

            // When
            final FutureTask<Boolean> result = new FutureTask<Boolean>( new Callable()
            {
                @Override
                public Boolean call() throws Exception
                {
                    try ( Transaction tx = slave.beginTx() )
                    {
                        tx.acquireWriteLock( slave.getNodeById( 0 ) );
                        // Fail
                        return false;
                    }
                    catch ( Exception e )
                    {
                        // Ok!
                        return true;
                    }
                }
            } );
            master.getDependencyResolver().resolveDependency( LifeSupport.class ).addLifecycleListener( new
                                                                                LifecycleListener()
            {
                @Override
                public void notifyStatusChanged( Object instance, LifecycleStatus from, LifecycleStatus to )
                {
                    if ( instance.getClass().getName().contains( "DatabaseAvailability" ) && to == LifecycleStatus
                            .STOPPED )
                    {
                        result.run();
                    }
                }
            } );

            master.shutdown();

            // Then
            Assert.assertThat( result.get(), CoreMatchers.equalTo( true ) );
        }
        finally
        {
            clusterManager.stop();
        }

    }

Replace Generic With Diamond FutureTask<Boolean> with FutureTask<> in method public givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() : void from class org.neo4j.ha.ClusterTransactionTest


    @Test
    public void shouldMoveToToMasterFromPendingOnMasterElectedForItself() throws Throwable
    {
        // Given
        InstanceId me = new InstanceId( 1 );
        HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me, false );
        AvailabilityGuard guard = mock( AvailabilityGuard.class );
        ClusterMembers members = mock( ClusterMembers.class );
        ClusterMemberEvents events = mock( ClusterMemberEvents.class );

        final Set<ClusterMemberListener> listener = new HashSet<>();

        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
                return null;
            }

        } ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );

        Election election = mock( Election.class );
        StringLogger logger = mock( StringLogger.class );
        HighAvailabilityMemberStateMachine toTest =
                new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );
        toTest.init();
        ClusterMemberListener theListener = listener.iterator().next();

        // When
        theListener.coordinatorIsElected( me );

        // Then
        assertThat( listener.size(), equalTo( 1 ) ); // Sanity check.
        assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.TO_MASTER ) );
    }

    @Test
    public void shouldMoveToToMasterFromPendingOnMasterElectedForItself() throws Throwable
    {
        // Given
        InstanceId me = new InstanceId( 1 );
        HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me, false );
        AvailabilityGuard guard = mock( AvailabilityGuard.class );
        ClusterMembers members = mock( ClusterMembers.class );
        ClusterMemberEvents events = mock( ClusterMemberEvents.class );

        final Set<ClusterMemberListener> listener = new HashSet<ClusterMemberListener>();

        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
                return null;
            }

        } ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );

        Election election = mock( Election.class );
        StringLogger logger = mock( StringLogger.class );
        HighAvailabilityMemberStateMachine toTest =
                new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );
        toTest.init();
        ClusterMemberListener theListener = listener.iterator().next();

        // When
        theListener.coordinatorIsElected( me );

        // Then
        assertThat( listener.size(), equalTo( 1 ) ); // Sanity check.
        assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.TO_MASTER ) );
    }

Replace Generic With Diamond HashSet<ClusterMemberListener> with HashSet<> in method public shouldMoveToToMasterFromPendingOnMasterElectedForItself() : void from class org.neo4j.kernel.ha.cluster.HighAvailabilityMemberStateMachineTest


    @Test
    public void shouldRemainToPendingOnMasterElectedForSomeoneElse() throws Throwable
    {
        // Given
        InstanceId me = new InstanceId( 1 );
        HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me, false );
        AvailabilityGuard guard = mock( AvailabilityGuard.class );
        ClusterMembers members = mock( ClusterMembers.class );
        ClusterMemberEvents events = mock( ClusterMemberEvents.class );

        final Set<ClusterMemberListener> listener = new HashSet<>();

        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
                return null;
            }

        } ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );

        Election election = mock( Election.class );
        StringLogger logger = mock( StringLogger.class );
        HighAvailabilityMemberStateMachine toTest =
                new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );
        toTest.init();
        ClusterMemberListener theListener = listener.iterator().next();

        // When
        theListener.coordinatorIsElected( new InstanceId( 2 ) );

        // Then
        assertThat( listener.size(), equalTo( 1 ) ); // Sanity check.
        assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.PENDING ) );
    }

    @Test
    public void shouldRemainToPendingOnMasterElectedForSomeoneElse() throws Throwable
    {
        // Given
        InstanceId me = new InstanceId( 1 );
        HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me, false );
        AvailabilityGuard guard = mock( AvailabilityGuard.class );
        ClusterMembers members = mock( ClusterMembers.class );
        ClusterMemberEvents events = mock( ClusterMemberEvents.class );

        final Set<ClusterMemberListener> listener = new HashSet<ClusterMemberListener>();

        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
                return null;
            }

        } ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );

        Election election = mock( Election.class );
        StringLogger logger = mock( StringLogger.class );
        HighAvailabilityMemberStateMachine toTest =
                new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );
        toTest.init();
        ClusterMemberListener theListener = listener.iterator().next();

        // When
        theListener.coordinatorIsElected( new InstanceId( 2 ) );

        // Then
        assertThat( listener.size(), equalTo( 1 ) ); // Sanity check.
        assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.PENDING ) );
    }

Replace Generic With Diamond HashSet<ClusterMemberListener> with HashSet<> in method public shouldRemainToPendingOnMasterElectedForSomeoneElse() : void from class org.neo4j.kernel.ha.cluster.HighAvailabilityMemberStateMachineTest


    @Test
    public void whenSlaveOnlyIsElectedStayInPending() throws Throwable
    {
        // Given
        InstanceId me = new InstanceId( 1 );
        HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me, true );
        AvailabilityGuard guard = mock( AvailabilityGuard.class );
        ClusterMembers members = mock( ClusterMembers.class );
        ClusterMemberEvents events = mock( ClusterMemberEvents.class );

        final Set<ClusterMemberListener> listener = new HashSet<>();

        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
                return null;
            }

        } ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );

        Election election = mock( Election.class );
        StringLogger logger = mock( StringLogger.class );
        HighAvailabilityMemberStateMachine toTest =
                new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );

        toTest.init();

        ClusterMemberListener theListener = listener.iterator().next();

        // When
        theListener.coordinatorIsElected( me );

        // Then
        assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.PENDING ) );

    }

    @Test
    public void whenSlaveOnlyIsElectedStayInPending() throws Throwable
    {
        // Given
        InstanceId me = new InstanceId( 1 );
        HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me, true );
        AvailabilityGuard guard = mock( AvailabilityGuard.class );
        ClusterMembers members = mock( ClusterMembers.class );
        ClusterMemberEvents events = mock( ClusterMemberEvents.class );

        final Set<ClusterMemberListener> listener = new HashSet<ClusterMemberListener>();

        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
                return null;
            }

        } ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );

        Election election = mock( Election.class );
        StringLogger logger = mock( StringLogger.class );
        HighAvailabilityMemberStateMachine toTest =
                new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );

        toTest.init();

        ClusterMemberListener theListener = listener.iterator().next();

        // When
        theListener.coordinatorIsElected( me );

        // Then
        assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.PENDING ) );

    }

Replace Generic With Diamond HashSet<ClusterMemberListener> with HashSet<> in method public whenSlaveOnlyIsElectedStayInPending() : void from class org.neo4j.kernel.ha.cluster.HighAvailabilityMemberStateMachineTest


    public NeoStoreUtil( File storeDir, FileSystemAbstraction fs )
    {
        try ( StoreChannel channel = fs.open( neoStoreFile( storeDir ), "r" ) )
        {
            int recordsToRead = 6;
            int bytesToRead = recordsToRead * NeoStore.RECORD_SIZE;
            ByteBuffer buf = ByteBuffer.allocate( bytesToRead );
            int bytesRead = channel.read( buf );
            if ( bytesRead != bytesToRead )
            {
                throw new RuntimeException( "Unable to read neo store header information, " +
                        "read: " + bytesRead + "B, expected " + bytesToRead + "B");
            }
            buf.flip();
            creationTime = nextRecord( buf );
            randomId = nextRecord( buf );
            logVersion = nextRecord( buf );
            txId = nextRecord( buf );
            storeVersion = nextRecord( buf );
            firstGraphProp = nextRecord( buf );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

    public NeoStoreUtil( File storeDir, FileSystemAbstraction fs )
    {
        StoreChannel channel = null;
        try
        {
            channel = fs.open( neoStoreFile( storeDir ), "r" );
            int recordsToRead = 6;
            ByteBuffer buf = ByteBuffer.allocate( recordsToRead*NeoStore.RECORD_SIZE );
            if ( channel.read( buf ) != recordsToRead*NeoStore.RECORD_SIZE )
            {
                throw new RuntimeException( "Unable to read neo store header information" );
            }
            buf.flip();
            creationTime = nextRecord( buf );
            randomId = nextRecord( buf );
            logVersion = nextRecord( buf );
            txId = nextRecord( buf );
            storeVersion = nextRecord( buf );
            firstGraphProp = nextRecord( buf );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
        finally
        {
            if ( channel != null )
            {
                try
                {
                    channel.close();
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        }
    }

Try With Resources try(StoreChannel channel=fs.open(neoStoreFile(storeDir),"r")) in method public NeoStoreUtil(storeDir File, fs FileSystemAbstraction) from class org.neo4j.kernel.impl.nioneo.store.NeoStoreUtil


    public <PAYLOAD> Response<PAYLOAD> deserializeResponse(BlockingReadHandler<ChannelBuffer> reader, ByteBuffer input, long timeout,
                                                           Deserializer<PAYLOAD> payloadDeserializer,
                                                           ResourceReleaser channelReleaser) throws IOException
    {
        DechunkingChannelBuffer dechunkingBuffer = new DechunkingChannelBuffer( reader, timeout,
                internalProtocolVersion, applicationProtocolVersion );

        PAYLOAD response = payloadDeserializer.read( dechunkingBuffer, input );
        StoreId storeId = readStoreId( dechunkingBuffer, input );
        TransactionStream txStreams = readTransactionStreams( dechunkingBuffer );
        return new Response<>( response, storeId, txStreams, channelReleaser );
    }

    public <PAYLOAD> Response<PAYLOAD> deserializeResponse(BlockingReadHandler<ChannelBuffer> reader, ByteBuffer input, long timeout,
                                                           Deserializer<PAYLOAD> payloadDeserializer,
                                                           ResourceReleaser channelReleaser) throws IOException
    {
        DechunkingChannelBuffer dechunkingBuffer = new DechunkingChannelBuffer( reader, timeout,
                internalProtocolVersion, applicationProtocolVersion );

        PAYLOAD response = payloadDeserializer.read( dechunkingBuffer, input );
        StoreId storeId = readStoreId( dechunkingBuffer, input );
        TransactionStream txStreams = readTransactionStreams( dechunkingBuffer );
        return new Response<PAYLOAD>( response, storeId, txStreams, channelReleaser );
    }

Replace Generic With Diamond Response<PAYLOAD> with Response<> in method public deserializeResponse(reader BlockingReadHandler<ChannelBuffer>, input ByteBuffer, timeout long, payloadDeserializer Deserializer<PAYLOAD>, channelReleaser ResourceReleaser) : Response<PAYLOAD> from class org.neo4j.com.Protocol


    public Map<String, String> asMap()
    {
        return new HashMap<>( this.map );
    }

    public Map<String, String> asMap()
    {
        return new HashMap<String, String>( this.map );
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public asMap() : Map<String,String> from class org.neo4j.helpers.Args


    public List<String> orphans()
    {
        return new ArrayList<>( this.orphans );
    }

    public List<String> orphans()
    {
        return new ArrayList<String>( this.orphans );
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public orphans() : List<String> from class org.neo4j.helpers.Args


    public static void verifyFilesHaveSameContent( FileSystemAbstraction fileSystem, File original, File other )
            throws IOException
    {
        final int bufferBatchSize = 32 * 1024;
        File[] files = fileSystem.listFiles( original );
        for ( File originalFile : files )
        {
            File otherFile = new File( other, originalFile.getName() );
            if ( !fileSystem.isDirectory( originalFile ) )
            {
                try ( StoreChannel originalChannel = fileSystem.open( originalFile, "r" );
                      StoreChannel otherChannel = fileSystem.open( otherFile, "r" ) )
                {
                    ByteBuffer buffer = ByteBuffer.allocate( bufferBatchSize );
                    while ( true )
                    {
                        if ( !readAndFlip( originalChannel, buffer, bufferBatchSize ) )
                        {
                            break;
                        }
                        byte[] originalBytes = new byte[buffer.limit()];
                        buffer.get( originalBytes );

                        if ( !readAndFlip( otherChannel, buffer, bufferBatchSize ) )
                        {
                            fail( "Files have different sizes" );
                        }

                        byte[] otherBytes = new byte[buffer.limit()];
                        buffer.get( otherBytes );

                        assertArrayEquals( "Different content in " + originalFile, originalBytes, otherBytes );
                    }
                }
            }
        }
    }

    public static void verifyFilesHaveSameContent( FileSystemAbstraction fileSystem, File original,
            File other ) throws IOException
    {
        for ( File originalFile : fileSystem.listFiles( original ) )
        {
            File otherFile = new File( other, originalFile.getName() );
            if ( !fileSystem.isDirectory( originalFile ) )
            {
                StoreChannel originalChannel = fileSystem.open( originalFile, "r" );
                StoreChannel otherChannel = fileSystem.open( otherFile, "r" );
                try
                {
                    ByteBuffer buffer = ByteBuffer.allocate( 1 );
                    while( true )
                    {
                        if ( !readAndFlip( originalChannel, buffer, 1 ) )
                        {
                            break;
                        }
                        int originalByte = buffer.get();

                        if ( !readAndFlip( otherChannel, buffer, 1 ) )
                        {
                            fail( "Files have different sizes" );
                        }
                        assertEquals( "Different content in " + originalFile.getName(), originalByte, buffer.get() );
                    }
                }
                finally
                {
                    originalChannel.close();
                    otherChannel.close();
                }
            }
        }
    }

Try With Resources try(StoreChannel originalChannel=fileSystem.open(originalFile,"r"); StoreChannel otherChannel=fileSystem.open(otherFile,"r")) in method public verifyFilesHaveSameContent(fileSystem FileSystemAbstraction, original File, other File) : void from class org.neo4j.kernel.impl.storemigration.MigrationTestUtils


    private Iterator<Slave> filter( Iterator<Slave> slaves, final Integer externalAuthorServerId )
    {
        return externalAuthorServerId == null ? slaves : new FilteringIterator<>( slaves, new Predicate<Slave>()
        {
            @Override
            public boolean accept( Slave item )
            {
                return item.getServerId() != externalAuthorServerId;
            }
        } );
    }

    private Iterator<Slave> filter( Iterator<Slave> slaves, final Integer externalAuthorServerId )
    {
        return externalAuthorServerId == null ? slaves : new FilteringIterator<Slave>( slaves, new Predicate<Slave>()
        {
            @Override
            public boolean accept( Slave item )
            {
                return item.getServerId() != externalAuthorServerId.intValue();
            }
        } );
    }

Replace Generic With Diamond FilteringIterator<Slave> with FilteringIterator<> in method private filter(slaves Iterator<Slave>, externalAuthorServerId Integer) : Iterator<Slave> from class org.neo4j.kernel.ha.transaction.MasterTxIdGenerator


    public static long[] readLogHeader( FileSystemAbstraction fileSystem, File file ) throws IOException
    {
        try ( StoreChannel channel = fileSystem.open( file, "r" ) )
        {
            return readLogHeader( ByteBuffer.allocateDirect( 100 * 1000 ), channel, true );
        }
    }

    public static long[] readLogHeader( FileSystemAbstraction fileSystem, File file ) throws IOException
    {
        StoreChannel channel = fileSystem.open( file, "r" );
        try
        {
            return readLogHeader( ByteBuffer.allocateDirect( 100*1000 ), channel, true );
        }
        finally
        {
            channel.close();
        }
    }

Try With Resources try(StoreChannel channel=fileSystem.open(file,"r")) in method public readLogHeader(fileSystem FileSystemAbstraction, file File) : long[] from class org.neo4j.kernel.impl.storemigration.legacystore.v19.LegacyLogIoUtil


    private void assertNoDuplicates( Token[] tokens )
    {
        Set<String> visited = new HashSet<>();
        for ( Token token : tokens )
        {
            assertTrue( visited.add( token.name() ) );
        }
    }

    private void assertNoDuplicates( Token[] tokens )
    {
        Set<String> visited = new HashSet<String>();
        for ( Token token : tokens )
        {
            assertTrue( visited.add( token.name() ) );
        }
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method private assertNoDuplicates(tokens Token[]) : void from class upgrade.StoreMigratorIT


    private Node getNodeWithName( GraphDatabaseService db, String name )
    {
        try ( Transaction tx = db.beginTx() )
        {
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
            {
                if ( name.equals( node.getProperty( "name", null ) ) )
                {
                    tx.success();
                    return node;
                }
            }
        }
        throw new IllegalArgumentException( name + " not found" );
    }

    private Node getNodeWithName( GraphDatabaseService db, String name )
    {
        Transaction tx = db.beginTx();
        try
        {
            for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
            {
                if ( name.equals( node.getProperty( "name", null ) ) )
                {
                    tx.success();
                    return node;
                }
            }
        }
        finally
        {
            tx.finish();
        }
        throw new IllegalArgumentException( name + " not found" );
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private getNodeWithName(db GraphDatabaseService, name String) : Node from class upgrade.StoreMigratorIT


    public static File unzip( Class<?> testClass, String resource ) throws IOException
    {
        File dir = TargetDirectory.forTest( testClass ).makeGraphDbDir();
        try ( InputStream source = testClass.getResourceAsStream( resource ) )
        {
            if ( source == null )
            {
                throw new FileNotFoundException( "Could not find resource '" + resource + "' to unzip" );
            }
            ZipInputStream zipStream = new ZipInputStream( source );
            ZipEntry entry;
            byte[] scratch = new byte[8096];
            while ( (entry = zipStream.getNextEntry()) != null )
            {
                if ( entry.isDirectory() )
                {
                    new File( dir, entry.getName() ).mkdirs();
                }
                else
                {
                    try ( OutputStream file =
                                  new BufferedOutputStream( new FileOutputStream( new File( dir, entry.getName() ) ) ) )
                    {
                        long toCopy = entry.getSize();
                        while ( toCopy > 0 )
                        {
                            int read = zipStream.read( scratch );
                            file.write( scratch, 0, read );
                            toCopy -= read;
                        }
                    }
                }
                zipStream.closeEntry();
            }
        }
        return dir;
    }

    public static File unzip( Class<?> testClass, String resource ) throws IOException
    {
        File dir = TargetDirectory.forTest( testClass ).makeGraphDbDir();
        try ( InputStream source = testClass.getResourceAsStream( resource ) )
        {
            if ( source == null )
            {
                throw new FileNotFoundException( "Could not find resource '" + resource + "' to unzip" );
            }
            ZipInputStream zipStream = new ZipInputStream( source );
            ZipEntry entry = null;
            byte[] scratch = new byte[8096];
            while ( (entry = zipStream.getNextEntry()) != null )
            {
                if ( entry.isDirectory() )
                {
                    new File( dir, entry.getName() ).mkdirs();
                }
                else
                {
                    OutputStream file = new BufferedOutputStream( new FileOutputStream( new File( dir, entry.getName() ) ) );
                    try
                    {
                        long toCopy = entry.getSize();
                        while ( toCopy > 0 )
                        {
                            int read = zipStream.read( scratch );
                            file.write( scratch, 0, read );
                            toCopy -= read;
                        }
                    }
                    finally
                    {
                        file.close();
                    }
                }
                zipStream.closeEntry();
            }
        }
        return dir;
    }

Try With Resources try(OutputStream file=new BufferedOutputStream(new FileOutputStream(new File(dir,entry.getName())))) in method public unzip(testClass Class<?>, resource String) : File from class org.neo4j.kernel.impl.AbstractNeo4jTestCase


    @Test
    public void givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() throws Throwable
    {
        // Given
        ClusterManager clusterManager = new ClusterManager(
                fromXml( getClass().getResource( "/threeinstances.xml" ).toURI() ),
                forTest( getClass() ).cleanDirectory( "testCluster" ),
                stringMap( HaSettings.ha_server.name(), ":6001-6005", HaSettings.tx_push_factor.name(), "2" ) );
        try
        {
            clusterManager.start();

            clusterManager.getDefaultCluster().await( ClusterManager.allSeesAllAsAvailable() );

            GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
            final GraphDatabaseAPI slave = clusterManager.getDefaultCluster().getAnySlave();

            // When
            final FutureTask<Boolean> result = new FutureTask<>( new Callable<Boolean>()
            {
                @Override
                public Boolean call() throws Exception
                {
                    try ( Transaction tx = slave.beginTx() )
                    {
                        tx.acquireWriteLock( slave.getNodeById( 0 ) );
                        // Fail
                        return false;
                    }
                    catch ( Exception e )
                    {
                        // Ok!
                        return true;
                    }
                }
            } );
            master.getDependencyResolver().resolveDependency( LifeSupport.class ).
                    addLifecycleListener( new LifecycleListener()
                    {
                        @Override
                        public void notifyStatusChanged( Object instance, LifecycleStatus from, LifecycleStatus to )
                        {
                            if ( instance.getClass().getName().contains( "DatabaseAvailability" ) && to ==
                                    LifecycleStatus.STOPPED )
                            {
                                result.run();
                            }
                        }
                    } );

            master.shutdown();

            // Then
            assertThat( result.get(), CoreMatchers.equalTo( true ) );
        }
        finally
        {
            clusterManager.stop();
        }

    }


    private Representation getRepresentation( Object r )
    {
        if( r == null )
        {
            return ValueRepresentation.string( null );
        }

        if ( r instanceof Path )
        {
            return new PathRepresentation<>((Path) r );
        }

        if(r instanceof Iterable)
        {
            return handleIterable( (Iterable) r );
        }

        if ( r instanceof Node)
        {
            return new NodeRepresentation( (Node) r );
        }

        if ( r instanceof Relationship)
        {
            return new RelationshipRepresentation( (Relationship) r );
        }

        return REPRESENTATION_DISPATCHER.dispatch( r, "" );
    }

    private Representation getRepresentation( Object r )
    {
        if( r == null )
        {
            return ValueRepresentation.string( null );
        }

        if ( r instanceof Path )
        {
            return new PathRepresentation<Path>((Path) r );
        }

        if(r instanceof Iterable)
        {
            return handleIterable( (Iterable) r );
        }

        if ( r instanceof Node)
        {
            return new NodeRepresentation( (Node) r );
        }

        if ( r instanceof Relationship)
        {
            return new RelationshipRepresentation( (Relationship) r );
        }

        return REPRESENTATION_DISPATCHER.dispatch( r, "" );
    }

Replace Generic With Diamond PathRepresentation<Path> with PathRepresentation<> in method private getRepresentation(r Object) : Representation from class org.neo4j.server.rest.repr.CypherResultRepresentation


    private Representation handleIterable( Iterable data ) {
        final List<Representation> results = new ArrayList<>();
        for ( final Object value : data )
        {
            Representation rep = getRepresentation(value);
            results.add(rep);
        }

        RepresentationType representationType = getType(results);
        return new ListRepresentation( representationType, results );
    }

    private Representation handleIterable( Iterable data ) {
        final List<Representation> results = new ArrayList<Representation>();
        for ( final Object value : data )
        {
            Representation rep = getRepresentation(value);
            results.add(rep);
        }

        RepresentationType representationType = getType(results);
        return new ListRepresentation( representationType, results );
    }

Replace Generic With Diamond ArrayList<Representation> with ArrayList<> in method private handleIterable(data Iterable) : Representation from class org.neo4j.server.rest.repr.CypherResultRepresentation


        public static void main( String[] args )
        {
            GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( args[0] );
            try ( Transaction tx = db.beginTx() )
            {
                Index<Node> index = db.index().forNodes( "index" );
                index.add( db.createNode(), "key", "value" );
                index.delete();
                tx.success();
            }

            db.shutdown();
            System.exit( 0 );
        }

    public static void main( String[] args )
    {
        GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( args[0] );
        Transaction tx = db.beginTx();
        try
        {
            Index<Node> index = db.index().forNodes( "index" );
            index.add( db.createNode(), "key", "value" );
            index.delete();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
        System.exit( 0 );
    }

Try With Resources try(Transaction tx=db.beginTx()) in method public main(args String[]) : void from class org.neo4j.index.impl.lucene.RecoveryTest.AddDeleteQuit


    @Test
    public void testRecovery() throws Exception
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            Node node = graphDb.createNode();
            Node otherNode = graphDb.createNode();
            Relationship rel = node.createRelationshipTo( otherNode, withName( "recovery" ) );
            graphDb.index().forNodes( "node-index" ).add( node, "key1", "string value" );
            graphDb.index().forNodes( "node-index" ).add( node, "key2", 12345 );
            graphDb.index().forRelationships( "rel-index" ).add( rel, "key1", "string value" );
            graphDb.index().forRelationships( "rel-index" ).add( rel, "key2", 12345 );
            tx.success();
        }

        forceRecover();
    }

    @Test
    public void testRecovery() throws Exception
    {
        GraphDatabaseService graphDb = newGraphDbService();
        Transaction transaction = graphDb.beginTx();
        try
        {
            Node node = graphDb.createNode();
            Node otherNode = graphDb.createNode();
            Relationship rel = node.createRelationshipTo( otherNode, withName( "recovery" ) );
            graphDb.index().forNodes( "node-index" ).add( node, "key1", "string value" );
            graphDb.index().forNodes( "node-index" ).add( node, "key2", 12345 );
            graphDb.index().forRelationships( "rel-index" ).add( rel, "key1", "string value" );
            graphDb.index().forRelationships( "rel-index" ).add( rel, "key2", 12345 );
            transaction.success();
        }
        finally
        {
            transaction.finish();
            graphDb.shutdown();
        }

        // Start up and let it recover
        new GraphDatabaseFactory().newEmbeddedDatabase( getDbPath().getPath() ).shutdown();
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public testRecovery() : void from class org.neo4j.index.impl.lucene.RecoveryTest


    private void deleteNode( long node )
    {

        try ( Transaction tx = db.beginTx() )
        {
            db.getNodeById( node ).delete();
            tx.success();
        }
    }

    private void deleteNode( long node )
    {
        Transaction tx = db.beginTx();
        try
        {
            db.getNodeById( node ).delete();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private deleteNode(node long) : void from class org.neo4j.kernel.api.impl.index.LuceneIndexRecoveryIT


    @Test
    public void shouldNotAddTwiceDuringRecoveryIfCrashedDuringPopulation() throws Exception
    {
        // Given
        startDb( createAlwaysInitiallyPopulatingLuceneIndexFactory() );

        IndexDefinition indexDefinition = createIndex( myLabel );
        waitForIndex( indexDefinition );

        long nodeId = createNode( myLabel, 12 );
        assertEquals( 1, doIndexLookup( myLabel, 12 ).size() );

        // And Given
        killDb();

        // When
        startDb( createAlwaysInitiallyPopulatingLuceneIndexFactory() );

        try ( Transaction tx = db.beginTx() )
        {
            IndexDefinition index = db.schema().getIndexes().iterator().next();
            waitForIndex( index );

            // Then
            assertEquals( 12, db.getNodeById( nodeId ).getProperty( NUM_BANANAS_KEY ) );
            assertEquals( 1, doIndexLookup( myLabel, 12 ).size() );
        }
    }

    @Test
    public void shouldNotAddTwiceDuringRecoveryIfCrashedDuringPopulation() throws Exception
    {
        // Given
        startDb( createAlwaysInitiallyPopulatingLuceneIndexFactory() );
        Label myLabel = label( "MyLabel" );

        createIndex( myLabel );
        long nodeId = createNode( myLabel, 12 );
        assertEquals( 1, doIndexLookup( myLabel, 12 ).size() );

        // And Given
        killDb();

        // When
        startDb( createAlwaysInitiallyPopulatingLuceneIndexFactory() );

        Transaction transaction = db.beginTx();
        try
        {
            IndexDefinition indexDefinition = db.schema().getIndexes().iterator().next();
            db.schema().awaitIndexOnline( indexDefinition, 10l, TimeUnit.SECONDS );

            // Then
            assertEquals( 12, db.getNodeById( nodeId ).getProperty( NUM_BANANAS_KEY ) );
            assertEquals( 1, doIndexLookup( myLabel, 12 ).size() );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method public shouldNotAddTwiceDuringRecoveryIfCrashedDuringPopulation() : void from class org.neo4j.kernel.api.impl.index.LuceneIndexRecoveryIT


    private long createNode( Label label, int number ) throws PropertyKeyNotFoundException, LabelNotFoundKernelException
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode( label );
            node.setProperty( NUM_BANANAS_KEY, number );
            tx.success();
            return node.getId();
        }
    }

    private long createNode( Label label, int number )
           throws PropertyKeyNotFoundException, LabelNotFoundKernelException
    {
       Transaction tx = db.beginTx();
       try
       {
           Node node = db.createNode( label );
           node.setProperty( NUM_BANANAS_KEY, number );
           tx.success();
           return node.getId();
       }
       finally
       {
           tx.finish();
       }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createNode(label Label, number int) : long from class org.neo4j.kernel.api.impl.index.LuceneIndexRecoveryIT


    private void updateNode( long nodeId, int value )
    {

        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.getNodeById( nodeId );
            node.setProperty( NUM_BANANAS_KEY, value );
            tx.success();
        }
    }

    private void updateNode( long nodeId, int value )
    {
        Transaction tx = db.beginTx();
        try
        {
            Node node = db.getNodeById( nodeId );
            node.setProperty( NUM_BANANAS_KEY, value );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private updateNode(nodeId long, value int) : void from class org.neo4j.kernel.api.impl.index.LuceneIndexRecoveryIT


                    @Override
                    public void run()
                    {
                        try ( Transaction tx = db.beginTx() )
                        {
                            latch.await();
                            Index<Node> index = db.index().forNodes( "index" + r );
                            Node node = db.createNode();
                            index.add( node, "name", "Name" );
                            tx.success();
                        }
                        catch ( InterruptedException e )
                        {
                            Thread.interrupted();
                        }
                    }

                    @Override
                    public void run()
                    {
                        Transaction tx = db.beginTx();
                        try
                        {
                            latch.await();
                            Index<Node> index = db.index().forNodes( "index" + r );
                            Node node = db.createNode();
                            index.add( node, "name", "Name" );
                            tx.success();
                        }
                        catch ( InterruptedException e )
                        {
                            Thread.interrupted();
                        }
                        finally
                        {
                            tx.finish();
                        }
                    }

Try With Resources try(Transaction tx=db.beginTx()) in method public run() : void from class org.neo4j.index.impl.lucene.IndexCreationTest.indexCreationConfigRaceCondition.submit.new Runnable


    private Map<String, Object> generate( List<PropertySpec> properties )
    {
        Map<String, Object> result = new HashMap<>();
        for ( PropertySpec property : properties )
        {
            result.putAll( property.generate() );
        }
        return result;
    }

    private Map<String, Object> generate( List<PropertySpec> properties )
    {
        Map<String, Object> result = new HashMap<String, Object>();
        for ( PropertySpec property : properties )
        {
            result.putAll( property.generate() );
        }
        return result;
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method private generate(properties List<PropertySpec>) : Map<String,Object> from class org.neo4j.perftest.enterprise.generator.DataGenerator


    @Override
    public Continuation execute( AppCommandParser parser, Session session,
        Output out ) throws Exception
    {
        try (Transaction tx = getServer().getDb().beginTx())
        {
            getServer().registerTopLevelTransactionInProgress( session.getId() );
            Continuation result = this.exec( parser, session, out );
            tx.success();
            return result;
        }
    }

    @Override
    public Continuation execute( AppCommandParser parser, Session session,
        Output out ) throws Exception
    {
        Transaction tx = getServer().getDb().beginTx();
        try
        {
            getServer().registerTopLevelTransactionInProgress( session.getId() );
            Continuation result = this.exec( parser, session, out );
            tx.success();
            return result;
        }
        finally
        {
            tx.close();
        }
    }

Try With Resources try(Transaction tx=getServer().getDb().beginTx()) in method public execute(parser AppCommandParser, session Session, out Output) : Continuation from class org.neo4j.shell.kernel.apps.TransactionProvidingApp


    public void grabPrompt()
    {
        init();
        Runnable ctrlcAction = getTerminateAction();
        while ( !end )
        {
            String command = readLine( getPrompt() );
            try ( Closeable ignored = signalHandler.install( ctrlcAction ) )
            {
                evaluate( command );
            }
            catch ( Exception e )
            {
                printStackTrace( e );
            }
        }
        this.shutdown();
    }

    public void grabPrompt()
    {
        init();
        while ( !end )
        {
            try
            {
                evaluate( readLine( getPrompt() ) );
            }
            catch ( Exception e )
            {
                if ( this.shouldPrintStackTraces() )
                {
                    e.printStackTrace();
                }
                else
                {
                    this.console.format( getShortExceptionMessage( e ) + "\n" );
                }
            }
        }
        this.shutdown();
    }

Try With Resources try(Closeable ignored=signalHandler.install(ctrlcAction)) in method public grabPrompt() : void from class org.neo4j.shell.impl.AbstractClient


        public NodeStage( Iterator<InputNode> input, BatchingNeoStore neoStore )
        {
            super( logging, "Nodes", config );
            input( new IteratorBatcherStep<>( control(), "INPUT", config.batchSize(), input ) );

            NodeStore nodeStore = neoStore.getNodeStore();
            PropertyStore propertyStore = neoStore.getPropertyStore();
            add( new NodeEncoderStep( control(), "ENCODER", config.workAheadSize(), 1,
                    neoStore.getPropertyKeyRepository(), neoStore.getLabelRepository(), nodeStore, propertyStore ) );
            add( new EntityStoreUpdaterStep<>( control(), "WRITER", nodeStore, propertyStore, writeMonitor ) );
        }

        public NodeStage( Iterator<InputNode> input, BatchingNeoStore neoStore )
        {
            super( logging, "Nodes", config );
            input( new ProducerStep<InputNode>( control(), "INPUT", config.batchSize() ), input );

            NodeStore nodeStore = neoStore.getNodeStore();
            PropertyStore propertyStore = neoStore.getPropertyStore();
            add( new NodeEncoderStep( control(), "ENCODER", config.workAheadSize(), 1,
                    neoStore.getPropertyKeyRepository(), neoStore.getLabelRepository(), nodeStore, propertyStore ) );
            add( new EntityStoreUpdaterStep<>( control(), "WRITER", nodeStore, propertyStore, writeMonitor ) );
        }

Replace Generic With Diamond ProducerStep<InputNode> with IteratorBatcherStep<> in method public NodeStage(input Iterator<InputNode>, neoStore BatchingNeoStore) from class org.neo4j.unsafe.impl.batchimport.ParallellBatchImporter.NodeStage


        public CalculateDenseNodesStage( Iterator<InputRelationship> input,
                BatchingNeoStore neoStore, NodeRelationshipLink nodeRelationshipLink )
        {
            super( logging, "Calculate dense nodes", config );
            input( new IteratorBatcherStep<>( control(), "INPUT", config.batchSize(), input ) );

            add( new CalculateDenseNodesStep( control(), config.workAheadSize(), nodeRelationshipLink ) );
        }

        public CalculateDenseNodesStage( Iterator<InputRelationship> input,
                BatchingNeoStore neoStore, NodeRelationshipLink nodeRelationshipLink )
        {
            super( logging, "Calculate dense nodes", config );
            input( new ProducerStep<InputRelationship>( control(), "INPUT", config.batchSize() ), input );

            add( new CalculateDenseNodesStep( control(), config.workAheadSize(), nodeRelationshipLink ) );
        }

Replace Generic With Diamond ProducerStep<InputRelationship> with IteratorBatcherStep<> in method public CalculateDenseNodesStage(input Iterator<InputRelationship>, neoStore BatchingNeoStore, nodeRelationshipLink NodeRelationshipLink) from class org.neo4j.unsafe.impl.batchimport.ParallellBatchImporter.CalculateDenseNodesStage


        public RelationshipStage( Iterator<InputRelationship> input, BatchingNeoStore neoStore,
                NodeRelationshipLink nodeRelationshipLink )
        {
            super( logging, "Relationships", config );
            input( new IteratorBatcherStep<>( control(), "INPUT", config.batchSize(), input ) );

            RelationshipStore relationshipStore = neoStore.getRelationshipStore();
            PropertyStore propertyStore = neoStore.getPropertyStore();
            add( new RelationshipEncoderStep( control(), "ENCODER", config.workAheadSize(), 1,
                    neoStore.getPropertyKeyRepository(), neoStore.getRelationshipTypeRepository(),
                    relationshipStore, propertyStore, nodeRelationshipLink ) );
            add( new EntityStoreUpdaterStep<>( control(), "WRITER", relationshipStore, propertyStore, writeMonitor ) );
        }

        public RelationshipStage( Iterator<InputRelationship> input, BatchingNeoStore neoStore,
                NodeRelationshipLink nodeRelationshipLink )
        {
            super( logging, "Relationships", config );
            input( new ProducerStep<InputRelationship>( control(), "INPUT", config.batchSize() ), input );

            RelationshipStore relationshipStore = neoStore.getRelationshipStore();
            PropertyStore propertyStore = neoStore.getPropertyStore();
            add( new RelationshipEncoderStep( control(), "ENCODER", config.workAheadSize(), 1,
                    neoStore.getPropertyKeyRepository(), neoStore.getRelationshipTypeRepository(),
                    relationshipStore, propertyStore, nodeRelationshipLink ) );
            add( new EntityStoreUpdaterStep<>( control(), "WRITER", relationshipStore, propertyStore, writeMonitor ) );
        }

Replace Generic With Diamond ProducerStep<InputRelationship> with IteratorBatcherStep<> in method public RelationshipStage(input Iterator<InputRelationship>, neoStore BatchingNeoStore, nodeRelationshipLink NodeRelationshipLink) from class org.neo4j.unsafe.impl.batchimport.ParallellBatchImporter.RelationshipStage


    @Test
    public void shouldTranslateTheLastTransactionLog() throws Exception
    {
        // GIVEN
        // A store that has a couple of transaction logs
        File unzippedStore = Unzip.unzip( LegacyStore.class, "legacy-store-with-transaction-logs.zip" );
        File legacyStoreDir = new File( unzippedStore, "legacystore" );
        LegacyStore legacyStore = new LegacyStore( fs, new File( legacyStoreDir, NeoStore.DEFAULT_NAME ) );
        NeoStore neoStore = storeFactory.createNeoStore( storeFileName );

        // WHEN
        new StoreMigrator( monitor ).migrate( legacyStore, neoStore );
        legacyStore.close();

        // THEN
        // We verify that we have a transaction log with two transactions in it, and it exposes
        // the correction transaction version, so that it can be used for incremental backup,
        // and for when an instance joins a cluster in HA and needs to verify that it is up to
        // date with the leader instance.
        // The store we are upgrading has two transaction logs, with two transactions in each.
        // So we should be able to enquire a migrated database about transactions 2 and 3.
        GraphDatabaseFactory factory = new GraphDatabaseFactory();
        GraphDatabaseAPI db = (GraphDatabaseAPI) factory.newEmbeddedDatabase( storeDir );
        try
        {
            DependencyResolver resolver = db.getDependencyResolver();
            XaDataSourceManager xaDataSourceManager = resolver.resolveDependency( XaDataSourceManager.class );
            NeoStoreXaDataSource neoStoreDataSource = xaDataSourceManager.getNeoStoreDataSource();
            XaContainer xaContainer = neoStoreDataSource.getXaContainer();
            XaLogicalLog logicalLog = xaContainer.getLogicalLog();
            // The dataset has been specifically constructed such that these two transactions are
            // contained in the last transaction log:
            try (LogExtractor logExtractor = logicalLog.getLogExtractor( 5, 6 ))
            {
                InMemoryLogBuffer buf = new InMemoryLogBuffer();

                // The first transaction must have the correct checksum
                assertThat( logExtractor.extractNext( buf ), is( 5L ) );
                assertThat( logExtractor.getLastTxChecksum(), is( -161474256273L ) );

                // The second transaction must have the correct checksum
                // As it happens, our checksum generation is woefully bad, so these two transactions
                // end up with the same checksum. Well... all we care about here is that we somehow
                // compute the same number as we did in the previous version. Not cool, but it's a
                // fight for another day.
                assertThat( logExtractor.extractNext( buf ), is( 6L ) );
                assertThat( logExtractor.getLastTxChecksum(), is( -161474256273L ) );

                // And then we reach the end of the file
                assertThat( logExtractor.extractNext( buf ), is( -1L ) );

                logExtractor.close();
            }
        }
        finally
        {
            db.shutdown();
        }
    }

    @Test
    public void shouldTranslateTheLastTransactionLog() throws Exception
    {
        // GIVEN
        // A store that has a couple of transaction logs
        File unzippedStore = Unzip.unzip( LegacyStore.class, "legacy-store-with-transaction-logs.zip" );
        File legacyStoreDir = new File( unzippedStore, "legacystore" );
        LegacyStore legacyStore = new LegacyStore( fs, new File( legacyStoreDir, NeoStore.DEFAULT_NAME ) );
        NeoStore neoStore = storeFactory.createNeoStore( storeFileName );

        // WHEN
        new StoreMigrator( monitor ).migrate( legacyStore, neoStore );
        legacyStore.close();

        // THEN
        // We verify that we have a transaction log with two transactions in it, and it exposes
        // the correction transaction version, so that it can be used for incremental backup,
        // and for when an instance joins a cluster in HA and needs to verify that it is up to
        // date with the leader instance.
        // The store we are upgrading has two transaction logs, with two transactions in each.
        // So we should be able to enquire a migrated database about transactions 2 and 3.
        GraphDatabaseFactory factory = new GraphDatabaseFactory();
        GraphDatabaseAPI db = (GraphDatabaseAPI) factory.newEmbeddedDatabase( storeDir );
        try
        {
            DependencyResolver resolver = db.getDependencyResolver();
            XaDataSourceManager xaDataSourceManager = resolver.resolveDependency( XaDataSourceManager.class );
            NeoStoreXaDataSource neoStoreDataSource = xaDataSourceManager.getNeoStoreDataSource();
            XaContainer xaContainer = neoStoreDataSource.getXaContainer();
            XaLogicalLog logicalLog = xaContainer.getLogicalLog();
            // The dataset has been specifically constructed such that these two transactions are
            // contained in the last transaction log:
            LogExtractor logExtractor = logicalLog.getLogExtractor( 5, 6 );
            InMemoryLogBuffer buf = new InMemoryLogBuffer();

            // The first transaction must have the correct checksum
            assertThat( logExtractor.extractNext( buf ), is( 5L ) );
            assertThat( logExtractor.getLastTxChecksum(), is( -161474256273L ) );

            // The second transaction must have the correct checksum
            // As it happens, our checksum generation is woefully bad, so these two transactions
            // end up with the same checksum. Well... all we care about here is that we somehow
            // compute the same number as we did in the previous version. Not cool, but it's a
            // fight for another day.
            assertThat( logExtractor.extractNext( buf ), is( 6L ) );
            assertThat( logExtractor.getLastTxChecksum(), is( -161474256273L ) );

            // And then we reach the end of the file
            assertThat( logExtractor.extractNext( buf ), is( -1L ) );
        }
        finally
        {
            db.shutdown();
        }
    }

Try With Resources try(LogExtractor logExtractor=logicalLog.getLogExtractor(5,6)) in method public shouldTranslateTheLastTransactionLog() : void from class org.neo4j.kernel.impl.storemigration.StoreMigratorIT


    private void migrateToIsolatedDirectory( File storageFileName, File upgradeDirectory )
    {
        if (upgradeDirectory.exists()) {
            try
            {
                fileSystem.deleteRecursively( upgradeDirectory );
            }
            catch ( IOException e )
            {
                throw new UnableToUpgradeException( e );
            }
        }
        fileSystem.mkdir( upgradeDirectory );

        File upgradeFileName = new File( upgradeDirectory, NeoStore.DEFAULT_NAME );
        Map<String, String> upgradeConfig = new HashMap<>( originalConfig.getParams() );
        upgradeConfig.put( "neo_store", upgradeFileName.getPath() );

        Config upgradeConfiguration = new Config( upgradeConfig );

        NeoStore neoStore = new StoreFactory( upgradeConfiguration, idGeneratorFactory, new DefaultWindowPoolFactory(),
                fileSystem, StringLogger.DEV_NULL, null ).createNeoStore( upgradeFileName );
        try
        {
            storeMigrator.migrate( new LegacyStore( fileSystem, storageFileName ),
                    neoStore );
        }
        catch ( IOException e )
        {
            throw new UnableToUpgradeException( e );
        }
        catch ( Exception e )
        {
            throw Exceptions.launderedException( e );
        }
        finally
        {
            neoStore.close();
        }
    }

    private void migrateToIsolatedDirectory( File storageFileName, File upgradeDirectory )
    {
        if (upgradeDirectory.exists()) {
            try
            {
                fileSystem.deleteRecursively( upgradeDirectory );
            }
            catch ( IOException e )
            {
                throw new UnableToUpgradeException( e );
            }
        }
        fileSystem.mkdir( upgradeDirectory );

        File upgradeFileName = new File( upgradeDirectory, NeoStore.DEFAULT_NAME );
        Map<String, String> upgradeConfig = new HashMap<String, String>( originalConfig.getParams() );
        upgradeConfig.put( "neo_store", upgradeFileName.getPath() );

        Config upgradeConfiguration = new Config( upgradeConfig );

        NeoStore neoStore = new StoreFactory( upgradeConfiguration, idGeneratorFactory, new DefaultWindowPoolFactory(),
                fileSystem, StringLogger.DEV_NULL, null ).createNeoStore( upgradeFileName );
        try
        {
            storeMigrator.migrate( new LegacyStore( fileSystem, storageFileName ),
                    neoStore );
        }
        catch ( IOException e )
        {
            throw new UnableToUpgradeException( e );
        }
        catch ( Exception e )
        {
            throw Exceptions.launderedException( e );
        }
        finally
        {
            neoStore.close();
        }
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method private migrateToIsolatedDirectory(storageFileName File, upgradeDirectory File) : void from class org.neo4j.kernel.impl.storemigration.StoreUpgrader


    public static <T> Response<T> empty()
    {
        return new Response<>( null, new StoreId( -1, -1 ), TransactionStream.EMPTY, ResourceReleaser.NO_OP );
    }

    public static <T> Response<T> empty()
    {
        return new Response<T>( null, new StoreId( -1, -1 ), null, ResourceReleaser.NO_OP );
    }

Replace Generic With Diamond Response<T> with Response<> in method public empty() : Response<T> from class org.neo4j.com.Response


            @Override
            public void write( ChannelBuffer buffer ) throws IOException
            {
                try ( BlockLogBuffer writer = new BlockLogBuffer( buffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ) )
                {
                    writer.write( data );
                }
            }

            @Override
            public void write( ChannelBuffer buffer ) throws IOException
            {
                BlockLogBuffer writer = new BlockLogBuffer( buffer, new Monitors().newMonitor( ByteCounterMonitor.class ) );
                try
                {
                    writer.write( data );
                }
                finally
                {
                    writer.done();
                }
            }

Try With Resources try(BlockLogBuffer writer=new BlockLogBuffer(buffer,new Monitors().newMonitor(ByteCounterMonitor.class))) in method public write(buffer ChannelBuffer) : void from class org.neo4j.com.MadeUpClient.sendDataStream.sendRequest.new Serializer


    @Override
    public void write( ReadableByteChannel data )
    {
        try ( BlockLogBuffer blockBuffer = new BlockLogBuffer( target, new Monitors().newMonitor( ByteCounterMonitor.class ) ) )
        {
            blockBuffer.write( data );
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

    @Override
    public void write( ReadableByteChannel data )
    {
        BlockLogBuffer blockBuffer = new BlockLogBuffer( target, new Monitors().newMonitor( ByteCounterMonitor.class ) );
        try
        {
            blockBuffer.write( data );
            blockBuffer.done();
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

Try With Resources try(BlockLogBuffer blockBuffer=new BlockLogBuffer(target,new Monitors().newMonitor(ByteCounterMonitor.class))) in method public write(data ReadableByteChannel) : void from class org.neo4j.com.ToChannelBufferWriter


    private DbRepresentation addMoreData( File path )
    {
        GraphDatabaseService db = startGraphDatabase( path, false );
        DbRepresentation representation;
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            node.setProperty( "backup", "Is great" );
            db.createNode().createRelationshipTo( node,
                    DynamicRelationshipType.withName( "LOVES" ) );
            tx.success();
        }
        finally
        {
            representation = DbRepresentation.of( db );
            db.shutdown();
        }
        return representation;
    }

    private DbRepresentation addMoreData( File path )
    {
        GraphDatabaseService db = startGraphDatabase( path, false );
        try
        {
            Transaction tx = db.beginTx();
            Node node = db.createNode();
            node.setProperty( "backup", "Is great" );
            db.createNode().createRelationshipTo( node,
                    DynamicRelationshipType.withName( "LOVES" ) );
            tx.success();
            tx.finish();
            return DbRepresentation.of( db );
        }
        finally
        {
            db.shutdown();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private addMoreData(path File) : DbRepresentation from class org.neo4j.backup.TestBackup


    @Test
    public void backupIndexWithNoCommits() throws Exception
    {
        GraphDatabaseService db = null;
        try
        {
            db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( serverPath.getPath() ).
                setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ).
                newGraphDatabase();

            try ( Transaction transaction = db.beginTx() )
            {
                db.index().forNodes( "created-no-commits" );
                transaction.success();
            }

            OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
            backup.full( backupPath.getPath() );
            assertTrue( "Should be consistent", backup.isConsistent() );
            assertTrue( backup.isConsistent() );
        }
        finally
        {
            if ( db != null )
            {
                db.shutdown();
            }
        }
    }

    @Test
    public void backupIndexWithNoCommits() throws Exception
    {
        GraphDatabaseService db = null;
        try
        {
            db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( serverPath.getPath() ).
                setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE ).
                newGraphDatabase();

            Transaction transaction = db.beginTx();
            try
            {
                db.index().forNodes( "created-no-commits" );
                transaction.success();
            }
            finally
            {
                transaction.finish();
            }

            OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
            backup.full( backupPath.getPath() );
            assertTrue( "Should be consistent", backup.isConsistent() );
            assertTrue( backup.isConsistent() );
        }
        finally
        {
            if ( db != null )
            {
                db.shutdown();
            }
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method public backupIndexWithNoCommits() : void from class org.neo4j.backup.TestBackup


    public Client( String hostNameOrIp, int port, Logging logging, Monitors monitors,
                   StoreId storeId, int frameLength,
                   byte applicationProtocolVersion, long readTimeout,
                   int maxConcurrentChannels, int chunkSize )
    {
        assertChunkSizeIsWithinFrameSize( chunkSize, frameLength );

        this.msgLog = logging.getMessagesLog( getClass() );
        this.storeId = storeId;
        this.frameLength = frameLength;
        this.readTimeout = readTimeout;
        // ResourcePool no longer controls max concurrent channels. Use this value for the pool size
        this.maxUnusedChannels = maxConcurrentChannels;
        this.mismatchingVersionHandlers = new ArrayList<>( 2 );
        this.address = new InetSocketAddress( hostNameOrIp, port );
        this.protocol = new Protocol( chunkSize, applicationProtocolVersion, getInternalProtocolVersion() );

        msgLog.info( getClass().getSimpleName() + " communication channel created towards " + hostNameOrIp + ":" +
                port );
        this.requestMonitor = monitors.newMonitor( RequestMonitor.class, getClass() );
    }

    public Client( String hostNameOrIp, int port, Logging logging, Monitors monitors,
                   StoreId storeId, int frameLength,
                   byte applicationProtocolVersion, long readTimeout,
                   int maxConcurrentChannels, int chunkSize )
    {
        assertChunkSizeIsWithinFrameSize( chunkSize, frameLength );

        this.msgLog = logging.getMessagesLog( getClass() );
        this.storeId = storeId;
        this.frameLength = frameLength;
        this.readTimeout = readTimeout;
        // ResourcePool no longer controls max concurrent channels. Use this value for the pool size
        this.maxUnusedChannels = maxConcurrentChannels;
        this.mismatchingVersionHandlers = new ArrayList<MismatchingVersionHandler>( 2 );
        this.address = new InetSocketAddress( hostNameOrIp, port );
        this.protocol = new Protocol( chunkSize, applicationProtocolVersion, getInternalProtocolVersion() );

        msgLog.info( getClass().getSimpleName() + " communication channel created towards " + hostNameOrIp + ":" +
                port );
        this.requestMonitor = monitors.newMonitor( RequestMonitor.class, getClass() );
    }

Replace Generic With Diamond ArrayList<MismatchingVersionHandler> with ArrayList<> in method public Client(hostNameOrIp String, port int, logging Logging, monitors Monitors, storeId StoreId, frameLength int, applicationProtocolVersion byte, readTimeout long, maxConcurrentChannels int, chunkSize int) from class org.neo4j.com.Client


    private Node createMiniTree( GraphDatabaseService db )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node root = db.createNode();
            root.createRelationshipTo( db.createNode(), MyRelTypes.TEST );
            root.createRelationshipTo( db.createNode(), MyRelTypes.TEST );
            tx.success();
            return root;
        }
    }

    private Node createMiniTree( GraphDatabaseService db )
    {
        Transaction tx = db.beginTx();
        try
        {
            Node root = db.createNode();
            root.createRelationshipTo( db.createNode(), MyRelTypes.TEST );
            root.createRelationshipTo( db.createNode(), MyRelTypes.TEST );
            tx.success();
            return root;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createMiniTree(db GraphDatabaseService) : Node from class org.neo4j.ha.TransactionConstraintsIT


    private void deleteNode( HighlyAvailableGraphDatabase db, long id )
    {
        try ( Transaction tx = db.beginTx() )
        {
            db.getNodeById( id ).delete();
            tx.success();
        }
    }

    private void deleteNode( HighlyAvailableGraphDatabase db, long id )
    {
        Transaction tx = db.beginTx();
        try
        {
            db.getNodeById( id ).delete();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private deleteNode(db HighlyAvailableGraphDatabase, id long) : void from class org.neo4j.ha.TransactionConstraintsIT


    private void doABogusTransaction( GraphDatabaseService db ) throws Exception
    {
        try ( Transaction ignore = db.beginTx() )
        {
            db.createNode();
        }
    }

    private void doABogusTransaction( GraphDatabaseService db ) throws Exception
    {
        Transaction tx = db.beginTx();
        try
        {
            db.createNode();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction ignore=db.beginTx()) in method private doABogusTransaction(db GraphDatabaseService) : void from class org.neo4j.ha.TransactionConstraintsIT


    private Node createNode( GraphDatabaseService db, String... labels )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            for ( String label : labels )
            {
                node.addLabel( DynamicLabel.label( label ) );
            }
            node.setProperty( PROPERTY_KEY, PROPERTY_VALUE );
            tx.success();
            return node;
        }
    }

    private Node createNode( GraphDatabaseService db )
    {
        Transaction tx = db.beginTx();
        try
        {
            Node node = db.createNode();
            node.setProperty( "name", "yo" );
            tx.success();
            return node;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createNode(db GraphDatabaseService, labels String...) : Node from class org.neo4j.ha.TransactionConstraintsIT


    @Test
    public void canMeasureAmountsOfHitsAndMisses() throws Exception
    {
        try(Transaction tx = graphDb.beginTx())
        {
            graphDb.createNode();
            tx.success();
        }

        graphDb.getDependencyResolver().resolveDependency( Caches.class ).clear();

        long[] hits = get( CacheBean.HIT_COUNT ), miss = get( CacheBean.MISS_COUNT );
        try ( Transaction transaction = graphDb.beginTx() )
        {
            graphDb.getNodeById(0);
            graphDb.getNodeById(0);
            transaction.success();
        }
        assertChanged( "hit count not updated", hits, get( CacheBean.HIT_COUNT ) );
        assertChanged( "miss count not updated", miss, get( CacheBean.MISS_COUNT ) );
    }

    @Test
    public void canMeasureAmountsOfHitsAndMisses() throws Exception
    {
        try(Transaction tx = graphDb.beginTx())
        {
            graphDb.createNode();
            tx.success();
        }

        graphDb.getDependencyResolver().resolveDependency( Caches.class ).clear();

        long[] hits = get( CacheBean.HIT_COUNT ), miss = get( CacheBean.MISS_COUNT );
        Transaction transaction = graphDb.beginTx();
        try
        {
            graphDb.getNodeById(0);
            graphDb.getNodeById(0);
        }
        finally
        {
            transaction.finish();
        }
        assertChanged( "hit count not updated", hits, get( CacheBean.HIT_COUNT ) );
        assertChanged( "miss count not updated", miss, get( CacheBean.MISS_COUNT ) );
    }

Try With Resources try(Transaction transaction=graphDb.beginTx()) in method public canMeasureAmountsOfHitsAndMisses() : void from class org.neo4j.management.TestCacheBeans


        private Map<String, Byte> readMap( ReadableLogChannel channel ) throws IOException
        {
            byte size = channel.get();
            Map<String, Byte> result = new HashMap<>();
            for ( int i = 0; i < size; i++ )
            {
                String key = read2bLengthAndString( channel );
                byte id = channel.get();
                if ( key == null )
                {
                    return null;
                }
                result.put( key, id );
            }
            return result;
        }

        private Map<String, Byte> readMap( ReadableLogChannel channel ) throws IOException
        {
            byte size = channel.get();
            Map<String, Byte> result = new HashMap<String, Byte>();
            for ( int i = 0; i < size; i++ )
            {
                String key = read2bLengthAndString( channel );
                byte id = channel.get();
                if ( key == null )
                {
                    return null;
                }
                result.put( key, id );
            }
            return result;
        }

Replace Generic With Diamond HashMap<String,Byte> with HashMap<> in method private readMap(channel ReadableLogChannel) : Map<String,Byte> from class org.neo4j.kernel.impl.nioneo.xa.command.PhysicalLogNeoCommandReaderV1.PhysicalNeoCommandReader


    @Test
    public void crashAndRebuildSlowWithDynamicStringDeletions() throws Exception
    {
        String storeDir = new File("dir").getAbsolutePath();
        final GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory()
                .setFileSystem( fs.get() ).newImpermanentDatabase( storeDir );
        produceNonCleanDefraggedStringStore( db );
        EphemeralFileSystemAbstraction snapshot = fs.snapshot( shutdownDb( db ) );

        // Recover with rebuild_idgenerators_fast=false
        assertNumberOfFreeIdsEquals( storeDir, snapshot, 0 );
        GraphDatabaseAPI newDb = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( snapshot )
                .newImpermanentDatabaseBuilder( storeDir )
                .setConfig( GraphDatabaseSettings.rebuild_idgenerators_fast, Settings.FALSE )
                .newGraphDatabase();
        assertNumberOfFreeIdsEquals( storeDir, snapshot, 4 );

        try ( Transaction tx = newDb.beginTx() )
        {
            int nameCount = 0;
            int relCount = 0;
            for ( Node node : GlobalGraphOperations.at( newDb ).getAllNodes() )
            {
                nameCount++;
                assertThat( node, inTx( newDb, hasProperty( "name" ), true ) );
                relCount += count( node.getRelationships( Direction.OUTGOING ) );
            }

            assertEquals( 16, nameCount );
            assertEquals( 12, relCount );
            tx.success();
        }
        finally
        {
            newDb.shutdown();
        }
    }

    @Test
    public void crashAndRebuildSlowWithDynamicStringDeletions() throws Exception
    {
        String storeDir = new File("dir").getAbsolutePath();
        final GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory()
                .setFileSystem( fs.get() ).newImpermanentDatabase( storeDir );
        produceNonCleanDefraggedStringStore( db );
        EphemeralFileSystemAbstraction snapshot = fs.snapshot( shutdownDb( db ) );

        // Recover with rebuild_idgenerators_fast=false
        assertNumberOfFreeIdsEquals( storeDir, snapshot, 0 );
        GraphDatabaseAPI newDb = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( snapshot )
                .newImpermanentDatabaseBuilder( storeDir )
                .setConfig( GraphDatabaseSettings.rebuild_idgenerators_fast, Settings.FALSE )
                .newGraphDatabase();
        assertNumberOfFreeIdsEquals( storeDir, snapshot, 4 );

        Transaction transaction = newDb.beginTx();
        try
        {
            int nameCount = 0;
            int relCount = 0;
            for ( Node node : GlobalGraphOperations.at( newDb ).getAllNodes() )
            {
                nameCount++;
                assertThat( node, inTx( newDb, hasProperty( "name" )  ) );
                relCount += count( node.getRelationships( Direction.OUTGOING ) );
            }

            assertEquals( 16, nameCount );
            assertEquals( 12, relCount );
        }
        finally
        {
            transaction.finish();
            newDb.shutdown();
        }
    }

Try With Resources try(Transaction tx=newDb.beginTx()) in method public crashAndRebuildSlowWithDynamicStringDeletions() : void from class org.neo4j.kernel.impl.core.TestCrashWithRebuildSlow


    private static void produceNonCleanDefraggedStringStore( GraphDatabaseService db )
    {
        // Create some strings
        List<Node> nodes = new ArrayList<>();
        try ( Transaction tx = db.beginTx() )
        {
            Node previous = null;
            for ( int i = 0; i < 20; i++ )
            {
                Node node = db.createNode();
                node.setProperty( "name", "a looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong string" );
                nodes.add( node );
                if ( previous != null )
                {
                    previous.createRelationshipTo( node, MyRelTypes.TEST );
                }
                previous = node;
            }
            tx.success();
        }

        // Delete some of them, but leave some in between deletions
        try ( Transaction tx = db.beginTx() )
        {
            delete( nodes.get( 5 ) );
            delete( nodes.get( 7 ) );
            delete( nodes.get( 8 ) );
            delete( nodes.get( 10 ) );
            tx.success();
        }
    }

    private void produceNonCleanDefraggedStringStore( GraphDatabaseService db )
    {
        // Create some strings
        List<Node> nodes = new ArrayList<Node>();
        Transaction tx = db.beginTx();
        try
        {
            Node previous = null;
            for ( int i = 0; i < 20; i++ )
            {
                Node node = db.createNode();
                node.setProperty( "name", "a looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong string" );
                nodes.add( node );
                if ( previous != null )
                {
                    previous.createRelationshipTo( node, MyRelTypes.TEST );
                }
                previous = node;
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }

        // Delete some of them, but leave some in between deletions
        tx = db.beginTx();
        try
        {
            delete( nodes.get( 5 ) );
            delete( nodes.get( 7 ) );
            delete( nodes.get( 8 ) );
            delete( nodes.get( 10 ) );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private produceNonCleanDefraggedStringStore(db GraphDatabaseService) : void from class org.neo4j.kernel.impl.core.TestCrashWithRebuildSlow


    private boolean indexExists( String indexName )
    {
        try ( Transaction transaction = db.beginTx() )
        {
            boolean exists = db.index().existsForNodes( indexName );
            transaction.success();
            return exists;
        }
    }

    private boolean indexExists( String indexName )
    {
        Transaction transaction = db.beginTx();
        try
        {
            return db.index().existsForNodes( indexName );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method private indexExists(indexName String) : boolean from class org.neo4j.kernel.impl.index.TestIndexImplOnNeo


    public static long[] readLogHeader( FileSystemAbstraction fileSystem, File file ) throws IOException
    {
        try ( StoreChannel channel = fileSystem.open( file, "r" ) )
        {
            return readLogHeader( ByteBuffer.allocateDirect( 100*1000 ), channel, true );
        }
    }

    public static long[] readLogHeader( FileSystemAbstraction fileSystem, File file ) throws IOException
    {
        StoreChannel channel = fileSystem.open( file, "r" );
        try
        {
            return readLogHeader( ByteBuffer.allocateDirect( 100*1000 ), channel, true );
        }
        finally
        {
            channel.close();
        }
    }

Try With Resources try(StoreChannel channel=fileSystem.open(file,"r")) in method public readLogHeader(fileSystem FileSystemAbstraction, file File) : long[] from class org.neo4j.kernel.impl.transaction.xaframework.VersionAwareLogEntryReader


    private void doTransaction()
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            node.setProperty( "name", "a somewhat lengthy string of some sort, right?" );
            tx.success();
        }
    }

    private void doTransaction()
    {
        Transaction tx = db.beginTx();
        try
        {
            db.createNode();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private doTransaction() : void from class org.neo4j.kernel.impl.transaction.xaframework.TestLogPruning


    private Map<String, String> injectDefaultProviderIfMissing( String indexName, Map<?, ?> dbConfig,
            Map<String, String> config )
    {
        String provider = config.get( PROVIDER );
        if ( provider == null )
        {
            config = new HashMap<>( config );
            config.put( PROVIDER, getDefaultProvider( indexName, dbConfig ) );
        }
        return config;
    }

    private Map<String, String> injectDefaultProviderIfMissing( String indexName, Map<?, ?> dbConfig,
            Map<String, String> config )
    {
        String provider = config.get( PROVIDER );
        if ( provider == null )
        {
            config = new HashMap<String, String>( config );
            config.put( PROVIDER, getDefaultProvider( indexName, dbConfig ) );
        }
        return config;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method private injectDefaultProviderIfMissing(indexName String, dbConfig Map<?,?>, config Map<String,String>) : Map<String,String> from class org.neo4j.kernel.impl.index.LegacyIndexStore


    private Map<String, String> config( Class<? extends PropertyContainer> cls,
            String indexName, Map<String, String> config )
    {
        // TODO Doesn't look right
        if ( config != null )
        {
            config = MapUtil.stringMap( new HashMap<>( config ),
                    IndexManager.PROVIDER, LuceneIndexImplementation.SERVICE_NAME );
            indexStore.setIfNecessary( cls, indexName, config );
            return config;
        }
        else
        {
            return indexStore.get( cls, indexName );
        }
    }

    private Map<String, String> config( Class<? extends PropertyContainer> cls,
            String indexName, Map<String, String> config )
    {
        // TODO Doesn't look right
        if ( config != null )
        {
            config = MapUtil.stringMap( new HashMap<String, String>( config ),
                    IndexManager.PROVIDER, LuceneIndexImplementation.SERVICE_NAME );
            indexStore.setIfNecessary( cls, indexName, config );
            return config;
        }
        else
        {
            return indexStore.get( cls, indexName );
        }
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method private config(cls Class<? extends PropertyContainer>, indexName String, config Map<String,String>) : Map<String,String> from class org.neo4j.index.impl.lucene.LuceneBatchInserterIndexProviderNewImpl


    @Override
    public Map<String, String> fillInDefaults( Map<String, String> source )
    {
        Map<String, String> result = source != null ?
                new HashMap<>( source ) : new HashMap<String, String>();
        String analyzer = result.get( KEY_ANALYZER );
        if ( analyzer == null )
        {
            // Type is only considered if "analyzer" isn't supplied
            String type = result.get( KEY_TYPE );
            if ( type == null )
            {
                type = "exact";
                result.put( KEY_TYPE, type );
            }
            if ( type.equals( "fulltext" ) &&
                 !result.containsKey( LuceneIndexImplementation.KEY_TO_LOWER_CASE ) )
            {
                result.put( KEY_TO_LOWER_CASE, "true" );
            }
        }
        return result;
    }

    @Override
    public Map<String, String> fillInDefaults( Map<String, String> source )
    {
        Map<String, String> result = source != null ?
                new HashMap<String, String>( source ) : new HashMap<String, String>();
        String analyzer = result.get( KEY_ANALYZER );
        if ( analyzer == null )
        {
            // Type is only considered if "analyzer" isn't supplied
            String type = result.get( KEY_TYPE );
            if ( type == null )
            {
                type = "exact";
                result.put( KEY_TYPE, type );
            }
            if ( type.equals( "fulltext" ) &&
                 !result.containsKey( LuceneIndexImplementation.KEY_TO_LOWER_CASE ) )
            {
                result.put( KEY_TO_LOWER_CASE, "true" );
            }
        }
        return result;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public fillInDefaults(source Map<String,String>) : Map<String,String> from class org.neo4j.index.impl.lucene.LuceneIndexImplementation


    static Collection<Long> merge( Collection<Long> c1, Collection<Long> c2 )
    {
        if ( c1 == null && c2 == null )
        {
            return Collections.<Long>emptySet();
        }
        else if ( c1 != null && c2 != null )
        {
            if (c1.isEmpty())
            {
                return c2;
            }
            if (c2.isEmpty())
            {
                return c1;
            }
            Collection<Long> result = new HashSet<>( c1.size()+c2.size(), 1 );
            result.addAll( c1 );
            result.addAll( c2 );
            return result;
        }
        else
        {
            return c1 != null ? c1 : c2;
        }
    }

    static Collection<Long> merge( Collection<Long> c1, Collection<Long> c2 )
    {
        if ( c1 == null && c2 == null )
        {
            return Collections.<Long>emptySet();
        }
        else if ( c1 != null && c2 != null )
        {
            if (c1.isEmpty())
            {
                return c2;
            }
            if (c2.isEmpty())
            {
                return c1;
            }
            Collection<Long> result = new HashSet<Long>( c1.size()+c2.size(), 1 );
            result.addAll( c1 );
            result.addAll( c2 );
            return result;
        }
        else
        {
            return c1 != null ? c1 : c2;
        }
    }

Replace Generic With Diamond HashSet<Long> with HashSet<> in method package merge(c1 Collection<Long>, c2 Collection<Long>) : Collection<Long> from class org.neo4j.index.impl.lucene.LuceneTransactionState


    private void verifyData( GraphDatabaseService graphdb )
    {
        try ( Transaction tx = graphdb.beginTx() )
        {
            int nodecount = 0;
            for ( Node node : GlobalGraphOperations.at( graphdb ).getAllNodes() )
            {
                int propcount = readProperties( node );
                int relcount = 0;
                for ( Relationship rel : node.getRelationships() )
                {
                    assertEquals( "all relationships should have 3 properties.", 3, readProperties( rel ) );
                    relcount++;
                }
                assertEquals( "all created nodes should have 3 properties.", 3, propcount );
                assertEquals( "all created nodes should have 2 relationships.", 2, relcount );

                nodecount++;
            }
            assertEquals( "The database should have 2 nodes.", 2, nodecount );
        }
    }

    private void verifyData( GraphDatabaseService graphdb )
    {
        Transaction tx = graphdb.beginTx();
        try
        {
            int nodecount = 0;
            for ( Node node : GlobalGraphOperations.at( graphdb ).getAllNodes() )
            {
                int propcount = readProperties( node );
                int relcount = 0;
                for ( Relationship rel : node.getRelationships() )
                {
                    assertEquals( "all relationships should have 3 properties.", 3, readProperties( rel ) );
                    relcount++;
                }
                assertEquals( "all created nodes should have 3 properties.", 3, propcount );
                assertEquals( "all created nodes should have 2 relationships.", 2, relcount );

                nodecount++;
            }
            assertEquals( "The database should have 2 nodes.", 2, nodecount );
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=graphdb.beginTx()) in method private verifyData(graphdb GraphDatabaseService) : void from class org.neo4j.kernel.impl.nioneo.store.IdGeneratorRebuildFailureEmulationTest


    private void createInitialData( GraphDatabaseService graphdb )
    {
        try ( Transaction tx = graphdb.beginTx() )
        {
            Node first = properties( graphdb.createNode() );
            Node other = properties( graphdb.createNode() );
            properties( first.createRelationshipTo( other, DynamicRelationshipType.withName( "KNOWS" ) ) );
            properties( other.createRelationshipTo( first, DynamicRelationshipType.withName( "DISTRUSTS" ) ) );

            tx.success();
        }
    }

    private void createInitialData( GraphDatabaseService graphdb )
    {
        Transaction tx = graphdb.beginTx();
        try
        {
            Node first = properties( graphdb.createNode() );
            Node other = properties( graphdb.createNode() );
            properties( first.createRelationshipTo( other, DynamicRelationshipType.withName( "KNOWS" ) ) );
            properties( other.createRelationshipTo( first, DynamicRelationshipType.withName( "DISTRUSTS" ) ) );

            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=graphdb.beginTx()) in method private createInitialData(graphdb GraphDatabaseService) : void from class org.neo4j.kernel.impl.nioneo.store.IdGeneratorRebuildFailureEmulationTest


    @Test
    public void lazyLoadWithinWriteTransaction() throws Exception
    {
        // Given
        File dir = new File( "dir" );
        BatchInserter inserter = BatchInserters.inserter( dir.getAbsoluteFile().getPath(), fs.get() );
        int count = 3000;
        long nodeId = inserter.createNode( mapWithManyProperties( count /* larger than initial property index load threshold */ ) );
        inserter.shutdown();

        GraphDatabaseService db = new TestGraphDatabaseFactory().setFileSystem( fs.get() ).newImpermanentDatabase( dir.getAbsoluteFile().getPath() );

        // When
        try (Transaction tx = db.beginTx())
        {
            db.createNode();
            Node node = db.getNodeById( nodeId );

            // Then
            assertEquals( count, IteratorUtil.count( node.getPropertyKeys() ) );
            tx.success();
        }
        finally
        {
            db.shutdown();
        }
    }

    @Test
    public void lazyLoadWithinWriteTransaction() throws Exception
    {
        File dir = new File( "dir" );
        BatchInserter inserter = BatchInserters.inserter( dir.getPath(), fs.get() );
        int count = 3000;
        long nodeId = inserter.createNode( mapWithManyProperties( count /* larger than initial property index load threshold */ ) );
        inserter.shutdown();

        GraphDatabaseService db = new TestGraphDatabaseFactory().setFileSystem( fs.get() ).newImpermanentDatabase( dir.getPath() );
        Transaction tx = db.beginTx();
        try
        {
            db.createNode();
            Node node = db.getNodeById( nodeId );
            assertEquals( count, IteratorUtil.count( node.getPropertyKeys() ) );
            tx.success();
        }
        finally
        {
            tx.finish();
            db.shutdown();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method public lazyLoadWithinWriteTransaction() : void from class org.neo4j.kernel.impl.nioneo.store.PropertyKeyTest


    public void execute()
    {
        for ( int attemptsLeft = attempts - 1; attemptsLeft >= 0; attemptsLeft-- )
        {
            try ( Transaction tx = graphDb.beginTx() )
            {
                unitOfWork.doWork();
                tx.success();
            }
            catch ( RuntimeException e )
            {
                if ( attemptsLeft == 0 )
                {
                    throw e;
                }
            }
        }
    }

    public void execute()
    {
        Transaction tx = graphDb.beginTx();

        try
        {
            unitOfWork.doWork();
            tx.success();
        }
        finally
        {
            tx.finish();
        }

    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public execute() : void from class org.neo4j.server.helpers.Transactor