    private void applyCommit( boolean isRecovered )
    {
        try ( LockGroup lockGroup = new LockGroup() )
        {
            committed = true;
            CommandSorter sorter = new CommandSorter();
            // reltypes
            if ( relationshipTypeTokenCommands != null )
            {
                java.util.Collections.sort( relationshipTypeTokenCommands, sorter );
                for ( Command.RelationshipTypeTokenCommand command : relationshipTypeTokenCommands )
                {
                    command.execute();
                    if ( isRecovered )
                    {
                        addRelationshipType( (int) command.getKey() );
                    }
                }
            }
            // label keys
            if ( labelTokenCommands != null )
            {
                java.util.Collections.sort( labelTokenCommands, sorter );
                for ( Command.LabelTokenCommand command : labelTokenCommands )
                {
                    command.execute();
                    if ( isRecovered )
                    {
                        addLabel( (int) command.getKey() );
                    }
                }
            }
            // property keys
            if ( propertyKeyTokenCommands != null )
            {
                java.util.Collections.sort( propertyKeyTokenCommands, sorter );
                for ( Command.PropertyKeyTokenCommand command : propertyKeyTokenCommands )
                {
                    command.execute();
                    if ( isRecovered )
                    {
                        addPropertyKey( (int) command.getKey() );
                    }
                }
            }

            // primitives
            java.util.Collections.sort( relCommands, sorter );
            java.util.Collections.sort( propCommands, sorter );
            executeCreated( lockGroup, isRecovered, propCommands, relCommands, nodeCommands.values() );
            executeModified( lockGroup, isRecovered, propCommands, relCommands, nodeCommands.values() );
            executeDeleted( lockGroup, propCommands, relCommands, nodeCommands.values() );

            // property change set for index updates
            Collection<NodeLabelUpdate> labelUpdates = gatherLabelUpdates();
            if ( !labelUpdates.isEmpty() )
            {
                updateLabelScanStore( labelUpdates );
                cacheAccess.applyLabelUpdates( labelUpdates );
            }

            if ( !nodeCommands.isEmpty() || !propCommands.isEmpty() )
            {
                indexes.updateIndexes( new LazyIndexUpdates(
                        getNodeStore(), getPropertyStore(),
                        new ArrayList<>( propCommands ), new HashMap<>( nodeCommands ) ) );
            }

            // schema rules. Execute these after generating the property updates so. If executed
            // before and we've got a transaction that sets properties/labels as well as creating an index
            // we might end up with this corner-case:
            // 1) index rule created and index population job started
            // 2) index population job processes some nodes, but doesn't complete
            // 3) we gather up property updates and send those to the indexes. The newly created population
            //    job might get those as updates
            // 4) the population job will apply those updates as added properties, and might end up with duplicate
            //    entries for the same property
            for ( SchemaRuleCommand command : schemaRuleCommands )
            {
                command.setTxId( getCommitTxId() );
                command.execute();
                switch ( command.getMode() )
                {
                case DELETE:
                    cacheAccess.removeSchemaRuleFromCache( command.getKey() );
                    break;
                default:
                    cacheAccess.addSchemaRule( command.getSchemaRule() );
                }
            }

            if ( neoStoreCommand != null )
            {
                neoStoreCommand.execute();
                if ( isRecovered )
                {
                    removeGraphPropertiesFromCache();
                }
            }
            if ( !isRecovered )
            {
                updateFirstRelationships();
                state.commitCows(); // updates the cached primitives
            }
            neoStore.setLastCommittedTx( getCommitTxId() );
            if ( isRecovered )
            {
                neoStore.updateIdGenerators();
            }
        }
        finally
        {
            clear();
        }
    }

    private void applyCommit( boolean isRecovered )
    {
        try
        {
            committed = true;
            CommandSorter sorter = new CommandSorter();
            // reltypes
            if ( relationshipTypeTokenCommands != null )
            {
                java.util.Collections.sort( relationshipTypeTokenCommands, sorter );
                for ( Command.RelationshipTypeTokenCommand command : relationshipTypeTokenCommands )
                {
                    command.execute();
                    if ( isRecovered )
                    {
                        addRelationshipType( (int) command.getKey() );
                    }
                }
            }
            // label keys
            if ( labelTokenCommands != null )
            {
                java.util.Collections.sort( labelTokenCommands, sorter );
                for ( Command.LabelTokenCommand command : labelTokenCommands )
                {
                    command.execute();
                    if ( isRecovered )
                    {
                        addLabel( (int) command.getKey() );
                    }
                }
            }
            // property keys
            if ( propertyKeyTokenCommands != null )
            {
                java.util.Collections.sort( propertyKeyTokenCommands, sorter );
                for ( Command.PropertyKeyTokenCommand command : propertyKeyTokenCommands )
                {
                    command.execute();
                    if ( isRecovered )
                    {
                        addPropertyKey( (int) command.getKey() );
                    }
                }
            }

            // primitives
            java.util.Collections.sort( relCommands, sorter );
            java.util.Collections.sort( propCommands, sorter );
            executeCreated( isRecovered, propCommands, relCommands, nodeCommands.values() );
            executeModified( isRecovered, propCommands, relCommands, nodeCommands.values() );
            executeDeleted( propCommands, relCommands, nodeCommands.values() );

            // property change set for index updates
            Collection<NodeLabelUpdate> labelUpdates = gatherLabelUpdates();
            if ( !labelUpdates.isEmpty() )
            {
                updateLabelScanStore( labelUpdates );
                cacheAccess.applyLabelUpdates( labelUpdates );
            }

            if ( !nodeCommands.isEmpty() || !propCommands.isEmpty() )
            {
                indexes.updateIndexes( new LazyIndexUpdates(
                        getNodeStore(), getPropertyStore(),
                        new ArrayList<>( propCommands ), new HashMap<>( nodeCommands ) ) );
            }

            // schema rules. Execute these after generating the property updates so. If executed
            // before and we've got a transaction that sets properties/labels as well as creating an index
            // we might end up with this corner-case:
            // 1) index rule created and index population job started
            // 2) index population job processes some nodes, but doesn't complete
            // 3) we gather up property updates and send those to the indexes. The newly created population
            //    job might get those as updates
            // 4) the population job will apply those updates as added properties, and might end up with duplicate
            //    entries for the same property
            for ( SchemaRuleCommand command : schemaRuleCommands )
            {
                command.setTxId( getCommitTxId() );
                command.execute();
                switch ( command.getMode() )
                {
                case DELETE:
                    cacheAccess.removeSchemaRuleFromCache( command.getKey() );
                    break;
                default:
                    cacheAccess.addSchemaRule( command.getSchemaRule() );
                }
            }

            if ( neoStoreCommand != null )
            {
                neoStoreCommand.execute();
                if ( isRecovered )
                {
                    removeGraphPropertiesFromCache();
                }
            }
            if ( !isRecovered )
            {
                updateFirstRelationships();
                state.commitCows(); // updates the cached primitives
            }
            neoStore.setLastCommittedTx( getCommitTxId() );
            if ( isRecovered )
            {
                neoStore.updateIdGenerators();
            }
        }
        finally
        {
            clear();
        }
    }

Try With Resources try(LockGroup lockGroup=new LockGroup()) in method private applyCommit(isRecovered boolean) : void from class org.neo4j.kernel.impl.nioneo.xa.WriteTransaction


    private void awaitSignal( Process process ) throws IOException
    {
        try ( BufferedReader reader = new BufferedReader( new InputStreamReader( process.getInputStream() ) ) )
        {
            String line = reader.readLine();
            if ( !SIGNAL.equals( line ) )
            {
                fail( "Got weird signal " + line );
            }
            // We got signal, great
        }
    }

    private void awaitSignal( Process process ) throws IOException
    {
        BufferedReader reader = new BufferedReader( new InputStreamReader( process.getInputStream() ) );
        try
        {
            String line = reader.readLine();
            if ( !SIGNAL.equals( line ) )
            {
                fail( "Got weird signal " + line );
            }
            // We got signal, great
        }
        finally
        {
            reader.close();
        }
    }

Try With Resources try(BufferedReader reader=new BufferedReader(new InputStreamReader(process.getInputStream()))) in method private awaitSignal(process Process) : void from class org.neo4j.qa.tooling.DumpProcessInformationTest


    private Set<Class> extractCauseTypes( Throwable e )
    {
        Set<Class> types = new HashSet<>();
        types.add( e.getClass() );
        if ( e.getCause() != null )
        {
            types.addAll( extractCauseTypes( e.getCause() ) );
        }
        return types;
    }

    private Set<Class> extractCauseTypes( Throwable e )
    {
        Set<Class> types = new HashSet<Class>();
        types.add( e.getClass() );
        if ( e.getCause() != null )
        {
            types.addAll( extractCauseTypes( e.getCause() ) );
        }
        return types;
    }

Replace Generic With Diamond HashSet<Class> with HashSet<> in method private extractCauseTypes(e Throwable) : Set<Class> from class org.neo4j.desktop.runtime.DatabaseActions


    public static void selectPlatformUI()
    {
        try
        {
            UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
        }
        catch ( ClassNotFoundException | UnsupportedLookAndFeelException | InstantiationException | IllegalAccessException e)
        {
            // don't care
            e.printStackTrace( System.out );
        }
    }

    public static void selectPlatformUI()
    {
        try
        {
            UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
        }
        catch ( ClassNotFoundException e)
        {
            // don't care
            e.printStackTrace( System.out );
        }
        catch ( UnsupportedLookAndFeelException e )
        {
            // don't care
            e.printStackTrace( System.out );
        }
        catch ( InstantiationException e )
        {
            // don't care
            e.printStackTrace( System.out );
        }
        catch ( IllegalAccessException e )
        {
            // don't care
            e.printStackTrace( System.out );
        }
    }

Merge Catch [catch(ClassNotFoundException e), catch(UnsupportedLookAndFeelException e), catch(InstantiationException e), catch(IllegalAccessException e)] to catch(ClassNotFoundException|UnsupportedLookAndFeelException|InstantiationException|IllegalAccessException e) in method public selectPlatformUI() : void from class org.neo4j.desktop.ui.PlatformUI


    @Test
    public void explicitLocksAffectTheLockCount()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            Node root = graphDb.createNode();
            Lock first = tx.acquireReadLock( root );

            LockInfo lock = getSingleLock();
            assertEquals( "read count", 1, lock.getReadCount() );
            assertEquals( "write count", 1, lock.getWriteCount() );

            tx.acquireReadLock( root );
            lock = getSingleLock();
            assertEquals( "read count", 2, lock.getReadCount() );
            assertEquals( "write count", 1, lock.getWriteCount() );

            tx.acquireWriteLock( root );
            lock = getSingleLock();
            assertEquals( "read count", 2, lock.getReadCount() );
            assertEquals( "write count", 2, lock.getWriteCount() );

            first.release();
            lock = getSingleLock();
            assertEquals( "read count", 1, lock.getReadCount() );
            assertEquals( "write count", 2, lock.getWriteCount() );
        }

        List<LockInfo> locks = lockManager.getLocks();
        assertEquals( "unexpected lock count", 0, locks.size() );
    }

    @Test
    public void explicitLocksAffectTheLockCount()
    {
        Transaction tx = graphDb.beginTx();
        try
        {
            Node root = graphDb.createNode();
            Lock first = tx.acquireReadLock( root );

            LockInfo lock = getSingleLock();
            assertEquals( "read count", 1, lock.getReadCount() );
            assertEquals( "write count", 1, lock.getWriteCount() );

            tx.acquireReadLock( root );
            lock = getSingleLock();
            assertEquals( "read count", 2, lock.getReadCount() );
            assertEquals( "write count", 1, lock.getWriteCount() );

            tx.acquireWriteLock( root );
            lock = getSingleLock();
            assertEquals( "read count", 2, lock.getReadCount() );
            assertEquals( "write count", 2, lock.getWriteCount() );

            first.release();
            lock = getSingleLock();
            assertEquals( "read count", 1, lock.getReadCount() );
            assertEquals( "write count", 2, lock.getWriteCount() );
        }
        finally
        {
            tx.finish();
        }
        List<LockInfo> locks = lockManager.getLocks();
        assertEquals( "unexpected lock count", 0, locks.size() );
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public explicitLocksAffectTheLockCount() : void from class org.neo4j.management.TestLockManagerBean


        DebuggerConnector( BreakPoint[] breakpoints )
        {
            this.args = connector.defaultArguments();
            for ( BreakPoint breakpoint : breakpoints )
            {
                List<BreakPoint> list = this.breakpoints.get( breakpoint.type );
                if ( list == null )
                    this.breakpoints.put( breakpoint.type, list = new ArrayList<>() );
                list.add( breakpoint );
            }
        }

        DebuggerConnector( BreakPoint[] breakpoints )
        {
            this.args = connector.defaultArguments();
            for ( BreakPoint breakpoint : breakpoints )
            {
                List<BreakPoint> list = this.breakpoints.get( breakpoint.type );
                if ( list == null )
                    this.breakpoints.put( breakpoint.type, list = new ArrayList<BreakPoint>() );
                list.add( breakpoint );
            }
        }

Replace Generic With Diamond ArrayList<BreakPoint> with ArrayList<> in method package DebuggerConnector(breakpoints BreakPoint[]) from class org.neo4j.test.subprocess.SubProcess.DebuggerConnector


        DebuggedThread[] suspendedThreads()
        {
            if ( suspended.isEmpty() ) return new DebuggedThread[0];
            List<DebuggedThread> threads = new ArrayList<>();
            for ( com.sun.jdi.ThreadReference thread : suspended.keySet() )
            {
                threads.add( new DebuggedThread( this, thread ) );
            }
            return threads.toArray( new DebuggedThread[threads.size()] );
        }

        DebuggedThread[] suspendedThreads()
        {
            if ( suspended.isEmpty() ) return new DebuggedThread[0];
            List<DebuggedThread> threads = new ArrayList<DebuggedThread>();
            for ( com.sun.jdi.ThreadReference thread : suspended.keySet() )
            {
                threads.add( new DebuggedThread( this, thread ) );
            }
            return threads.toArray( new DebuggedThread[threads.size()] );
        }

Replace Generic With Diamond ArrayList<DebuggedThread> with ArrayList<> in method package suspendedThreads() : DebuggedThread[] from class org.neo4j.test.subprocess.SubProcess.DebugDispatch


        @Override
        public void run()
        {
            while ( true )
            {
                List<PipeTask> done = new ArrayList<>();
                for ( PipeTask task : tasks )
                {
                    if ( !task.pipe() )
                    {
                        done.add( task );
                    }
                }
                if ( !done.isEmpty() ) tasks.removeAll( done );
                if ( tasks.isEmpty() )
                {
                    synchronized ( PipeThread.class )
                    {
                        if ( tasks.isEmpty() )
                        {
                            piper = null;
                            return;
                        }
                    }
                }
                try
                {
                    Thread.sleep( 10 );
                }
                catch ( InterruptedException e )
                {
                    Thread.interrupted();
                }
            }
        }

        @Override
        public void run()
        {
            while ( true )
            {
                List<PipeTask> done = new ArrayList<PipeTask>();
                for ( PipeTask task : tasks )
                {
                    if ( !task.pipe() )
                    {
                        done.add( task );
                    }
                }
                if ( !done.isEmpty() ) tasks.removeAll( done );
                if ( tasks.isEmpty() )
                {
                    synchronized ( PipeThread.class )
                    {
                        if ( tasks.isEmpty() )
                        {
                            piper = null;
                            return;
                        }
                    }
                }
                try
                {
                    Thread.sleep( 10 );
                }
                catch ( InterruptedException e )
                {
                    Thread.interrupted();
                }
            }
        }

Replace Generic With Diamond ArrayList<PipeTask> with ArrayList<> in method public run() : void from class org.neo4j.test.subprocess.SubProcess.PipeThread


    private static InvocationHandler live( Handler handler )
    {
        try
        {
            synchronized ( Handler.class )
            {
                if ( live == null )
                {
                    final Set<Handler> handlers = live = new HashSet<>();
                    Runtime.getRuntime().addShutdownHook( new Thread()
                    {
                        @Override
                        public void run()
                        {
                            killAll( handlers );
                        }
                    } );
                }
                live.add( handler );
            }
        }
        catch ( UnsupportedOperationException e )
        {
            handler.kill( false );
            throw new IllegalStateException( "JVM is shutting down!" );
        }
        return handler;
    }

    private static InvocationHandler live( Handler handler )
    {
        try
        {
            synchronized ( Handler.class )
            {
                if ( live == null )
                {
                    final Set<Handler> handlers = live = new HashSet<Handler>();
                    Runtime.getRuntime().addShutdownHook( new Thread()
                    {
                        @Override
                        public void run()
                        {
                            killAll( handlers );
                        }
                    } );
                }
                live.add( handler );
            }
        }
        catch ( UnsupportedOperationException e )
        {
            handler.kill( false );
            throw new IllegalStateException( "JVM is shutting down!" );
        }
        return handler;
    }

Replace Generic With Diamond HashSet<Handler> with HashSet<> in method private live(handler Handler) : InvocationHandler from class org.neo4j.test.subprocess.SubProcess


    private void assertLuceneLogVersionsExists( int... versions ) throws Exception
    {
        Set<Integer> versionSet = new HashSet<>();
        for ( int version : versions )
            versionSet.add( version );
        File path = new File( getStoreDir( this, 0, false ), "index" );
        for ( File file : nonNull( path.listFiles() ) )
        {
            if ( file.getName().contains( ".log.v" ) )
            {
                int v = parseInt( file.getName().substring( file.getName().lastIndexOf( ".v" )+2 ) );
                assertTrue( "Unexpected version found " + v, versionSet.remove( v ) );
            }
        }
        assertTrue( "These versions weren't found " + versionSet, versionSet.isEmpty() );
    }

    private void assertLuceneLogVersionsExists( int... versions ) throws Exception
    {
        Set<Integer> versionSet = new HashSet<Integer>();
        for ( int version : versions )
            versionSet.add( version );
        File path = new File( getStoreDir( this, 0, false ), "index" );
        for ( File file : nonNull( path.listFiles() ) )
        {
            if ( file.getName().contains( ".log.v" ) )
            {
                int v = parseInt( file.getName().substring( file.getName().lastIndexOf( ".v" )+2 ) );
                assertTrue( "Unexpected version found " + v, versionSet.remove( v ) );
            }
        }
        assertTrue( "These versions weren't found " + versionSet, versionSet.isEmpty() );
    }

Replace Generic With Diamond HashSet<Integer> with HashSet<> in method private assertLuceneLogVersionsExists(versions int...) : void from class recovery.TestRecoveryLogTimingIssues


            @Override
            public void run()
            {
                try( Transaction tx = getGraphDb().beginTx() )
                {
                    tx.acquireWriteLock( entity );
                    gotTheLock.set( true );
                    tx.success();
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                    throw launderedException( e );
                }
            }

            @Override
            public void run()
            {
                Transaction tx = getGraphDb().beginTx();
                try
                {
                    tx.acquireWriteLock( entity );
                    gotTheLock.set( true );
                    tx.success();
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                    throw launderedException( e );
                }
                finally
                {
                    tx.failure();
                }
            }

Try With Resources try(Transaction tx=getGraphDb().beginTx()) in method public run() : void from class org.neo4j.kernel.impl.core.TestNode.testLockProblem.thread.new Thread


                @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;
                    }
                }

                @Override
                public Boolean call() throws Exception
                {
                    Transaction tx = slave.beginTx();

                    try
                    {
                        tx.acquireWriteLock( slave.getNodeById( 0 ) );
                        // Fail
                        return false;
                    }
                    catch ( Exception e )
                    {
                        // Ok!
                        return true;
                    }
                }

Try With Resources try(Transaction tx=slave.beginTx()) in method public call() : Boolean from class org.neo4j.ha.ClusterTransactionTest.givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave.result.new FutureTask<Boolean>.new Callable


    private long getLabelId( HighlyAvailableGraphDatabase db, Label label ) throws LabelNotFoundKernelException
    {
        try ( Transaction ignore = db.beginTx() )
        {
            ThreadToStatementContextBridge bridge = db.getDependencyResolver().resolveDependency(
                    ThreadToStatementContextBridge.class );
            return bridge.instance().readOperations().labelGetForName( label.name() );
        }
    }

    private long getLabelId( HighlyAvailableGraphDatabase db, Label label ) throws LabelNotFoundKernelException
    {
        Transaction tx = db.beginTx();
        try
        {
            ThreadToStatementContextBridge bridge = db.getDependencyResolver().resolveDependency(
                    ThreadToStatementContextBridge.class );
            return bridge.instance().readOperations().labelGetForName( label.name() );
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction ignore=db.beginTx()) in method private getLabelId(db HighlyAvailableGraphDatabase, label Label) : long from class org.neo4j.kernel.LabelIT


    @Before
    public void simpleSanityCheck() throws Exception
    {
        cluster.await( ClusterManager.masterAvailable() );
        cluster.await( ClusterManager.masterSeesMembers( 3 ) );
        cluster.await( ClusterManager.masterSeesSlavesAsAvailable( 1 ) );

        slave = cluster.getAnySlave();

        slaveDir = cluster.getStoreDir( slave );
        slaveTempCopyDir = new File( slaveDir, COPY_FROM_MASTER_TEMP );

        try ( Transaction ignore = slave.beginTx() )
        {
            assertEquals( VALUE, slave.getNodeById( nodeId ).getProperty( KEY ) );
        }
    }

    @Before
    public void simpleSanityCheck() throws Exception
    {
        cluster.await( ClusterManager.masterAvailable() );
        cluster.await( ClusterManager.masterSeesMembers( 3 ) );
        cluster.await( ClusterManager.masterSeesSlavesAsAvailable( 1 ) );

        slave = cluster.getAnySlave();

        slaveDir = cluster.getStoreDir( slave );
        slaveTempCopyDir = new File( slaveDir, COPY_FROM_MASTER_TEMP );

        Transaction transaction = slave.beginTx();
        try
        {
            assertEquals( VALUE, slave.getNodeById( nodeId ).getProperty( KEY ) );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignore=slave.beginTx()) in method public simpleSanityCheck() : void from class slavetest.TestStoreCopy


    private long createIndexedNode( GraphDatabaseService db, String key, String value )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node n = db.createNode();
            n.setProperty( key, value );
            db.index().forNodes( key ).add( n, key, value );
            long nodeId = n.getId();
            tx.success();
            return nodeId;
        }
    }

    private long createIndexedNode( GraphDatabaseService db, String key, String value )
    {
        Transaction tx = db.beginTx();
        try
        {
            Node n = db.createNode();
            n.setProperty( key, value );
            db.index().forNodes( key ).add( n, key, value );
            long nodeId = n.getId();
            tx.success();
            return nodeId;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createIndexedNode(db GraphDatabaseService, key String, value String) : long from class slavetest.TestStoreCopy


    protected void assertRelationshipDoesntExist( long id )
    {
        try ( Transaction ignore = db.beginTx() )
        {
            db.getRelationshipById( id );
            fail( "Relationship " + id + " shouldn't exist" );
        }
        catch ( NotFoundException e )
        {
            // Good
        }
    }

    protected void assertRelationshipDoesntExist( long id )
    {
        Transaction transaction = db.beginTx();
        try
        {
            db.getRelationshipById( id );
            fail( "Relationship " + id + " shouldn't exist" );
        }
        catch ( NotFoundException e )
        { // Good
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignore=db.beginTx()) in method protected assertRelationshipDoesntExist(id long) : void from class org.neo4j.shell.AbstractShellTest


    protected void assertNodeExists( long id )
    {
        try ( Transaction ignore = db.beginTx() )
        {
            db.getNodeById( id );
        }
        catch ( NotFoundException e )
        {
            fail( "Node " + id + " should exist" );
        }
    }

    protected void assertNodeExists( long id )
    {
        Transaction transaction = db.beginTx();
        try
        {
            db.getNodeById( id );
        }
        catch ( NotFoundException e )
        {
            fail( "Node " + id + " should exist" );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignore=db.beginTx()) in method protected assertNodeExists(id long) : void from class org.neo4j.shell.AbstractShellTest


    protected void assertNodeDoesntExist( long id )
    {
        try ( Transaction ignore = db.beginTx() )
        {
            db.getNodeById( id );
            fail( "Relationship " + id + " shouldn't exist" );
        }
        catch ( NotFoundException e )
        {
            // Good
        }
    }

    protected void assertNodeDoesntExist( long id )
    {
        Transaction transaction = db.beginTx();
        try
        {
            db.getNodeById( id );
            fail( "Relationship " + id + " shouldn't exist" );
        }
        catch ( NotFoundException e )
        { // Good
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignore=db.beginTx()) in method protected assertNodeDoesntExist(id long) : void from class org.neo4j.shell.AbstractShellTest


    protected Node getCurrentNode() throws RemoteException, ShellException
    {
        Serializable current = shellServer.interpretVariable( shellClient.getId(), Variables.CURRENT_KEY );
        int nodeId = parseInt( current.toString().substring( 1 ) );
        try ( Transaction tx = db.beginTx() )
        {
            Node nodeById = db.getNodeById( nodeId );
            tx.success();
            return nodeById;
        }
    }

    protected Node getCurrentNode() throws RemoteException, ShellException
    {
        Serializable current = shellServer.interpretVariable( shellClient.getId(), Variables.CURRENT_KEY );
        Transaction transaction = db.beginTx();
        try
        {
            Node nodeById = this.db.getNodeById( parseInt( current.toString().substring( 1 ) ) );
            transaction.success();
            return nodeById;
        }
        finally {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method protected getCurrentNode() : Node from class org.neo4j.shell.AbstractShellTest


    @Test
    public void makeSureSlaveCanJoinEvenIfTooFarBackComparedToMaster() throws Exception
    {
        String key = "foo";
        String value = "bar";

        HighlyAvailableGraphDatabase master = null;
        HighlyAvailableGraphDatabase slave = null;
        try
        {
            master = start( dir.directory( "master", true ).getAbsolutePath(), 0, stringMap( keep_logical_logs.name(),
                    "1 files", ClusterSettings.initial_hosts.name(), "127.0.0.1:5001" ) );
            createNode( master, "something", "unimportant" );
            // Need to start and shutdown the slave so when we start it up later it verifies instead of copying
            slave = start( dir.directory( "slave", true ).getAbsolutePath(), 1,
                    stringMap( ClusterSettings.initial_hosts.name(), "127.0.0.1:5001,127.0.0.1:5002" ) );
            slave.shutdown();

            long nodeId = createNode( master, key, value );
            createNode( master, "something", "unimportant" );
            // Rotating, moving the above transactions away so they are removed on shutdown.
            rotateLogs( getXaDataSourceManager( master ), getKernelPanicGenerator( master ),
                    master.getDependencyResolver().resolveDependency( StringLogger.class ) );

            /*
             * We need to shutdown - rotating is not enough. The problem is that log positions are cached and they
             * are not removed from the cache until we run into the cache limit. This means that the information
             * contained in the log can actually be available even if the log is removed. So, to trigger the case
             * of the master information missing from the master we need to also flush the log entry cache - hence,
             * restart.
             */
            master.shutdown();
            master = start( dir.directory( "master", false ).getAbsolutePath(), 0, stringMap( keep_logical_logs.name(),
                    "1 files", ClusterSettings.initial_hosts.name(), "127.0.0.1:5001" ) );

            slave = start( dir.directory( "slave", false ).getAbsolutePath(), 1,
                    stringMap( ClusterSettings.initial_hosts.name(), "127.0.0.1:5001,127.0.0.1:5002" ) );
            slave.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();

            try ( Transaction ignore = slave.beginTx() )
            {
                assertEquals( "store contents differ", value, slave.getNodeById( nodeId ).getProperty( key ) );
            }
        }
        finally
        {
            if ( slave != null )
            {
                slave.shutdown();
            }

            if ( master != null )
            {
                master.shutdown();
            }
        }
    }

    @Test
    public void makeSureSlaveCanJoinEvenIfTooFarBackComparedToMaster() throws Exception
    {
        String key = "foo";
        String value = "bar";

        HighlyAvailableGraphDatabase master = null;
        HighlyAvailableGraphDatabase slave = null;
        try
        {
            master = start( dir.directory( "master", true ).getAbsolutePath(), 0, stringMap( keep_logical_logs.name(),
                    "1 files", ClusterSettings.initial_hosts.name(), "127.0.0.1:5001" ) );
            createNode( master, "something", "unimportant" );
            // Need to start and shutdown the slave so when we start it up later it verifies instead of copying
            slave = start( dir.directory( "slave", true ).getAbsolutePath(), 1,
                    stringMap( ClusterSettings.initial_hosts.name(), "127.0.0.1:5001,127.0.0.1:5002" ) );
            slave.shutdown();

            long nodeId = createNode( master, key, value );
            createNode( master, "something", "unimportant" );
            // Rotating, moving the above transactions away so they are removed on shutdown.
            rotateLogs( master.getXaDataSourceManager(), master.getKernelPanicGenerator(),
                    master.getDependencyResolver().resolveDependency( StringLogger.class ) );

            /*
             * We need to shutdown - rotating is not enough. The problem is that log positions are cached and they
             * are not removed from the cache until we run into the cache limit. This means that the information
             * contained in the log can actually be available even if the log is removed. So, to trigger the case
             * of the master information missing from the master we need to also flush the log entry cache - hence,
             * restart.
             */
            master.shutdown();
            master = start( dir.directory( "master", false ).getAbsolutePath(), 0, stringMap( keep_logical_logs.name(),
                    "1 files", ClusterSettings.initial_hosts.name(), "127.0.0.1:5001" ) );

            slave = start( dir.directory( "slave", false ).getAbsolutePath(), 1,
                    stringMap( ClusterSettings.initial_hosts.name(), "127.0.0.1:5001,127.0.0.1:5002" ) );
            slave.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();

            Transaction transaction = slave.beginTx();
            try
            {
                assertEquals( "store contents differ", value, slave.getNodeById( nodeId ).getProperty( key ) );
            }
            finally
            {
                transaction.finish();
            }
        }
        finally
        {
            if ( slave != null )
            {
                slave.shutdown();
            }

            if ( master != null )
            {
                master.shutdown();
            }
        }
    }

Try With Resources try(Transaction ignore=slave.beginTx()) in method public makeSureSlaveCanJoinEvenIfTooFarBackComparedToMaster() : void from class slavetest.TestInstanceJoin


        @Override
        public List<String> getDiagnosticsProviders()
        {
            List<String> result = new ArrayList<>();
            for ( DiagnosticsProvider provider : diagnostics )
            {
                result.add( provider.getDiagnosticsIdentifier() );
            }
            return result;
        }

        @Override
        public List<String> getDiagnosticsProviders()
        {
            List<String> result = new ArrayList<String>();
            for ( DiagnosticsProvider provider : diagnostics )
            {
                result.add( provider.getDiagnosticsIdentifier() );
            }
            return result;
        }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public getDiagnosticsProviders() : List<String> from class org.neo4j.management.impl.DiagnosticsBean.DiagnosticsImpl


    @Test
    public void testSetNoCache()
    {
        ArrayList<CacheProvider> cacheList = new ArrayList<>();
        TestGraphDatabaseFactory gdbf = new TestGraphDatabaseFactory();
        gdbf.setCacheProviders( cacheList );
        try
        {
            gdbf.newImpermanentDatabase();
        }
        catch ( IllegalArgumentException iae )
        {
            assertTrue( iae.getMessage().contains( "No provider for cache type" ) );
            assertTrue( iae.getMessage().contains( "register" ) );
            assertTrue( iae.getMessage().contains( "missing" ) );
        }
    }

    @Test
    public void testSetNoCache()
    {
        ArrayList<CacheProvider> cacheList = new ArrayList<CacheProvider>();
        TestGraphDatabaseFactory gdbf = new TestGraphDatabaseFactory();
        gdbf.setCacheProviders( cacheList );
        try
        {
            gdbf.newImpermanentDatabase();
        }
        catch ( IllegalArgumentException iae )
        {
            assertTrue( iae.getMessage().contains( "No provider for cache type" ) );
            assertTrue( iae.getMessage().contains( "register" ) );
            assertTrue( iae.getMessage().contains( "missing" ) );
        }
    }

Replace Generic With Diamond ArrayList<CacheProvider> with ArrayList<> in method public testSetNoCache() : void from class org.neo4j.graphdb.factory.SetCacheProvidersTest


    /**
     * Given a data source name, a start and an end tx, this method extracts
     * these transactions (inclusive) in a transaction stream and encapsulates
     * them in a {@link Response} object, ready to be returned to the slave.
     *
     * @param graphDb        The graph database to use
     * @param dataSourceName The name of the data source to extract transactions
     *                       from
     * @param startTx        The first tx in the returned stream
     * @param endTx          The last tx in the returned stream
     * @return A {@link Response} object containing a transaction stream with
     *         the requested transactions from the specified data source.
     */
    public static Response<Void> getTransactions( GraphDatabaseAPI graphDb,
                                                  String dataSourceName, long startTx, long endTx )
    {
        List<Triplet<String, Long, TxExtractor>> stream = new ArrayList<>();
        XaDataSourceManager dsManager = dsManager( graphDb );
        final XaDataSource dataSource = dsManager.getXaDataSource( dataSourceName );
        if ( dataSource == null )
        {
            throw new RuntimeException( "No data source '" + dataSourceName
                    + "' found" );
        }

        List<LogExtractor> extractors = startTx < endTx ? Collections.singletonList(
                getTransactionStreamForDatasource( dataSource, startTx, endTx, stream, ServerUtil.ALL ) ) :
                Collections.<LogExtractor>emptyList();
        return new Response<>( null, graphDb.storeId(), createTransactionStream(
                Collections.singletonList( dataSourceName ), stream,
                extractors ), ResourceReleaser.NO_OP );

    }

    /**
     * Given a data source name, a start and an end tx, this method extracts
     * these transactions (inclusive) in a transaction stream and encapsulates
     * them in a {@link Response} object, ready to be returned to the slave.
     *
     * @param graphDb        The graph database to use
     * @param dataSourceName The name of the data source to extract transactions
     *                       from
     * @param startTx        The first tx in the returned stream
     * @param endTx          The last tx in the returned stream
     * @return A {@link Response} object containing a transaction stream with
     *         the requested transactions from the specified data source.
     */
    public static Response<Void> getTransactions( GraphDatabaseAPI graphDb,
                                                  String dataSourceName, long startTx, long endTx )
    {
        List<Triplet<String, Long, TxExtractor>> stream = new ArrayList<Triplet<String, Long, TxExtractor>>();
        XaDataSourceManager dsManager = graphDb.getXaDataSourceManager();
        final XaDataSource dataSource = dsManager.getXaDataSource( dataSourceName );
        if ( dataSource == null )
        {
            throw new RuntimeException( "No data source '" + dataSourceName
                    + "' found" );
        }

        List<LogExtractor> extractors = startTx < endTx ? Collections.singletonList(
                getTransactionStreamForDatasource( dataSource, startTx, endTx, stream, ServerUtil.ALL ) ) :
                Collections.<LogExtractor>emptyList();
        return new Response<Void>( null, graphDb.getStoreId(), createTransactionStream(
                Collections.singletonList( dataSourceName ), stream,
                extractors ), ResourceReleaser.NO_OP );

    }

Replace Generic With Diamond Response<Void> with Response<> in method public getTransactions(graphDb GraphDatabaseAPI, dataSourceName String, startTx long, endTx long) : Response<Void> from class org.neo4j.com.ServerUtil


    @Test
    public void bruteForceCreateSamePropertyKeyOnDifferentSlaveAtTheSameTimeShouldYieldSameId() throws Exception
    {
        // Get a hold of all the slaves in there
        List<HighlyAvailableGraphDatabase> slaves = new ArrayList<>();
        for ( int i = 0; i < cluster.size()-1; i++ )
            slaves.add( cluster.getAnySlave( slaves.toArray( new HighlyAvailableGraphDatabase[0] ) ) );

        for ( int i = 0; i < 10; i++ )
        {
            final String key = "Key" + i;
            final CountDownLatch latch = new CountDownLatch( 1 );
            List<Thread> threads = new ArrayList<Thread>();
            for ( HighlyAvailableGraphDatabase slave : slaves )
            {
                final GraphDatabaseAPI db = slave;
                Thread thread = new Thread()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            latch.await();
                        }
                        catch ( InterruptedException e )
                        {
                            throw new RuntimeException( e );
                        }

                        Transaction tx = db.beginTx();
                        try
                        {
                            db.createNode().setProperty( key, "yes" );
                            tx.success();
                        }
                        finally
                        {
                            tx.finish();
                        }
                    }
                };
                thread.start();
                threads.add( thread );
            }

            latch.countDown();
            for ( Thread thread : threads )
            {
                thread.join();
            }

            // Verify so that the property keys on all the machines has got the same id
            int highestId = 0;
            for ( GraphDatabaseAPI db : cluster.getAllMembers() )
            {
                TokenHolder<Token> holder = db.getDependencyResolver().resolveDependency( PropertyKeyTokenHolder.class );
                highestId = highestIdOf( holder, highestId );
                Set<String> types = new HashSet<String>();
                for ( int j = 0; j <= highestId; j++ )
                {
                    Token type = holder.getTokenById( j );
                    if ( type != null )
                    {
                        assertTrue( type.name() + " already existed for " + db, types.add( type.name() ) );
                    }
                }
            }
        }
    }

    @Test
    public void bruteForceCreateSamePropertyKeyOnDifferentSlaveAtTheSameTimeShouldYieldSameId() throws Exception
    {
        // Get a hold of all the slaves in there
        List<HighlyAvailableGraphDatabase> slaves = new ArrayList<HighlyAvailableGraphDatabase>();
        for ( int i = 0; i < cluster.size()-1; i++ )
            slaves.add( cluster.getAnySlave( slaves.toArray( new HighlyAvailableGraphDatabase[0] ) ) );

        for ( int i = 0; i < 10; i++ )
        {
            final String key = "Key" + i;
            final CountDownLatch latch = new CountDownLatch( 1 );
            List<Thread> threads = new ArrayList<Thread>();
            for ( HighlyAvailableGraphDatabase slave : slaves )
            {
                final GraphDatabaseAPI db = slave;
                Thread thread = new Thread()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            latch.await();
                        }
                        catch ( InterruptedException e )
                        {
                            throw new RuntimeException( e );
                        }

                        Transaction tx = db.beginTx();
                        try
                        {
                            db.createNode().setProperty( key, "yes" );
                            tx.success();
                        }
                        finally
                        {
                            tx.finish();
                        }
                    }
                };
                thread.start();
                threads.add( thread );
            }

            latch.countDown();
            for ( Thread thread : threads )
            {
                thread.join();
            }

            // Verify so that the property keys on all the machines has got the same id
            int highestId = 0;
            for ( GraphDatabaseAPI db : cluster.getAllMembers() )
            {
                TokenHolder<Token> holder = db.getDependencyResolver().resolveDependency( PropertyKeyTokenHolder.class );
                highestId = highestIdOf( holder, highestId );
                Set<String> types = new HashSet<String>();
                for ( int j = 0; j <= highestId; j++ )
                {
                    Token type = holder.getTokenById( j );
                    if ( type != null )
                    {
                        assertTrue( type.name() + " already existed for " + db, types.add( type.name() ) );
                    }
                }
            }
        }
    }

Replace Generic With Diamond ArrayList<HighlyAvailableGraphDatabase> with ArrayList<> in method public bruteForceCreateSamePropertyKeyOnDifferentSlaveAtTheSameTimeShouldYieldSameId() : void from class org.neo4j.kernel.ha.TestUniqueKeys


    public void rollback() throws TransactionFailureException
    {
        beginClose();
        try
        {
            try
            {
                dropCreatedConstraintIndexes();
            }
            catch ( IllegalStateException | SecurityException e )
            {
                throw new TransactionFailureException( e );
            }
            finally
            {
                try
                {
                    lockHolder.releaseLocks();
                }
                catch ( ReleaseLocksFailedKernelException e )
                {
                    throw new TransactionFailureException(
                            Exceptions.withCause( new RollbackException( e.getMessage() ), e ) );
                }
            }
            close();
        }
        finally
        {
            closing = false;
        }
    }

    public void rollback() throws TransactionFailureException
    {
        beginClose();
        try
        {
            try
            {
                dropCreatedConstraintIndexes();
            }
            catch ( IllegalStateException e )
            {
                throw new TransactionFailureException( e );
            }
            catch ( SecurityException e )
            {
                throw new TransactionFailureException( e );
            }
            finally
            {
                try
                {
                    lockHolder.releaseLocks();
                }
                catch ( ReleaseLocksFailedKernelException e )
                {
                    throw new TransactionFailureException(
                            Exceptions.withCause( new RollbackException( e.getMessage() ), e ) );
                }
            }
            close();
        }
        finally
        {
            closing = false;
        }
    }

Merge Catch [catch(IllegalStateException e), catch(SecurityException e)] to catch(IllegalStateException|SecurityException e) in method public rollback() : void from class org.neo4j.kernel.api.KernelTransactionImplementation


        void free()
        {
            try
            {
                clear();
                int sizeIndex = buf.capacity() / SIZES[SIZES.length - 1];
                if (sizeIndex == 0) for ( ; sizeIndex < SIZES.length; sizeIndex++ )
                {
                    if (buf.capacity() == SIZES[sizeIndex]) break;
                }
                else
                {
                    sizeIndex += SIZES.length - 1;
                }
                AtomicReferenceArray<Queue<Reference<ByteBuffer>>> pools = POOLS;
                // Use soft references to the buffers to allow the GC to reclaim
                // unused buffers if memory gets scarce.
                SoftReference<ByteBuffer> ref = new SoftReference<>( buf );

                // Put our buffer into a pool, create a pool for the buffer size if one does not exist
                ( sizeIndex < pools.length() ? pools.get( sizeIndex ) : getOrCreatePoolForSize( sizeIndex ) ).add( ref );
            }
            finally
            {
                buf = null;
            }
        }

        void free()
        {
            try
            {
                clear();
                int sizeIndex = buf.capacity() / SIZES[SIZES.length - 1];
                if (sizeIndex == 0) for ( ; sizeIndex < SIZES.length; sizeIndex++ )
                {
                    if (buf.capacity() == SIZES[sizeIndex]) break;
                }
                else
                {
                    sizeIndex += SIZES.length - 1;
                }
                AtomicReferenceArray<Queue<Reference<ByteBuffer>>> pools = POOLS;
                // Use soft references to the buffers to allow the GC to reclaim
                // unused buffers if memory gets scarce.
                SoftReference<ByteBuffer> ref = new SoftReference<ByteBuffer>( buf );

                // Put our buffer into a pool, create a pool for the buffer size if one does not exist
                ( sizeIndex < pools.length() ? pools.get( sizeIndex ) : getOrCreatePoolForSize( sizeIndex ) ).add( ref );
            }
            finally
            {
                buf = null;
            }
        }

Replace Generic With Diamond SoftReference<ByteBuffer> with SoftReference<> in method package free() : void from class org.neo4j.test.impl.EphemeralFileSystemAbstraction.DynamicByteBuffer


        private static synchronized Queue<Reference<ByteBuffer>> getOrCreatePoolForSize( int sizeIndex )
        {
            AtomicReferenceArray<Queue<Reference<ByteBuffer>>> pools = POOLS;
            if ( sizeIndex >= pools.length() )
            {
                int newSize = pools.length();
                while ( sizeIndex >= newSize )
                    newSize <<= 1;
                AtomicReferenceArray<Queue<Reference<ByteBuffer>>> newPool = new AtomicReferenceArray<>( newSize );
                for ( int i = 0; i < pools.length(); i++ )
                    newPool.set( i, pools.get( i ) );
                for ( int i = pools.length(); i < newPool.length(); i++ )
                    newPool.set( i, new ConcurrentLinkedQueue<Reference<ByteBuffer>>() );
                POOLS = pools = newPool;
            }
            return pools.get( sizeIndex );
        }

        private static synchronized Queue<Reference<ByteBuffer>> getOrCreatePoolForSize( int sizeIndex )
        {
            AtomicReferenceArray<Queue<Reference<ByteBuffer>>> pools = POOLS;
            if ( sizeIndex >= pools.length() )
            {
                int newSize = pools.length();
                while ( sizeIndex >= newSize )
                    newSize <<= 1;
                AtomicReferenceArray<Queue<Reference<ByteBuffer>>> newPool = new AtomicReferenceArray<Queue<Reference<ByteBuffer>>>(
                        newSize );
                for ( int i = 0; i < pools.length(); i++ )
                    newPool.set( i, pools.get( i ) );
                for ( int i = pools.length(); i < newPool.length(); i++ )
                    newPool.set( i, new ConcurrentLinkedQueue<Reference<ByteBuffer>>() );
                POOLS = pools = newPool;
            }
            return pools.get( sizeIndex );
        }

Replace Generic With Diamond AtomicReferenceArray<Queue<Reference<ByteBuffer>>> with AtomicReferenceArray<> in method private getOrCreatePoolForSize(sizeIndex int) : Queue<Reference<ByteBuffer>> from class org.neo4j.test.impl.EphemeralFileSystemAbstraction.DynamicByteBuffer


    public EphemeralFileSystemAbstraction()
    {
        this.files = new ConcurrentHashMap<>();
    }

    public EphemeralFileSystemAbstraction()
    {
        this.files = new ConcurrentHashMap<File, EphemeralFileData>();
    }

Replace Generic With Diamond ConcurrentHashMap<File,EphemeralFileData> with ConcurrentHashMap<> in method public EphemeralFileSystemAbstraction() from class org.neo4j.test.impl.EphemeralFileSystemAbstraction


    private EphemeralFileSystemAbstraction( Set<File> directories, Map<File, EphemeralFileData> files )
    {
        this.files = new ConcurrentHashMap<>( files );
        this.directories.addAll( directories );
        this.files.putAll( files );
    }

    private EphemeralFileSystemAbstraction( Set<File> directories, Map<File, EphemeralFileData> files )
    {
        this.files = new ConcurrentHashMap<File, EphemeralFileData>( files );
        this.directories.addAll( directories );
        this.files.putAll( files );
    }

Replace Generic With Diamond ConcurrentHashMap<File,EphemeralFileData> with ConcurrentHashMap<> in method private EphemeralFileSystemAbstraction(directories Set<File>, files Map<File,EphemeralFileData>) from class org.neo4j.test.impl.EphemeralFileSystemAbstraction


    public void assertNoOpenFiles() throws Exception
    {
        List<FileStillOpenException> open = new ArrayList<>();
        for ( EphemeralFileData file : files.values() )
        {
            for ( EphemeralFileChannel channel : loop( file.getOpenChannels() ) )
            {
                open.add( channel.openedAt );
            }
        }
        MultipleExceptionsStrategy.assertEmptyExceptions( open );
    }

    public void assertNoOpenFiles() throws Exception
    {
        List<FileStillOpenException> open = new ArrayList<FileStillOpenException>();
        for ( EphemeralFileData file : files.values() )
        {
            for ( EphemeralFileChannel channel : loop( file.getOpenChannels() ) )
            {
                open.add( channel.openedAt );
            }
        }
        MultipleExceptionsStrategy.assertEmptyExceptions( open );
    }

Replace Generic With Diamond ArrayList<FileStillOpenException> with ArrayList<> in method public assertNoOpenFiles() : void from class org.neo4j.test.impl.EphemeralFileSystemAbstraction


    @Override
    public File[] listFiles( File directory )
    {
        if ( files.containsKey( directory ) )
            // This means that you're trying to list files on a file, not a directory.
            return null;

        List<String> directoryPathItems = splitPath( directory );
        List<File> found = new ArrayList<>();
        for ( Map.Entry<File, EphemeralFileData> file : files.entrySet() )
        {
            File fileName = file.getKey();
            List<String> fileNamePathItems = splitPath( fileName );
            if ( directoryMatches( directoryPathItems, fileNamePathItems ) )
                found.add( constructPath( fileNamePathItems, directoryPathItems.size()+1 ) );
        }
        return found.toArray( new File[found.size()] );
    }

    @Override
    public File[] listFiles( File directory )
    {
        if ( files.containsKey( directory ) )
            // This means that you're trying to list files on a file, not a directory.
            return null;

        List<String> directoryPathItems = splitPath( directory );
        List<File> found = new ArrayList<File>();
        for ( Map.Entry<File, EphemeralFileData> file : files.entrySet() )
        {
            File fileName = file.getKey();
            List<String> fileNamePathItems = splitPath( fileName );
            if ( directoryMatches( directoryPathItems, fileNamePathItems ) )
                found.add( constructPath( fileNamePathItems, directoryPathItems.size()+1 ) );
        }
        return found.toArray( new File[found.size()] );
    }

Replace Generic With Diamond ArrayList<File> with ArrayList<> in method public listFiles(directory File) : File[] from class org.neo4j.test.impl.EphemeralFileSystemAbstraction


    public EphemeralFileSystemAbstraction snapshot()
    {
        Map<File, EphemeralFileData> copiedFiles = new HashMap<>();
        for ( Map.Entry<File, EphemeralFileData> file : files.entrySet() )
        {
            copiedFiles.put( file.getKey(), file.getValue().copy() );
        }
        return new EphemeralFileSystemAbstraction( directories, copiedFiles );
    }

    public EphemeralFileSystemAbstraction snapshot()
    {
        Map<File, EphemeralFileData> copiedFiles = new HashMap<File, EphemeralFileData>();
        for ( Map.Entry<File, EphemeralFileData> file : files.entrySet() )
        {
            copiedFiles.put( file.getKey(), file.getValue().copy() );
        }
        return new EphemeralFileSystemAbstraction( directories, copiedFiles );
    }

Replace Generic With Diamond HashMap<File,EphemeralFileData> with HashMap<> in method public snapshot() : EphemeralFileSystemAbstraction from class org.neo4j.test.impl.EphemeralFileSystemAbstraction


        @Override
        public PathRepresentation<Path> from( Path path )
        {
            return new PathRepresentation<>( path );
        }

        @Override
        public PathRepresentation<Path> from( Path path )
        {
            return new PathRepresentation<Path>( path );
        }

Replace Generic With Diamond PathRepresentation<Path> with PathRepresentation<> in method public from(path Path) : PathRepresentation<Path> from class org.neo4j.server.rest.web.DatabaseActions.PATH_REPRESENTATION_CREATOR.new PathRepresentationCreator<Path>


        public Collection<T> collection()
        {
            try ( Transaction ignored = db.beginTx() )
            {
                return asCollection( manifest() );
            }
        }

        public Collection<T> collection()
        {
            Transaction tx = db.beginTx();
            try
            {
                return asCollection( manifest() );
            }
            finally
            {
                tx.finish();
            }
        }

Try With Resources try(Transaction ignored=db.beginTx()) in method public collection() : Collection<T> from class org.neo4j.graphdb.Neo4jMatchers.Deferred


            @Override
            protected boolean matches( Object item, Description mismatchDescription )
            {
                try ( Transaction ignored = db.beginTx() )
                {
                    if ( inner.matches( item ) )
                    {
                        return true;
                    }

                    inner.describeMismatch( item, mismatchDescription );

                    return false;
                }
            }

            @Override
            protected boolean matches( Object item, Description mismatchDescription )
            {
                Transaction tx = db.beginTx();
                try
                {
                    if ( inner.matches( item ) )
                    {
                        return true;
                    }

                    inner.describeMismatch( item, mismatchDescription );

                    return false;

                }
                finally
                {
                    tx.finish();
                }
            }

Try With Resources try(Transaction ignored=db.beginTx()) in method protected matches(item Object, mismatchDescription Description) : boolean from class org.neo4j.graphdb.Neo4jMatchers.inTx.new DiagnosingMatcher<T>


    public static IndexDefinition createIndex( GraphDatabaseService beansAPI, Label label, String property )
    {
        IndexDefinition indexDef;
        try ( Transaction tx = beansAPI.beginTx() )
        {
            indexDef = beansAPI.schema().indexFor( label ).on( property ).create();
            tx.success();
        }

        waitForIndex( beansAPI, indexDef );
        return indexDef;
    }

    public static IndexDefinition createIndex( GraphDatabaseService beansAPI, Label label, String property )
    {
        Transaction tx = beansAPI.beginTx();
        IndexDefinition indexDef;
        try
        {
            indexDef = beansAPI.schema().indexFor( label ).on( property ).create();
            tx.success();
        }
        finally
        {
            tx.finish();
        }

        waitForIndex( beansAPI, indexDef );
        return indexDef;
    }

Try With Resources try(Transaction tx=beansAPI.beginTx()) in method public createIndex(beansAPI GraphDatabaseService, label Label, property String) : IndexDefinition from class org.neo4j.graphdb.Neo4jMatchers


    public static void waitForIndex( GraphDatabaseService beansAPI, IndexDefinition indexDef )
    {
        try ( Transaction ignored = beansAPI.beginTx() )
        {
            beansAPI.schema().awaitIndexOnline( indexDef, 10, SECONDS );
        }
    }

    public static void waitForIndex( GraphDatabaseService beansAPI, IndexDefinition indexDef )
    {
        Transaction tx;
        tx = beansAPI.beginTx();
        try
        {
            beansAPI.schema().awaitIndexOnline( indexDef, 10, SECONDS );
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction ignored=beansAPI.beginTx()) in method public waitForIndex(beansAPI GraphDatabaseService, indexDef IndexDefinition) : void from class org.neo4j.graphdb.Neo4jMatchers


    public static Object getIndexState( GraphDatabaseService beansAPI, IndexDefinition indexDef )
    {
        try ( Transaction ignored = beansAPI.beginTx() )
        {
            return beansAPI.schema().getIndexState( indexDef );
        }
    }

    public static Object getIndexState( GraphDatabaseService beansAPI, IndexDefinition indexDef )
    {
        Transaction tx;
        tx = beansAPI.beginTx();
        try
        {
            return beansAPI.schema().getIndexState( indexDef );
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction ignored=beansAPI.beginTx()) in method public getIndexState(beansAPI GraphDatabaseService, indexDef IndexDefinition) : Object from class org.neo4j.graphdb.Neo4jMatchers


    @Test
    public void testOpsCountGuardFail()
    {
        GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().
            newImpermanentDatabaseBuilder().
            setConfig( GraphDatabaseSettings.execution_guard_enabled, Settings.TRUE ).
            newGraphDatabase();

        Guard guard = db.getGuard();
        guard.startOperationsCount( 2 );

        try ( Transaction ignored = db.beginTx() )
        {
            db.createNode();
            db.createNode();
            try
            {
                db.createNode();
                fail();
            } catch ( GuardOperationsCountException e )
            {
                // expected
            }
        }

        db.shutdown();
    }

    @Test
    public void testOpsCountGuardFail()
    {
        GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().
            newImpermanentDatabaseBuilder().
            setConfig( GraphDatabaseSettings.execution_guard_enabled, Settings.TRUE ).
            newGraphDatabase();
        db.beginTx();
        Guard guard = db.getGuard();

        guard.startOperationsCount( 2 );
        Node n0 = db.createNode();
        Node n1 = db.createNode();
        try
        {
            Node n2 = db.createNode();
            fail();
        } catch ( GuardOperationsCountException e )
        {
            // expected
        }
        db.shutdown();
    }

Try With Resources try(Transaction ignored=db.beginTx()) in method public testOpsCountGuardFail() : void from class org.neo4j.kernel.TestGuard


    @Before
    public void createInitialData()
    {
        beginTx();
        index = graphDb.index().forNodes( INDEX_NAME );
        index.delete();
        restartTx();

        index = graphDb.index().forNodes( INDEX_NAME );
        key = "key";

        value = "my own value";
        node = graphDb.createNode();
        index.add( node, key, value );
        workers = new ArrayList<>();
    }

    @Before
    public void createInitialData()
    {
        beginTx();
        index = graphDb.index().forNodes( INDEX_NAME );
        index.delete();
        restartTx();

        index = graphDb.index().forNodes( INDEX_NAME );
        key = "key";

        value = "my own value";
        node = graphDb.createNode();
        index.add( node, key, value );
        workers = new ArrayList<WorkThread>();
    }

Replace Generic With Diamond ArrayList<WorkThread> with ArrayList<> in method public createInitialData() : void from class org.neo4j.index.impl.lucene.TestIndexDeletion


    @Test
    public void makeSureFulltextIndexCanBeCaseSensitive()
    {
        Index<Node> index = nodeIndex( MapUtil.stringMap(
                new HashMap<>( LuceneIndexImplementation.FULLTEXT_CONFIG ),
                        "to_lower_case", "false" ) );
        Node node = graphDb.createNode();
        String key = "name";
        String value = "Mattias Persson";
        index.add( node, key, value );
        for ( int i = 0; i < 2; i++ )
        {
            assertThat( index.query( "name", "[A TO Z]" ), contains( node ) );
            assertThat( index.query( "name", "[a TO z]" ), isEmpty() );
            assertThat( index.query( "name", "Matt*" ), contains( node ) );
            assertThat( index.query( "name", "matt*" ), isEmpty() );
            assertThat( index.query( "name", "Persson" ), contains( node ) );
            assertThat( index.query( "name", "persson" ), isEmpty() );
            restartTx();
        }
    }

    @Test
    public void makeSureFulltextIndexCanBeCaseSensitive()
    {
        Index<Node> index = nodeIndex( MapUtil.stringMap(
                new HashMap<String, String>( LuceneIndexImplementation.FULLTEXT_CONFIG ),
                        "to_lower_case", "false" ) );
        Node node = graphDb.createNode();
        String key = "name";
        String value = "Mattias Persson";
        index.add( node, key, value );
        for ( int i = 0; i < 2; i++ )
        {
            assertThat( index.query( "name", "[A TO Z]" ), contains( node ) );
            assertThat( index.query( "name", "[a TO z]" ), isEmpty() );
            assertThat( index.query( "name", "Matt*" ), contains( node ) );
            assertThat( index.query( "name", "matt*" ), isEmpty() );
            assertThat( index.query( "name", "Persson" ), contains( node ) );
            assertThat( index.query( "name", "persson" ), isEmpty() );
            restartTx();
        }
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public makeSureFulltextIndexCanBeCaseSensitive() : void from class org.neo4j.index.impl.lucene.TestLuceneIndex


    @Test
    public void settingAnEmptyArrayShouldWorkIfOriginalEntityHasAnEmptyArrayAsWell() throws Exception
    {
        // Given
        long nodeId = createNode( map( "emptyArray", new int[]{} ) );

        // When
        actions.setNodeProperty( nodeId, "emptyArray", new ArrayList<>() );

        // Then
        Transaction transaction = graph.beginTx();
        try
        {
            assertThat( ((List<Object>) serialize( actions.getNodeProperty( nodeId, "emptyArray" ) )).size(), is( 0 ) );
        }
        finally
        {
            transaction.finish();
        }
    }

    @Test
    public void settingAnEmptyArrayShouldWorkIfOriginalEntityHasAnEmptyArrayAsWell() throws Exception
    {
        // Given
        long nodeId = createNode( map( "emptyArray", new int[]{} ) );

        // When
        actions.setNodeProperty( nodeId, "emptyArray", new ArrayList<Object>() );

        // Then
        Transaction transaction = graph.beginTx();
        try
        {
            assertThat( ((List<Object>) serialize( actions.getNodeProperty( nodeId, "emptyArray" ) )).size(), is( 0 ) );
        }
        finally
        {
            transaction.finish();
        }
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method public settingAnEmptyArrayShouldWorkIfOriginalEntityHasAnEmptyArrayAsWell() : void from class org.neo4j.server.rest.web.DatabaseActionsTest


    private void assertCanCreateAndFind( GraphDatabaseService db, Label label, String propertyKey, Object value )
    {
        Node created = createNode( db, map( propertyKey, value ), label );
        try ( Transaction tx = db.beginTx() )
        {
            Node found = single( db.findNodesByLabelAndProperty( label, propertyKey, value ) );
            assertThat( found, equalTo( created ) );
            found.delete();
            tx.success();
        }
    }

    private void assertCanCreateAndFind( GraphDatabaseService db, Label label, String propertyKey, Object value )
    {
        Node created = createNode( db, map( propertyKey, value ), label );
        Transaction tx = db.beginTx();
        try
        {
            Node found = single( db.findNodesByLabelAndProperty( label, propertyKey, value ) );
            assertThat(found, equalTo(created));
            found.delete();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private assertCanCreateAndFind(db GraphDatabaseService, label Label, propertyKey String, value Object) : void from class org.neo4j.graphdb.IndexingAcceptanceTest


    private Node createNode( GraphDatabaseService beansAPI, Map<String, Object> properties, Label... labels )
    {
        try ( Transaction tx = beansAPI.beginTx() )
        {
            Node node = beansAPI.createNode( labels );
            for ( Map.Entry<String, Object> property : properties.entrySet() )
                node.setProperty( property.getKey(), property.getValue() );
            tx.success();
            return node;
        }
    }

    private Node createNode( GraphDatabaseService beansAPI, Map<String, Object> properties, Label... labels )
    {
        Transaction tx = beansAPI.beginTx();
        try
        {
            Node node = beansAPI.createNode( labels );
            for ( Map.Entry<String,Object> property : properties.entrySet() )
                node.setProperty( property.getKey(), property.getValue() );
            tx.success();
            return node;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=beansAPI.beginTx()) in method private createNode(beansAPI GraphDatabaseService, properties Map<String,Object>, labels Label...) : Node from class org.neo4j.graphdb.IndexingAcceptanceTest


    protected Collection<InjectableProvider<?>> createDefaultInjectables()
    {
        Collection<InjectableProvider<?>> singletons = new ArrayList<>();

        Database database = getDatabase();

        singletons.add( new DatabaseProvider( database ) );
        singletons.add( new DatabaseActions.Provider( databaseActions ) );
        singletons.add( new GraphDatabaseServiceProvider( database ) );
        singletons.add( new NeoServerProvider( this ) );
        singletons.add( new ConfigurationProvider( getConfiguration() ) );

        singletons.add( new RrdDbProvider( rrdDbWrapper ) );

        singletons.add( new WebServerProvider( getWebServer() ) );

        PluginInvocatorProvider pluginInvocatorProvider = new PluginInvocatorProvider( this );
        singletons.add( pluginInvocatorProvider );
        RepresentationFormatRepository repository = new RepresentationFormatRepository( this );

        singletons.add( new InputFormatProvider( repository ) );
        singletons.add( new OutputFormatProvider( repository ) );
        singletons.add( new CypherExecutorProvider( cypherExecutor ) );
        singletons.add( providerForSingleton( transactionFacade, TransactionFacade.class ) );

        singletons.add( new TransactionFilter( database ) );

        return singletons;
    }

    protected Collection<InjectableProvider<?>> createDefaultInjectables()
    {
        Collection<InjectableProvider<?>> singletons = new ArrayList<InjectableProvider<?>>();

        Database database = getDatabase();

        singletons.add( new DatabaseProvider( database ) );
        singletons.add( new DatabaseActions.Provider( databaseActions ) );
        singletons.add( new GraphDatabaseServiceProvider( database ) );
        singletons.add( new NeoServerProvider( this ) );
        singletons.add( new ConfigurationProvider( getConfiguration() ) );

        singletons.add( new RrdDbProvider( rrdDbWrapper ) );

        singletons.add( new WebServerProvider( getWebServer() ) );

        PluginInvocatorProvider pluginInvocatorProvider = new PluginInvocatorProvider( this );
        singletons.add( pluginInvocatorProvider );
        RepresentationFormatRepository repository = new RepresentationFormatRepository( this );

        singletons.add( new InputFormatProvider( repository ) );
        singletons.add( new OutputFormatProvider( repository ) );
        singletons.add( new CypherExecutorProvider( cypherExecutor ) );
        singletons.add( providerForSingleton( transactionFacade, TransactionFacade.class ) );

        singletons.add( new TransactionFilter( database ) );

        return singletons;
    }

Replace Generic With Diamond ArrayList<InjectableProvider<?>> with ArrayList<> in method protected createDefaultInjectables() : Collection<InjectableProvider<?>> from class org.neo4j.server.AbstractNeoServer


    private void loadAllMounts()
    {
        SessionManager sm = new HashSessionManager();

        final SortedSet<String> mountpoints = new TreeSet<>( new Comparator<String>()
        {
            @Override
            public int compare( final String o1, final String o2 )
            {
                return o2.compareTo( o1 );
            }
        } );

        mountpoints.addAll( staticContent.keySet() );
        mountpoints.addAll( jaxRSPackages.keySet() );
        mountpoints.addAll( jaxRSClasses.keySet() );

        for ( String contentKey : mountpoints )
        {
            final boolean isStatic = staticContent.containsKey( contentKey );
            final boolean isJaxrsPackage = jaxRSPackages.containsKey( contentKey );
            final boolean isJaxrsClass = jaxRSClasses.containsKey( contentKey );

            if ( countSet( isStatic, isJaxrsPackage, isJaxrsClass ) > 1 )
            {
                throw new RuntimeException(
                    format( "content-key '%s' is mapped more than once", contentKey ) );
            }
            else if ( isStatic )
            {
                loadStaticContent( sm, contentKey );
            }
            else if ( isJaxrsPackage )
            {
                loadJAXRSPackage( sm, contentKey );
            }
            else if ( isJaxrsClass )
            {
                loadJAXRSClasses( sm, contentKey );
            }
            else
            {
                throw new RuntimeException( format( "content-key '%s' is not mapped", contentKey ) );
            }
        }

        if( requestLoggingConfiguration != null )
        {
            loadRequestLogging();
        }

    }

    private void loadAllMounts()
    {
        SessionManager sm = new HashSessionManager();

        final SortedSet<String> mountpoints = new TreeSet<String>( new Comparator<String>()
        {
            @Override
            public int compare( final String o1, final String o2 )
            {
                return o2.compareTo( o1 );
            }
        } );

        mountpoints.addAll( staticContent.keySet() );
        mountpoints.addAll( jaxRSPackages.keySet() );
        mountpoints.addAll( jaxRSClasses.keySet() );

        for ( String contentKey : mountpoints )
        {
            final boolean isStatic = staticContent.containsKey( contentKey );
            final boolean isJaxrsPackage = jaxRSPackages.containsKey( contentKey );
            final boolean isJaxrsClass = jaxRSClasses.containsKey( contentKey );

            if ( countSet( isStatic, isJaxrsPackage, isJaxrsClass ) > 1 )
            {
                throw new RuntimeException(
                    format( "content-key '%s' is mapped more than once", contentKey ) );
            }
            else if ( isStatic )
            {
                loadStaticContent( sm, contentKey );
            }
            else if ( isJaxrsPackage )
            {
                loadJAXRSPackage( sm, contentKey );
            }
            else if ( isJaxrsClass )
            {
                loadJAXRSClasses( sm, contentKey );
            }
            else
            {
                throw new RuntimeException( format( "content-key '%s' is not mapped", contentKey ) );
            }
        }

        if( requestLoggingConfiguration != null )
        {
            loadRequestLogging();
        }

    }

Replace Generic With Diamond TreeSet<String> with TreeSet<> in method private loadAllMounts() : void from class org.neo4j.server.web.Jetty9WebServer


    @Override
    public NodeRecord clone()
    {
        NodeRecord clone = new NodeRecord( getId(), getCommittedNextRel(), getCommittedNextProp() );
        clone.setNextProp( getNextProp() );
        clone.nextRel = nextRel;
        clone.labels = labels;
        clone.isLight = isLight;
        clone.setInUse( inUse() );

        if( dynamicLabelRecords.size() > 0 )
        {
            List<DynamicRecord> clonedLabelRecords = new ArrayList<>(dynamicLabelRecords.size());
            for ( DynamicRecord labelRecord : dynamicLabelRecords )
            {
                clonedLabelRecords.add( labelRecord.clone() );
            }
            clone.dynamicLabelRecords = clonedLabelRecords;
        }
        return clone;
    }

    @Override
    public NodeRecord clone()
    {
        NodeRecord clone = new NodeRecord( getId(), getCommittedNextRel(), getCommittedNextProp() );
        clone.setNextProp( getNextProp() );
        clone.nextRel = nextRel;
        clone.labels = labels;
        clone.isLight = isLight;
        clone.setInUse( inUse() );

        if( dynamicLabelRecords.size() > 0 )
        {
            List<DynamicRecord> clonedLabelRecords = new ArrayList<DynamicRecord>(dynamicLabelRecords.size());
            for ( DynamicRecord labelRecord : dynamicLabelRecords )
            {
                clonedLabelRecords.add( labelRecord.clone() );
            }
            clone.dynamicLabelRecords = clonedLabelRecords;
        }
        return clone;
    }

Replace Generic With Diamond ArrayList<DynamicRecord> with ArrayList<> in method public clone() : NodeRecord from class org.neo4j.kernel.impl.nioneo.store.NodeRecord


    private List<?>[] getRecordLists( Iterable<List<Record>> danglingRecords )
    {
        List<List<?>> list = new ArrayList<>();
        for ( List<Record> txs : danglingRecords )
        {
            list.add( txs );
        }
        return list.toArray( new List[list.size()] );
    }

    private List<?>[] getRecordLists( Iterable<List<Record>> danglingRecords )
    {
        List<List<?>> list = new ArrayList<List<?>>();
        for ( List<Record> txs : danglingRecords )
        {
            list.add( txs );
        }
        return list.toArray( new List[list.size()] );
    }

Replace Generic With Diamond ArrayList<List<?>> with ArrayList<> in method private getRecordLists(danglingRecords Iterable<List<Record>>) : List<?>[] from class org.neo4j.kernel.impl.transaction.TestTxLog


    protected Map<String, String> getDbTuningPropertiesWithServerDefaults()
    {
        Map<String, String> result = new HashMap<>( configurator.getDatabaseTuningProperties() );
        putIfAbsent( result, ShellSettings.remote_shell_enabled.name(), Settings.TRUE );
        putIfAbsent( result, GraphDatabaseSettings.keep_logical_logs.name(), Settings.TRUE );

        try
        {
            result.put( UdcSettings.udc_source.name(), "server" );
        }
        catch ( NoClassDefFoundError e )
        {
            // UDC is not on classpath, ignore
        }

        return result;
    }

    protected Map<String, String> getDbTuningPropertiesWithServerDefaults()
    {
        Map<String, String> result = new HashMap<String, String>( configurator.getDatabaseTuningProperties() );
        putIfAbsent( result, ShellSettings.remote_shell_enabled.name(), Settings.TRUE );
        putIfAbsent( result, GraphDatabaseSettings.keep_logical_logs.name(), Settings.TRUE );

        try
        {
            result.put( UdcSettings.udc_source.name(), "server" );
        }
        catch ( NoClassDefFoundError e )
        {
            // UDC is not on classpath, ignore
        }

        return result;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method protected getDbTuningPropertiesWithServerDefaults() : Map<String,String> from class org.neo4j.server.database.CommunityDatabase


    public <STATE> TraversalDescription expand( PathExpander<STATE> expander, InitialStateFactory<STATE> initialState )
    {
        return new MonoDirectionalTraversalDescription( expander, uniqueness,
                uniquenessParameter, evaluator, new InitialStateFactory.AsInitialBranchState<>( initialState ),
                branchOrdering, sorting, endNodes, statementFactory );
    }

    public <STATE> TraversalDescription expand( PathExpander<STATE> expander, InitialStateFactory<STATE> initialState )
    {
        return new MonoDirectionalTraversalDescription( expander, uniqueness,
                uniquenessParameter, evaluator, new InitialStateFactory.AsInitialBranchState<STATE>( initialState ),
                branchOrdering, sorting, endNodes, statementFactory );
    }

Replace Generic With Diamond MonoDirectionalTraversalDescription with MonoDirectionalTraversalDescription in method public expand(expander PathExpander<STATE>, initialState InitialStateFactory<STATE>) : TraversalDescription from class org.neo4j.kernel.impl.traversal.MonoDirectionalTraversalDescription


/**
     * Switches log file. Copies the dangling records in current log file to the
     * newFile and then makes the switch closing the old log file.
     *
     * @param newFile
     *            The filename of the new file to switch to
     * @throws IOException
     *             If unable to switch log file
     */
    public synchronized void switchToLogFile( File newFile )
        throws IOException
    {
        if ( newFile == null )
        {
            throw new IllegalArgumentException( "Null filename" );
        }
        // copy all dangling records from current log to new log
        force();
        Iterable<List<Record>> itr = getDanglingRecords();
        close();
        List<Record> records = new ArrayList<>();
        for ( List<Record> tx : itr )
        {
            records.addAll( tx );
        }
        Collections.sort( records, new Comparator<Record>()
        {
            public int compare( Record r1, Record r2 )
            {
                return r1.getSequenceNumber() - r2.getSequenceNumber();
            }
        } );
        Iterator<Record> recordItr = records.iterator();
        FileChannel fileChannel = fileSystem.open( newFile, "rw" );
        fileChannel.position( fileChannel.size() );
        logBuffer = new DirectMappedLogBuffer( fileChannel );
        name = newFile;
        truncate();
        while ( recordItr.hasNext() )
        {
            Record record = recordItr.next();
            writeRecord( record, ForceMode.forced );
        }
        force();
    }

/**
     * Switches log file. Copies the dangling records in current log file to the
     * newFile and then makes the switch closing the old log file.
     *
     * @param newFile
     *            The filename of the new file to switch to
     * @throws IOException
     *             If unable to switch log file
     */
    public synchronized void switchToLogFile( File newFile )
        throws IOException
    {
        if ( newFile == null )
        {
            throw new IllegalArgumentException( "Null filename" );
        }
        // copy all dangling records from current log to new log
        force();
        Iterable<List<Record>> itr = getDanglingRecords();
        close();
        List<Record> records = new ArrayList<Record>();
        for ( List<Record> tx : itr )
        {
            records.addAll( tx );
        }
        Collections.sort( records, new Comparator<Record>()
        {
            public int compare( Record r1, Record r2 )
            {
                return r1.getSequenceNumber() - r2.getSequenceNumber();
            }
        } );
        Iterator<Record> recordItr = records.iterator();
        FileChannel fileChannel = fileSystem.open( newFile, "rw" );
        fileChannel.position( fileChannel.size() );
        logBuffer = new DirectMappedLogBuffer( fileChannel );
        name = newFile;
        truncate();
        while ( recordItr.hasNext() )
        {
            Record record = recordItr.next();
            writeRecord( record, ForceMode.forced );
        }
        force();
    }

Replace Generic With Diamond ArrayList<Record> with ArrayList<> in method public switchToLogFile(newFile File) : void from class org.neo4j.kernel.impl.transaction.TxLog


    private Iterator<Path> fetchAndSortResult()
    {
        List<Path> result = new ArrayList<>();
        while ( source.hasNext() )
        {
            result.add( source.next() );
        }
        Collections.sort( result, this.traverserImpl.description.sorting );
        return result.iterator();
    }

    private Iterator<Path> fetchAndSortResult()
    {
        List<Path> result = new ArrayList<Path>();
        while ( source.hasNext() )
        {
            result.add( source.next() );
        }
        Collections.sort( result, this.traverserImpl.description.sorting );
        return result.iterator();
    }

Replace Generic With Diamond ArrayList<Path> with ArrayList<> in method private fetchAndSortResult() : Iterator<Path> from class org.neo4j.kernel.impl.traversal.SortingTraverserIterator


    private Index<Node> createIndex()
    {
        GraphDatabaseService graphDatabaseService = dbRule.getGraphDatabaseService();
        try ( Transaction transaction = graphDatabaseService.beginTx() )
        {
            Index<Node> index = graphDatabaseService.index().forNodes( "foo" );
            transaction.success();
            return index;
        }
    }

    private Index<Node> createIndex()
    {
        GraphDatabaseService graphDatabaseService = dbRule.getGraphDatabaseService();
        Transaction transaction = graphDatabaseService.beginTx();
        try
        {
            Index<Node> index = graphDatabaseService.index().forNodes( "foo" );
            transaction.success();
            return index;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=graphDatabaseService.beginTx()) in method private createIndex() : Index<Node> from class org.neo4j.graphdb.MandatoryTransactionsForIndexHitsFacadeTests


    private IndexHits<Node> queryIndex( Index<Node> index )
    {
        GraphDatabaseService graphDatabaseService = dbRule.getGraphDatabaseService();
        try ( Transaction transaction = graphDatabaseService.beginTx() )
        {
            return index.get( "foo", 42 );
        }
    }

    private IndexHits<Node> queryIndex( Index<Node> index )
    {
        GraphDatabaseService graphDatabaseService = dbRule.getGraphDatabaseService();
        Transaction transaction = graphDatabaseService.beginTx();
        try
        {
            return index.get( "foo", 42 );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=graphDatabaseService.beginTx()) in method private queryIndex(index Index<Node>) : IndexHits<Node> from class org.neo4j.graphdb.MandatoryTransactionsForIndexHitsFacadeTests


    public EvaluatorFactory( boolean enableSandboxing )
    {
        Map<String,ScriptExecutor.Factory> languages = new HashMap<>();
        languages.put( "javascript", new JavascriptExecutor.Factory( enableSandboxing ) );

        factoryRepo = new ScriptExecutorFactoryRepository( languages );
    }

    public EvaluatorFactory( boolean enableSandboxing )
    {
        Map<String,ScriptExecutor.Factory> languages = new HashMap<String, ScriptExecutor.Factory>();
        languages.put( "javascript", new JavascriptExecutor.Factory( enableSandboxing ) );

        factoryRepo = new ScriptExecutorFactoryRepository( languages );
    }

Replace Generic With Diamond HashMap<String,ScriptExecutor.Factory> with HashMap<> in method public EvaluatorFactory(enableSandboxing boolean) from class org.neo4j.server.rest.domain.EvaluatorFactory


    private long extractNodeId( String uri ) throws BadInputException
    {
        try
        {
            return Long.parseLong( uri.substring( uri.lastIndexOf( "/" ) + 1 ) );
        }
        catch ( NumberFormatException | NullPointerException ex )
        {
            throw new BadInputException( ex );
        }
    }

    private long extractNodeId( String uri ) throws BadInputException
    {
        try
        {
            return Long.parseLong( uri.substring( uri.lastIndexOf( "/" ) + 1 ) );
        }
        catch ( NumberFormatException ex )
        {
            throw new BadInputException( ex );
        }
        catch ( NullPointerException ex )
        {
            throw new BadInputException( ex );
        }
    }

Merge Catch [catch(NumberFormatException ex), catch(NullPointerException ex)] to catch(NumberFormatException|NullPointerException ex) in method private extractNodeId(uri String) : long from class org.neo4j.server.rest.web.RestfulGraphDatabase


    private void createLinkedList( int listLength, Database db )
    {
        try ( Transaction tx = db.getGraph().beginTx() )
        {
            Node previous = null;
            for ( int i = 0; i < listLength; i++ )
            {
                Node current = db.getGraph().createNode();

                if ( previous != null )
                {
                    previous.createRelationshipTo( current, DynamicRelationshipType.withName( "NEXT" ) );
                }
                else
                {
                    startNode = current;
                }

                previous = current;
            }
            tx.success();
        }
    }

    private void createLinkedList( int listLength, Database db )
    {
        Transaction tx = db.getGraph().beginTx();
        try
        {
            Node previous = null;
            for ( int i = 0; i < listLength; i++ )
            {
                Node current = db.getGraph().createNode();

                if ( previous != null )
                {
                    previous.createRelationshipTo( current, DynamicRelationshipType.withName( "NEXT" ) );
                }
                else
                {
                    startNode = current;
                }

                previous = current;
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.getGraph().beginTx()) in method private createLinkedList(listLength int, db Database) : void from class org.neo4j.server.rest.paging.PagedTraverserTest


    @SuppressWarnings( "unused" )
    private int iterateThroughPagedTraverser( PagedTraverser traversalPager )
    {
        try ( Transaction transaction = database.getGraph().beginTx() )
        {
            int count = 0;
            for ( List<Path> paths : traversalPager )
            {
                count++;
            }
            transaction.success();
            return count;
        }
    }

    @SuppressWarnings( "unused" )
    private int iterateThroughPagedTraverser( PagedTraverser traversalPager )
    {
        Transaction transaction = database.getGraph().beginTx();
        try
        {
            int count = 0;
            for ( List<Path> paths : traversalPager )
            {
                count++;
            }
            return count;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=database.getGraph().beginTx()) in method private iterateThroughPagedTraverser(traversalPager PagedTraverser) : int from class org.neo4j.server.rest.paging.PagedTraverserTest


    @Test
    public void shouldCreateUniquenessConstraint() throws Exception
    {
        // WHEN
        ConstraintDefinition constraint = createConstraint( label, propertyKey );

        // THEN
        try ( Transaction tx = db.beginTx() )
        {
            assertEquals( ConstraintType.UNIQUENESS, constraint.getConstraintType() );

            assertEquals( label.name(), constraint.getLabel().name() );
            assertEquals( asSet( propertyKey ), asSet( constraint.getPropertyKeys() ) );
            tx.success();
        }
    }

    @Test
    public void shouldCreateUniquenessConstraint() throws Exception
    {
        // GIVEN

        // WHEN
        ConstraintDefinition constraint = createConstraint( label, propertyKey );

        // THEN
        Transaction tx = db.beginTx();
        try
        {
            assertEquals( ConstraintType.UNIQUENESS, constraint.getConstraintType() );

            assertEquals( label.name(), constraint.getLabel().name() );
            assertEquals( asSet( propertyKey ), asSet( constraint.getPropertyKeys() ) );
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method public shouldCreateUniquenessConstraint() : void from class org.neo4j.graphdb.SchemaAcceptanceTest


    private GraphDatabaseAPI databaseWithManyPropertyKeys( int propertyKeyCount )
    {
        GraphDatabaseAPI db = database();
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            for ( int i = 0; i < propertyKeyCount; i++ )
                node.setProperty( key( i ), true );
            tx.success();
            return db;
        }
    }

    private GraphDatabaseAPI databaseWithManyPropertyKeys( int propertyKeyCount )
    {
        GraphDatabaseAPI db = database();
        Transaction tx = db.beginTx();
        try
        {
            Node node = db.createNode();
            for ( int i = 0; i < propertyKeyCount; i++ )
                node.setProperty( key( i ), true );
            tx.success();
            return db;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private databaseWithManyPropertyKeys(propertyKeyCount int) : GraphDatabaseAPI from class org.neo4j.kernel.impl.core.ManyPropertyKeysIT