    private Node createNodeWithProperty( GraphDatabaseService db, String key, Object value )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            node.setProperty( key, value );
            tx.success();
            return node;
        }
    }

    private Node createNodeWithProperty( GraphDatabaseService db, String key, Object value )
    {
        Transaction tx = db.beginTx();
        try
        {
            Node node = db.createNode();
            node.setProperty( key, value );
            tx.success();
            return node;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createNodeWithProperty(db GraphDatabaseService, key String, value Object) : Node from class org.neo4j.kernel.impl.core.ManyPropertyKeysIT


    @Override
    protected TxIdGenerator createTxIdGenerator()
    {
        DelegateInvocationHandler<TxIdGenerator> txIdGeneratorDelegate = new DelegateInvocationHandler<>();
        TxIdGenerator txIdGenerator =
                (TxIdGenerator) Proxy.newProxyInstance( TxIdGenerator.class.getClassLoader(),
                        new Class[]{TxIdGenerator.class}, txIdGeneratorDelegate );
        slaves = life.add( new HighAvailabilitySlaves( members, clusterClient, new DefaultSlaveFactory(
                xaDataSourceManager, logging, config.get( HaSettings.com_chunk_size ).intValue() ) ) );

        new TxIdGeneratorModeSwitcher( memberStateMachine, txIdGeneratorDelegate,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, msgLog, config, slaves );
        return txIdGenerator;
    }

    @Override
    protected TxIdGenerator createTxIdGenerator()
    {
        DelegateInvocationHandler<TxIdGenerator> txIdGeneratorDelegate = new DelegateInvocationHandler<TxIdGenerator>();
        TxIdGenerator txIdGenerator =
                (TxIdGenerator) Proxy.newProxyInstance( TxIdGenerator.class.getClassLoader(),
                        new Class[]{TxIdGenerator.class}, txIdGeneratorDelegate );
        slaves = life.add( new HighAvailabilitySlaves( members, clusterClient, new DefaultSlaveFactory(
                xaDataSourceManager, logging, config.get( HaSettings.com_chunk_size ).intValue() ) ) );

        new TxIdGeneratorModeSwitcher( memberStateMachine, txIdGeneratorDelegate,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, msgLog, config, slaves );
        return txIdGenerator;
    }

Replace Generic With Diamond DelegateInvocationHandler<TxIdGenerator> with DelegateInvocationHandler<> in method protected createTxIdGenerator() : TxIdGenerator from class org.neo4j.kernel.ha.HighlyAvailableGraphDatabase


    @Override
    protected LockManager createLockManager()
    {
        DelegateInvocationHandler<LockManager> lockManagerDelegate = new DelegateInvocationHandler<>();
        LockManager lockManager =
                (LockManager) Proxy.newProxyInstance( LockManager.class.getClassLoader(),
                        new Class[]{LockManager.class}, lockManagerDelegate );
        new LockManagerModeSwitcher( memberStateMachine, lockManagerDelegate, txManager, txHook,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, accessGuard, config );
        return lockManager;
    }

    @Override
    protected LockManager createLockManager()
    {
        DelegateInvocationHandler<LockManager> lockManagerDelegate = new DelegateInvocationHandler<LockManager>();
        LockManager lockManager =
                (LockManager) Proxy.newProxyInstance( LockManager.class.getClassLoader(),
                        new Class[]{LockManager.class}, lockManagerDelegate );
        new LockManagerModeSwitcher( memberStateMachine, lockManagerDelegate, txManager, txHook,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, accessGuard, config );
        return lockManager;
    }

Replace Generic With Diamond DelegateInvocationHandler<LockManager> with DelegateInvocationHandler<> in method protected createLockManager() : LockManager from class org.neo4j.kernel.ha.HighlyAvailableGraphDatabase


    @Override
    protected TokenCreator createRelationshipTypeCreator()
    {
        DelegateInvocationHandler<TokenCreator> relationshipTypeCreatorDelegate =
                new DelegateInvocationHandler<>();
        TokenCreator relationshipTypeCreator =
                (TokenCreator) Proxy.newProxyInstance( TokenCreator.class.getClassLoader(),
                        new Class[]{TokenCreator.class}, relationshipTypeCreatorDelegate );
        new RelationshipTypeCreatorModeSwitcher( memberStateMachine, relationshipTypeCreatorDelegate,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, logging );
        return relationshipTypeCreator;
    }

    @Override
    protected TokenCreator createRelationshipTypeCreator()
    {
        DelegateInvocationHandler<TokenCreator> relationshipTypeCreatorDelegate =
                new DelegateInvocationHandler<TokenCreator>();
        TokenCreator relationshipTypeCreator =
                (TokenCreator) Proxy.newProxyInstance( TokenCreator.class.getClassLoader(),
                        new Class[]{TokenCreator.class}, relationshipTypeCreatorDelegate );
        new RelationshipTypeCreatorModeSwitcher( memberStateMachine, relationshipTypeCreatorDelegate,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, logging );
        return relationshipTypeCreator;
    }

Replace Generic With Diamond DelegateInvocationHandler<TokenCreator> with DelegateInvocationHandler<> in method protected createRelationshipTypeCreator() : TokenCreator from class org.neo4j.kernel.ha.HighlyAvailableGraphDatabase


    @Override
    protected TokenCreator createPropertyKeyCreator()
    {
        DelegateInvocationHandler<TokenCreator> propertyKeyCreatorDelegate =
                new DelegateInvocationHandler<>();
        TokenCreator propertyTokenCreator =
                (TokenCreator) Proxy.newProxyInstance( TokenCreator.class.getClassLoader(),
                        new Class[]{TokenCreator.class}, propertyKeyCreatorDelegate );
        new PropertyKeyCreatorModeSwitcher( memberStateMachine, propertyKeyCreatorDelegate,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, logging );
        return propertyTokenCreator;
    }

    @Override
    protected TokenCreator createPropertyKeyCreator()
    {
        DelegateInvocationHandler<TokenCreator> propertyKeyCreatorDelegate =
                new DelegateInvocationHandler<TokenCreator>();
        TokenCreator propertyTokenCreator =
                (TokenCreator) Proxy.newProxyInstance( TokenCreator.class.getClassLoader(),
                        new Class[]{TokenCreator.class}, propertyKeyCreatorDelegate );
        new PropertyKeyCreatorModeSwitcher( memberStateMachine, propertyKeyCreatorDelegate,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, logging );
        return propertyTokenCreator;
    }

Replace Generic With Diamond DelegateInvocationHandler<TokenCreator> with DelegateInvocationHandler<> in method protected createPropertyKeyCreator() : TokenCreator from class org.neo4j.kernel.ha.HighlyAvailableGraphDatabase


    @Override
    protected TokenCreator createLabelIdCreator()
    {
        DelegateInvocationHandler<TokenCreator> labelIdCreatorDelegate =
                new DelegateInvocationHandler<>();
        TokenCreator labelIdCreator =
                (TokenCreator) Proxy.newProxyInstance( TokenCreator.class.getClassLoader(),
                        new Class[]{TokenCreator.class}, labelIdCreatorDelegate );
        new LabelTokenCreatorModeSwitcher( memberStateMachine, labelIdCreatorDelegate,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, logging );
        return labelIdCreator;
    }

    @Override
    protected TokenCreator createLabelIdCreator()
    {
        DelegateInvocationHandler<TokenCreator> labelIdCreatorDelegate =
                new DelegateInvocationHandler<TokenCreator>();
        TokenCreator labelIdCreator =
                (TokenCreator) Proxy.newProxyInstance( TokenCreator.class.getClassLoader(),
                        new Class[]{TokenCreator.class}, labelIdCreatorDelegate );
        new LabelTokenCreatorModeSwitcher( memberStateMachine, labelIdCreatorDelegate,
                (HaXaDataSourceManager) xaDataSourceManager, master, requestContextFactory, logging );
        return labelIdCreator;
    }

Replace Generic With Diamond DelegateInvocationHandler<TokenCreator> with DelegateInvocationHandler<> in method protected createLabelIdCreator() : TokenCreator from class org.neo4j.kernel.ha.HighlyAvailableGraphDatabase


    public static void truncateFile( File file, long position ) throws IOException
    {
        try ( RandomAccessFile access = new RandomAccessFile( file, "rw" ) )
        {
            truncateFile( access.getChannel(), position );
        }
    }

    public static void truncateFile( File file, long position ) throws IOException
    {
        RandomAccessFile access = new RandomAccessFile( file, "rw" );
        try
        {
            truncateFile( access.getChannel(), position );
        }
        finally
        {
            access.close();
        }
    }

Try With Resources try(RandomAccessFile access=new RandomAccessFile(file,"rw")) in method public truncateFile(file File, position long) : void from class org.neo4j.kernel.impl.util.FileUtils


    public static void writeToFile( File target, String text, boolean append ) throws IOException
    {
        if ( !target.exists() )
        {
            target.getParentFile().mkdirs();
            target.createNewFile();
        }

        try ( Writer out = new OutputStreamWriter( new FileOutputStream( target, append ), "UTF-8" ) )
        {
            out.write( text );
        }
    }

    public static void writeToFile( File target, String text, boolean append ) throws IOException
    {
        if ( !target.exists() )
        {
            target.getParentFile().mkdirs();
            target.createNewFile();
        }

        Writer out = new OutputStreamWriter( new FileOutputStream( target, append ), "UTF-8" );
        try
        {
            out.write( text );
        }
        finally
        {
            out.close();
        }
    }

Try With Resources try(Writer out=new OutputStreamWriter(new FileOutputStream(target,append),"UTF-8")) in method public writeToFile(target File, text String, append boolean) : void from class org.neo4j.kernel.impl.util.FileUtils


    @Test
    public void makeSureLoopsCanBeCreated()
    {
        BatchInserter graphDb = newBatchInserter();
        long startNode = graphDb.createNode( properties );
        long otherNode = graphDb.createNode( properties );
        long selfRelationship = graphDb.createRelationship( startNode, startNode,
                relTypeArray[0], properties );
        long relationship = graphDb.createRelationship( startNode, otherNode,
                relTypeArray[0], properties );
        for ( BatchRelationship rel : graphDb.getRelationships( startNode ) )
        {
            if ( rel.getId() == selfRelationship )
            {
                assertEquals( startNode, rel.getStartNode() );
                assertEquals( startNode, rel.getEndNode() );
            }
            else if ( rel.getId() == relationship )
            {
                assertEquals( startNode, rel.getStartNode() );
                assertEquals( otherNode, rel.getEndNode() );
            }
            else
            {
                fail( "Unexpected relationship " + rel.getId() );
            }
        }

        GraphDatabaseService db = switchToEmbeddedGraphDatabaseService( graphDb );

        try ( Transaction ignored = db.beginTx() )
        {
            Node realStartNode = db.getNodeById( startNode );
            Relationship realSelfRelationship = db.getRelationshipById( selfRelationship );
            Relationship realRelationship = db.getRelationshipById( relationship );
            assertEquals( realSelfRelationship, realStartNode.getSingleRelationship( RelTypes.REL_TYPE1, Direction.INCOMING ) );
            assertEquals( asSet( realSelfRelationship, realRelationship ), asSet( realStartNode.getRelationships( Direction.OUTGOING ) ) );
            assertEquals( asSet( realSelfRelationship, realRelationship ), asSet( realStartNode.getRelationships() ) );
        }
        finally {
            db.shutdown();
        }
    }

    @Test
    public void makeSureLoopsCanBeCreated()
    {
        BatchInserter graphDb = newBatchInserter();
        long startNode = graphDb.createNode( properties );
        long otherNode = graphDb.createNode( properties );
        long selfRelationship = graphDb.createRelationship( startNode, startNode,
                relTypeArray[0], properties );
        long relationship = graphDb.createRelationship( startNode, otherNode,
                relTypeArray[0], properties );
        for ( BatchRelationship rel : graphDb.getRelationships( startNode ) )
        {
            if ( rel.getId() == selfRelationship )
            {
                assertEquals( startNode, rel.getStartNode() );
                assertEquals( startNode, rel.getEndNode() );
            }
            else if ( rel.getId() == relationship )
            {
                assertEquals( startNode, rel.getStartNode() );
                assertEquals( otherNode, rel.getEndNode() );
            }
            else
            {
                fail( "Unexpected relationship " + rel.getId() );
            }
        }

        GraphDatabaseService db = switchToEmbeddedGraphDatabaseService( graphDb );
        Transaction transaction = db.beginTx();
        try
        {
            Node realStartNode = db.getNodeById( startNode );
            Relationship realSelfRelationship = db.getRelationshipById( selfRelationship );
            Relationship realRelationship = db.getRelationshipById( relationship );
            assertEquals( realSelfRelationship, realStartNode.getSingleRelationship( RelTypes.REL_TYPE1, Direction.INCOMING ) );
            assertEquals( asSet( realSelfRelationship, realRelationship ), asSet( realStartNode.getRelationships( Direction.OUTGOING ) ) );
            assertEquals( asSet( realSelfRelationship, realRelationship ), asSet( realStartNode.getRelationships() ) );
        }
        finally {
            transaction.finish();
            db.shutdown();
        }
    }

Try With Resources try(Transaction ignored=db.beginTx()) in method public makeSureLoopsCanBeCreated() : void from class org.neo4j.unsafe.batchinsert.TestBatchInsert


    private Node getNodeInTx( long nodeId, GraphDatabaseService db )
    {
        try ( Transaction ignored = db.beginTx() )
        {
            return db.getNodeById( nodeId );
        }
    }

    private Node getNodeInTx( long nodeId, GraphDatabaseService db )
    {
        Transaction transaction = db.beginTx();
        try
        {
            return db.getNodeById( nodeId );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=db.beginTx()) in method private getNodeInTx(nodeId long, db GraphDatabaseService) : Node from class org.neo4j.unsafe.batchinsert.TestBatchInsert


    @Override
    public RecordReference<RelationshipTypeTokenRecord> relationshipType( int id )
    {
        if ( id < relationshipTypes.length )
        {
            return new DirectRecordReference<>( relationshipTypes[id], this );
        }
        else
        {
            return super.relationshipType( id );
        }
    }

    @Override
    public RecordReference<RelationshipTypeTokenRecord> relationshipType( int id )
    {
        if ( id < relationshipTypes.length )
        {
            return new DirectRecordReference<RelationshipTypeTokenRecord>( relationshipTypes[id], this );
        }
        else
        {
            return super.relationshipType( id );
        }
    }

Replace Generic With Diamond DirectRecordReference<RelationshipTypeTokenRecord> with DirectRecordReference<> in method public relationshipType(id int) : RecordReference<RelationshipTypeTokenRecord> from class org.neo4j.consistency.store.CacheSmallStoresRecordAccess


    @Override
    public RecordReference<PropertyKeyTokenRecord> propertyKey( int id )
    {
        if ( id < propertyKeys.length )
        {
            return new DirectRecordReference<>( propertyKeys[id], this );
        }
        else
        {
            return super.propertyKey( id );
        }
    }

    @Override
    public RecordReference<PropertyKeyTokenRecord> propertyKey( int id )
    {
        if ( id < propertyKeys.length )
        {
            return new DirectRecordReference<PropertyKeyTokenRecord>( propertyKeys[id], this );
        }
        else
        {
            return super.propertyKey( id );
        }
    }

Replace Generic With Diamond DirectRecordReference<PropertyKeyTokenRecord> with DirectRecordReference<> in method public propertyKey(id int) : RecordReference<PropertyKeyTokenRecord> from class org.neo4j.consistency.store.CacheSmallStoresRecordAccess


    @Override
    public RecordReference<LabelTokenRecord> label( int id )
    {
        if ( id < labels.length )
        {
            return new DirectRecordReference<>( labels[id], this );
        }
        else
        {
            return super.label( id );
        }
    }

    @Override
    public RecordReference<LabelTokenRecord> label( int id )
    {
        if ( id < labels.length )
        {
            return new DirectRecordReference<LabelTokenRecord>( labels[id], this );
        }
        else
        {
            return super.label( id );
        }
    }

Replace Generic With Diamond DirectRecordReference<LabelTokenRecord> with DirectRecordReference<> in method public label(id int) : RecordReference<LabelTokenRecord> from class org.neo4j.consistency.store.CacheSmallStoresRecordAccess


        @Override
        protected void generateInitialData( GraphDatabaseService graphDb )
        {
            // TODO: create bigger sample graph here
            try ( org.neo4j.graphdb.Transaction tx = graphDb.beginTx() )
            {
                Node node1 = set( graphDb.createNode() );
                Node node2 = set( graphDb.createNode(), property( "key", "value" ) );
                node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "C" ) );
                tx.success();
            }
        }

        @Override
        protected void generateInitialData( GraphDatabaseService graphDb )
        {
            // TODO: create bigger sample graph here
            org.neo4j.graphdb.Transaction tx = graphDb.beginTx();
            try
            {
                Node node1 = set( graphDb.createNode() );
                Node node2 = set( graphDb.createNode(), property( "key", "value" ) );
                node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "C" ) );
                tx.success();
            }
            finally
            {
                tx.finish();
            }
        }

Try With Resources try(org.neo4j.graphdb.Transaction tx=graphDb.beginTx()) in method protected generateInitialData(graphDb GraphDatabaseService) : void from class org.neo4j.consistency.checking.full.ExecutionOrderIntegrationTest.fixture.new GraphStoreFixture


    private static <R extends AbstractBaseRecord> R add( Map<Long, Delta<R>> records, R record )
    {
        records.put( record.getLongId(), new Delta<>( record ) );
        return record;
    }

    private static <R extends AbstractBaseRecord> R add( Map<Long, Delta<R>> records, R record )
    {
        records.put( record.getLongId(), new Delta<R>( record ) );
        return record;
    }

Replace Generic With Diamond Delta<R> with Delta<> in method private add(records Map<Long,Delta<R>>, record R) : R from class org.neo4j.consistency.store.RecordAccessStub


    private static <R extends AbstractBaseRecord> void add( Map<Long, Delta<R>> records, R oldRecord, R newRecord )
    {
        records.put( newRecord.getLongId(), new Delta<>( oldRecord, newRecord ) );
    }

    private static <R extends AbstractBaseRecord> void add( Map<Long, Delta<R>> records, R oldRecord, R newRecord )
    {
        records.put( newRecord.getLongId(), new Delta<R>( oldRecord, newRecord ) );
    }

Replace Generic With Diamond Delta<R> with Delta<> in method private add(records Map<Long,Delta<R>>, oldRecord R, newRecord R) : void from class org.neo4j.consistency.store.RecordAccessStub


    public <R extends AbstractBaseRecord> R addChange( R oldRecord, R newRecord )
    {
        if ( newRecord instanceof NodeRecord )
        {
            add( nodes, (NodeRecord) oldRecord, (NodeRecord) newRecord );
        }
        else if ( newRecord instanceof RelationshipRecord )
        {
            add( relationships, (RelationshipRecord) oldRecord, (RelationshipRecord) newRecord );
        }
        else if ( newRecord instanceof PropertyRecord )
        {
            add( properties, (PropertyRecord) oldRecord, (PropertyRecord) newRecord );
        }
        else if ( newRecord instanceof DynamicRecord )
        {
            DynamicRecord dyn = (DynamicRecord) newRecord;
            if ( dyn.getType() == PropertyType.STRING.intValue() )
            {
                add( strings, (DynamicRecord) oldRecord, dyn );
            }
            else if ( dyn.getType() == PropertyType.ARRAY.intValue() )
            {
                add( arrays, (DynamicRecord) oldRecord, dyn );
            }
            else if ( dyn.getType() == SCHEMA_RECORD_TYPE )
            {
                add( schemata, (DynamicRecord) oldRecord, dyn );
            }
            else
            {
                throw new IllegalArgumentException( "Invalid dynamic record type" );
            }
        }
        else if ( newRecord instanceof RelationshipTypeTokenRecord )
        {
            add( relationshipTypeTokens, (RelationshipTypeTokenRecord) oldRecord, (RelationshipTypeTokenRecord) newRecord );
        }
        else if ( newRecord instanceof PropertyKeyTokenRecord )
        {
            add( propertyKeyTokens, (PropertyKeyTokenRecord) oldRecord, (PropertyKeyTokenRecord) newRecord );
        }
        else if ( newRecord instanceof NeoStoreRecord )
        {
            this.graph = new Delta<>( (NeoStoreRecord) oldRecord, (NeoStoreRecord) newRecord );
        }
        else
        {
            throw new IllegalArgumentException( "Invalid record type" );
        }
        return newRecord;
    }

    public <R extends AbstractBaseRecord> R addChange( R oldRecord, R newRecord )
    {
        if ( newRecord instanceof NodeRecord )
        {
            add( nodes, (NodeRecord) oldRecord, (NodeRecord) newRecord );
        }
        else if ( newRecord instanceof RelationshipRecord )
        {
            add( relationships, (RelationshipRecord) oldRecord, (RelationshipRecord) newRecord );
        }
        else if ( newRecord instanceof PropertyRecord )
        {
            add( properties, (PropertyRecord) oldRecord, (PropertyRecord) newRecord );
        }
        else if ( newRecord instanceof DynamicRecord )
        {
            DynamicRecord dyn = (DynamicRecord) newRecord;
            if ( dyn.getType() == PropertyType.STRING.intValue() )
            {
                add( strings, (DynamicRecord) oldRecord, dyn );
            }
            else if ( dyn.getType() == PropertyType.ARRAY.intValue() )
            {
                add( arrays, (DynamicRecord) oldRecord, dyn );
            }
            else if ( dyn.getType() == SCHEMA_RECORD_TYPE )
            {
                add( schemata, (DynamicRecord) oldRecord, dyn );
            }
            else
            {
                throw new IllegalArgumentException( "Invalid dynamic record type" );
            }
        }
        else if ( newRecord instanceof RelationshipTypeTokenRecord )
        {
            add( relationshipTypeTokens, (RelationshipTypeTokenRecord) oldRecord, (RelationshipTypeTokenRecord) newRecord );
        }
        else if ( newRecord instanceof PropertyKeyTokenRecord )
        {
            add( propertyKeyTokens, (PropertyKeyTokenRecord) oldRecord, (PropertyKeyTokenRecord) newRecord );
        }
        else if ( newRecord instanceof NeoStoreRecord )
        {
            this.graph = new Delta<NeoStoreRecord>( (NeoStoreRecord) oldRecord, (NeoStoreRecord) newRecord );
        }
        else
        {
            throw new IllegalArgumentException( "Invalid record type" );
        }
        return newRecord;
    }

Replace Generic With Diamond Delta<NeoStoreRecord> with Delta<> in method public addChange(oldRecord R, newRecord R) : R from class org.neo4j.consistency.store.RecordAccessStub


    public <R extends AbstractBaseRecord> R add( R record )
    {
        if ( record instanceof NodeRecord )
        {
            add( nodes, (NodeRecord) record );
        }
        else if ( record instanceof RelationshipRecord )
        {
            add( relationships, (RelationshipRecord) record );
        }
        else if ( record instanceof PropertyRecord )
        {
            add( properties, (PropertyRecord) record );
        }
        else if ( record instanceof DynamicRecord )
        {
            DynamicRecord dyn = (DynamicRecord) record;
            if ( dyn.getType() == PropertyType.STRING.intValue() )
            {
                addString( dyn );
            }
            else if ( dyn.getType() == PropertyType.ARRAY.intValue() )
            {
                addArray( dyn );
            }
            else if ( dyn.getType() == SCHEMA_RECORD_TYPE )
            {
                addSchema( dyn );
            }
            else
            {
                throw new IllegalArgumentException( "Invalid dynamic record type" );
            }
        }
        else if ( record instanceof RelationshipTypeTokenRecord )
        {
            add( relationshipTypeTokens, (RelationshipTypeTokenRecord) record );
        }
        else if ( record instanceof PropertyKeyTokenRecord )
        {
            add( propertyKeyTokens, (PropertyKeyTokenRecord) record );
        }
        else if ( record instanceof LabelTokenRecord )
        {
            add( labelTokens, (LabelTokenRecord) record );
        }
        else if ( record instanceof NeoStoreRecord )
        {
            this.graph = new Delta<>( (NeoStoreRecord) record );
        }
        else
        {
            throw new IllegalArgumentException( "Invalid record type" );
        }
        return record;
    }

    public <R extends AbstractBaseRecord> R add( R record )
    {
        if ( record instanceof NodeRecord )
        {
            add( nodes, (NodeRecord) record );
        }
        else if ( record instanceof RelationshipRecord )
        {
            add( relationships, (RelationshipRecord) record );
        }
        else if ( record instanceof PropertyRecord )
        {
            add( properties, (PropertyRecord) record );
        }
        else if ( record instanceof DynamicRecord )
        {
            DynamicRecord dyn = (DynamicRecord) record;
            if ( dyn.getType() == PropertyType.STRING.intValue() )
            {
                addString( dyn );
            }
            else if ( dyn.getType() == PropertyType.ARRAY.intValue() )
            {
                addArray( dyn );
            }
            else if ( dyn.getType() == SCHEMA_RECORD_TYPE )
            {
                addSchema( dyn );
            }
            else
            {
                throw new IllegalArgumentException( "Invalid dynamic record type" );
            }
        }
        else if ( record instanceof RelationshipTypeTokenRecord )
        {
            add( relationshipTypeTokens, (RelationshipTypeTokenRecord) record );
        }
        else if ( record instanceof PropertyKeyTokenRecord )
        {
            add( propertyKeyTokens, (PropertyKeyTokenRecord) record );
        }
        else if ( record instanceof LabelTokenRecord )
        {
            add( labelTokens, (LabelTokenRecord) record );
        }
        else if ( record instanceof NeoStoreRecord )
        {
            this.graph = new Delta<NeoStoreRecord>( (NeoStoreRecord) record );
        }
        else
        {
            throw new IllegalArgumentException( "Invalid record type" );
        }
        return record;
    }

Replace Generic With Diamond Delta<NeoStoreRecord> with Delta<> in method public add(record R) : R from class org.neo4j.consistency.store.RecordAccessStub


    private <R extends AbstractBaseRecord> DirectRecordReference<R> reference( Map<Long, Delta<R>> records,
                                                                               long id, Version version )
    {
        return new DirectRecordReference<>( record( records, id, version ), this );
    }

    private <R extends AbstractBaseRecord> DirectRecordReference<R> reference( Map<Long, Delta<R>> records,
                                                                               long id, Version version )
    {
        return new DirectRecordReference<R>( record( records, id, version ), this );
    }

Replace Generic With Diamond DirectRecordReference<R> with DirectRecordReference<> in method private reference(records Map<Long,Delta<R>>, id long, version Version) : DirectRecordReference<R> from class org.neo4j.consistency.store.RecordAccessStub


    private void assertNodeAndIndexingExists( HighlyAvailableGraphDatabase db, long nodeId, String key, Object value )
    {
        try (Transaction tx = db.beginTx())
        {
            Node node = db.getNodeById( nodeId );
            assertEquals( "Property '" + key + "'='" + value + "' mismatch on " + node + " for " + db,
                    value, node.getProperty( key ) );
            assertTrue( "Index '" + key + "' not found for " + db, db.index().existsForNodes( key ) );
            assertEquals( "Index '" + key + "'='" + value + "' mismatch on " + node + " for " + db,
                    node, db.index().forNodes( key ).get( key, value ).getSingle() );
        }
    }

    private void assertNodeAndIndexingExists( HighlyAvailableGraphDatabase db, long nodeId, String key, Object value )
    {
        Transaction transaction = db.beginTx();
        try
        {
            Node node = db.getNodeById( nodeId );
            assertEquals( "Property '" + key + "'='" + value + "' mismatch on " + node + " for " + db,
                    value, node.getProperty( key ) );
            assertTrue( "Index '" + key + "' not found for " + db, db.index().existsForNodes( key ) );
            assertEquals( "Index '" + key + "'='" + value + "' mismatch on " + node + " for " + db,
                    node, db.index().forNodes( key ).get( key, value ).getSingle() );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private assertNodeAndIndexingExists(db HighlyAvailableGraphDatabase, nodeId long, key String, value Object) : void from class slavetest.TestStoreCopy


    private static void applyProfileFile( File file, Map<String, Serializable> session ) throws ShellException
    {
        try (FileInputStream fis = new FileInputStream( file ))
        {
            Properties properties = new Properties();
            properties.load( fis );
            for ( Object key : properties.keySet() )
            {
                String stringKey = (String) key;
                String value = properties.getProperty( stringKey );
                session.put( stringKey, value );
            }
        }
        catch ( IOException e )
        {
            throw new IllegalArgumentException( "Couldn't find profile '" +
                    file.getAbsolutePath() + "'" );
        }
    }

    private static void applyProfileFile( File file, Map<String, Serializable> session ) throws ShellException
    {
        InputStream in = null;
        try
        {
            Properties properties = new Properties();
            properties.load( new FileInputStream( file ) );
            for ( Object key : properties.keySet() )
            {
                String stringKey = (String) key;
                String value = properties.getProperty( stringKey );
                session.put( stringKey, value );
            }
        }
        catch ( IOException e )
        {
            throw new IllegalArgumentException( "Couldn't find profile '" +
                    file.getAbsolutePath() + "'" );
        }
        finally
        {
            if ( in != null )
            {
                try
                {
                    in.close();
                }
                catch ( IOException e )
                {
                    // OK
                }
            }
        }
    }

Try With Resources try(FileInputStream fis=new FileInputStream(file)) in method private applyProfileFile(file File, session Map<String,Serializable>) : void from class org.neo4j.shell.StartClient


    @Test
    public void createRelationshipWithArrayProperty() throws Exception
    {
        String type = "ARRAY";
        executeCommand( "mknode --cd" );
        executeCommand( "mkrel -ct " + type + " --rp \"{'values':[1,2,3,4]}\"" );

        try ( Transaction ignored = db.beginTx() )
        {
            assertThat( getCurrentNode().getSingleRelationship( withName( type ), OUTGOING ), inTx( db, hasProperty(
                    "values" ).withValue( new int[]{1, 2, 3, 4} ) ) );
        }
    }

    @Test
    public void createRelationshipWithArrayProperty() throws Exception
    {
        String type = "ARRAY";
        executeCommand( "mknode --cd" );
        executeCommand( "mkrel -ct " + type + " --rp \"{'values':[1,2,3,4]}\"" );
        Transaction transaction = db.beginTx();
        try
        {
            assertThat( getCurrentNode().getSingleRelationship( withName( type ), OUTGOING ), inTx( db, hasProperty(
                    "values" ).withValue( new int[]{1, 2, 3, 4} ) ) );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=db.beginTx()) in method public createRelationshipWithArrayProperty() : void from class org.neo4j.shell.TestApps


    @Test
    public void createRelationshipToNewNodeWithLabels() throws Exception
    {
        String type = "TEST";
        executeCommand( "mknode --cd" );
        executeCommand( "mkrel -ctl " + type + " Person" );

        try ( Transaction ignored = db.beginTx() )
        {
            assertThat( getCurrentNode().getSingleRelationship(
                    withName( type ), OUTGOING ).getEndNode(), inTx( db, hasLabels( "Person" ) ) );
        }
    }

    @Test
    public void createRelationshipToNewNodeWithLabels() throws Exception
    {
        String type = "TEST";
        executeCommand( "mknode --cd" );
        executeCommand( "mkrel -ctl " + type + " Person" );
        Transaction transaction = db.beginTx();
        try
        {
            assertThat( getCurrentNode().getSingleRelationship(
                    withName( type ), OUTGOING ).getEndNode(), inTx( db, hasLabels( "Person" ) ) );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=db.beginTx()) in method public createRelationshipToNewNodeWithLabels() : void from class org.neo4j.shell.TestApps


    @Test
    public void canMeasureSizeOfCache() throws Exception
    {
        long [] before = get( CacheBean.NUMBER_OF_CACHED_ELEMENTS );
        try(Transaction tx = graphDb.beginTx())
        {
            graphDb.createNode();
            tx.success();
        }

        assertChanged( "cache size not updated", before, get( CacheBean.NUMBER_OF_CACHED_ELEMENTS ) );
    }

    @Test
    public void canMeasureSizeOfCache() throws Exception
    {
        long[] before = get( CacheBean.NUMBER_OF_CACHED_ELEMENTS );
        Transaction transaction = graphDb.beginTx();
        try
        {
            graphDb.getReferenceNode();
        }
        finally
        {
            transaction.finish();
        }
        assertChanged( "cache size not updated", before, get( CacheBean.NUMBER_OF_CACHED_ELEMENTS ) );
    }

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


    @Test
    public void modifiedNodeImpliesLock()
    {
        Node node;
        try(Transaction tx = graphDb.beginTx())
        {
            node = graphDb.createNode();
            tx.success();
        }

        try(Transaction ignore = graphDb.beginTx())
        {
            node.setProperty( "key", "value" );

            List<LockInfo> locks = lockManager.getLocks();
            assertEquals( "unexpected lock count", 1, locks.size() );
            LockInfo lock = locks.get( 0 );
            assertNotNull( "null lock", lock );
            Collection<LockingTransaction> transactions = lock.getLockingTransactions();
            assertEquals( "unexpected transaction count", 1, transactions.size() );
            LockingTransaction txInfo = transactions.iterator().next();
            assertNotNull( "null transaction", txInfo );
            assertEquals( "read count", 0, txInfo.getReadCount() );

            /* Before property handling moved from Primitive into the Kernel API there were two
             * locks acquired for setting a property. One was about acquiring a write lock for that entity
             * before even accessing the Primitive. The other one was the normal write lock for a change
             * to an entity. The former guarded for a property data race, which is at the point of writing this
             * unknown if it exists after the move or not (which also made the change to only acquire
             * one lock again). */
            assertEquals( "write count should be 1", 1, txInfo.getWriteCount() );
            assertNotNull( "transaction", txInfo.getTransaction() );

            assertEquals( "read count", 0, lock.getReadCount() );
            assertEquals( "write count", 1, lock.getWriteCount() );

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

    @Test
    public void modifiedNodeImpliesLock()
    {
        Transaction tx = graphDb.beginTx();
        try
        {
            graphDb.getReferenceNode().setProperty( "key", "value" );

            List<LockInfo> locks = lockManager.getLocks();
            assertEquals( "unexpected lock count", 1, locks.size() );
            LockInfo lock = locks.get( 0 );
            assertNotNull( "null lock", lock );
            Collection<LockingTransaction> transactions = lock.getLockingTransactions();
            assertEquals( "unexpected transaction count", 1, transactions.size() );
            LockingTransaction txInfo = transactions.iterator().next();
            assertNotNull( "null transaction", txInfo );
            assertEquals( "read count", 0, txInfo.getReadCount() );

            /* Before property handling moved from Primitive into the Kernel API there were two
             * locks acquired for setting a property. One was about acquiring a write lock for that entity
             * before even accessing the Primitive. The other one was the normal write lock for a change
             * to an entity. The former guarded for a property data race, which is at the point of writing this
             * unknown if it exists after the move or not (which also made the change to only acquire
             * one lock again). */
            assertEquals( "write count should be 1", 1, txInfo.getWriteCount() );
            assertNotNull( "transaction", txInfo.getTransaction() );

            assertEquals( "read count", 0, lock.getReadCount() );
            assertEquals( "write count", 1, lock.getWriteCount() );

            assertEquals( "waiting thread count", 0, lock.getWaitingThreadsCount() );
        }
        finally
        {
            tx.finish();
        }
        List<LockInfo> locks = lockManager.getLocks();
        assertEquals( "unexpected lock count", 0, locks.size() );
    }

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


    @PluginTarget( Node.class )
    public Iterable<Relationship> getRelationshipsBetween( final @Source Node start,
            final @Parameter( name = "other" ) Node end )
    {
        return new FilteringIterable<>( start.getRelationships(), new Predicate<Relationship>()
        {
            @Override
            public boolean accept( Relationship item )
            {
                return item.getOtherNode( start )
                        .equals( end );
            }
        } );
    }

    @PluginTarget( Node.class )
    public Iterable<Relationship> getRelationshipsBetween( final @Source Node start,
            final @Parameter( name = "other" ) Node end )
    {
        return new FilteringIterable<Relationship>( start.getRelationships(), new Predicate<Relationship>()
        {
            @Override
            public boolean accept( Relationship item )
            {
                return item.getOtherNode( start )
                        .equals( end );
            }
        } );
    }

Replace Generic With Diamond FilteringIterable<Relationship> with FilteringIterable<> in method public getRelationshipsBetween(start Node, end Node) : Iterable<Relationship> from class org.neo4j.server.plugins.Plugin


    @PluginTarget( Node.class )
    public Iterable<Relationship> createRelationships( @Source Node start,
            @Parameter( name = "type" ) RelationshipType type, @Parameter( name = "nodes" ) Iterable<Node> nodes )
    {
        List<Relationship> result = new ArrayList<>();
        try(Transaction tx = start.getGraphDatabase().beginTx())
        {
            for ( Node end : nodes )
            {
                result.add( start.createRelationshipTo( end, type ) );
            }
            tx.success();
        }
        return result;
    }

    @PluginTarget( Node.class )
    public Iterable<Relationship> createRelationships( @Source Node start,
            @Parameter( name = "type" ) RelationshipType type, @Parameter( name = "nodes" ) Iterable<Node> nodes )
    {
        List<Relationship> result = new ArrayList<Relationship>();
        Transaction tx = start.getGraphDatabase()
                .beginTx();
        try
        {
            for ( Node end : nodes )
            {
                result.add( start.createRelationshipTo( end, type ) );
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
        return result;
    }

Try With Resources try(Transaction tx=start.getGraphDatabase().beginTx()) in method public createRelationships(start Node, type RelationshipType, nodes Iterable<Node>) : Iterable<Relationship> from class org.neo4j.server.plugins.Plugin


    protected Relationship[] createRelationshipChain( RelationshipType type, int length )
    {
        try(Transaction transaction = db.beginTx())
        {
            Relationship[] relationshipChain = createRelationshipChain( db.createNode(), type, length );
            transaction.success();
            return relationshipChain;
        }
    }

    protected Relationship[] createRelationshipChain( RelationshipType type, int length )
    {
        Transaction transaction = db.beginTx();
        try {
            Relationship[] relationshipChain = createRelationshipChain( db.getReferenceNode(), type, length );
            transaction.success();
            return relationshipChain;
        } finally {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method protected createRelationshipChain(type RelationshipType, length int) : Relationship[] from class org.neo4j.shell.AbstractShellTest


    private Node getNodeByIdInTx( int nodeId )
    {
        try ( Transaction ignored = gdb.beginTx(); )
        {
            return gdb.getNodeById( nodeId );
        }
    }

    private Node getNodeByIdInTx( int nodeId )
    {
        Transaction transaction = gdb.beginTx();
        try {
            return gdb.getNodeById( nodeId );
        } finally {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=gdb.beginTx()) in method private getNodeByIdInTx(nodeId int) : Node from class org.neo4j.cypher.javacompat.CypherUpdateMapTest


    @Test
    public void exampleWithParameterForIndexValue() throws Exception
    {
        try ( Transaction ignored = db.beginTx() )
        {
            // START SNIPPET: exampleWithParameterForIndexValue
            Map<String, Object> params = new HashMap<String, Object>();
            params.put( "value", "Michaela" );
            String query = "START n=node:people(name = {value}) RETURN n";
            ExecutionResult result = engine.execute( query, params );
            // END SNIPPET: exampleWithParameterForIndexValue
            assertEquals( asList( michaelaNode ), this.<Node>toList( result, "n" ) );
            dumpToFile( "exampleWithParameterForIndexValue", query, params );
        }
    }

    @Test
    public void exampleWithParameterForIndexValue() throws Exception
    {
        Transaction transaction = db.beginTx();
        try
        {
            // START SNIPPET: exampleWithParameterForIndexValue
            Map<String, Object> params = new HashMap<String, Object>();
            params.put( "value", "Michaela" );
            String query = "START n=node:people(name = {value}) RETURN n";
            ExecutionResult result = engine.execute( query, params );
            // END SNIPPET: exampleWithParameterForIndexValue
            assertEquals( asList( michaelaNode ), this.<Node>toList( result, "n" ) );
            dumpToFile( "exampleWithParameterForIndexValue", query, params );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=db.beginTx()) in method public exampleWithParameterForIndexValue() : void from class org.neo4j.cypher.javacompat.JavaExecutionEngineDocTest


    @Test
    public void exampleWithParametersForQuery() throws Exception
    {
        try ( Transaction ignored = db.beginTx() )
        {
            // START SNIPPET: exampleWithParametersForQuery
            Map<String, Object> params = new HashMap<String, Object>();
            params.put( "query", "name:Andreas" );
            String query = "START n=node:people({query}) RETURN n";
            ExecutionResult result = engine.execute( query, params );
            // END SNIPPET: exampleWithParametersForQuery
            assertEquals( asList( andreasNode ), this.<Node>toList( result, "n" ) );
            dumpToFile( "exampleWithParametersForQuery", query, params );
        }
    }

    @Test
    public void exampleWithParametersForQuery() throws Exception
    {
        Transaction transaction = db.beginTx();
        try
        {
            // START SNIPPET: exampleWithParametersForQuery
            Map<String, Object> params = new HashMap<String, Object>();
            params.put( "query", "name:Andreas" );
            String query = "START n=node:people({query}) RETURN n";
            ExecutionResult result = engine.execute( query, params );
            // END SNIPPET: exampleWithParametersForQuery
            assertEquals( asList( andreasNode ), this.<Node>toList( result, "n" ) );
            dumpToFile( "exampleWithParametersForQuery", query, params );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=db.beginTx()) in method public exampleWithParametersForQuery() : void from class org.neo4j.cypher.javacompat.JavaExecutionEngineDocTest


    @Override
    public Cache<NodeImpl> newNodeCache( StringLogger logger, Config config )
    {
        return new WeakLruCache<>( NODE_CACHE_NAME );
    }

    @Override
    public Cache<NodeImpl> newNodeCache( StringLogger logger, Config config )
    {
        return new WeakLruCache<NodeImpl>( NODE_CACHE_NAME );
    }

Replace Generic With Diamond WeakLruCache<NodeImpl> with WeakLruCache<> in method public newNodeCache(logger StringLogger, config Config) : Cache<NodeImpl> from class org.neo4j.kernel.impl.cache.WeakCacheProvider


    @Override
    public Cache<RelationshipImpl> newRelationshipCache( StringLogger logger, Config config )
    {
        return new WeakLruCache<>( RELATIONSHIP_CACHE_NAME );
    }

    @Override
    public Cache<RelationshipImpl> newRelationshipCache( StringLogger logger, Config config )
    {
        return new WeakLruCache<RelationshipImpl>( RELATIONSHIP_CACHE_NAME );
    }

Replace Generic With Diamond WeakLruCache<RelationshipImpl> with WeakLruCache<> in method public newRelationshipCache(logger StringLogger, config Config) : Cache<RelationshipImpl> from class org.neo4j.kernel.impl.cache.WeakCacheProvider


    public void beforeCompletion()
    {
        this.transactionData = tm.getTransactionState().getTransactionData();

        try
        {
            if ( tm.getStatus() != Status.STATUS_ACTIVE )
            {
                return;
            }
        }
        catch ( SystemException e )
        {
            e.printStackTrace();
        }

        states = new ArrayList<>();
        handlers.beforeCompletion(transactionData, states);
    }

    public void beforeCompletion()
    {
        this.transactionData = tm.getTransactionState().getTransactionData();

        try
        {
            if ( tm.getStatus() != Status.STATUS_ACTIVE )
            {
                return;
            }
        }
        catch ( SystemException e )
        {
            e.printStackTrace();
        }

        states = new ArrayList<TransactionEventHandlers.HandlerAndState>();
        handlers.beforeCompletion(transactionData, states);
    }

Replace Generic With Diamond ArrayList<TransactionEventHandlers.HandlerAndState> with ArrayList<> in method public beforeCompletion() : void from class org.neo4j.kernel.impl.core.TransactionEventsSyncHook


    /**
     * Recover all datasources
     */
    public void recover( Iterator<List<TxLog.Record>> knownDanglingRecordList )
    {
        // contains NonCompletedTransaction that needs to be committed
        List<NonCompletedTransaction> commitList =
                new ArrayList<NonCompletedTransaction>();

        // contains Xids that should be rolledback
        final List<Xid> rollbackList = new LinkedList<Xid>();

        // key = Resource(branchId) value = XAResource
        final Map<Resource, XaDataSource> resourceMap =
                new HashMap<Resource, XaDataSource>();
        buildRecoveryInfo( commitList, rollbackList, resourceMap,
                knownDanglingRecordList );
        // invoke recover on all xa resources found
        final List<Xid> recoveredXidsList = new LinkedList<Xid>();

        try
        {

            for ( XaDataSource xaDataSource : dataSources.values() )
            {
                XAResource xaRes = xaDataSource.getXaConnection().getXaResource();
                Xid xids[] = xaRes.recover( XAResource.TMNOFLAGS );

                for ( Xid xid : xids )
                {
                    if ( XidImpl.isThisTm( xid.getGlobalTransactionId() ) )
                    {
                        // linear search
                        if ( rollbackList.contains( xid ) )
                        {
                            msgLog.logMessage( "TM: Found pre commit " + xid + " rolling back ... ", true );
                            rollbackList.remove( xid );
                            xaRes.rollback( xid );
                        }
                        else
                        {
                            Resource resource = new Resource( xid.getBranchQualifier() );
                            if ( !resourceMap.containsKey( resource ) )
                            {
                                resourceMap.put( resource, xaDataSource );
                            }
                            recoveredXidsList.add( xid );
                        }
                    }
                    else
                    {
                        msgLog.warn( "Unknown xid: " + xid );
                    }
                }
            }

            // sort the commit list after sequence number
            Collections.sort( commitList );

            // go through and commit
            for ( NonCompletedTransaction nct : commitList )
            {
                int seq = nct.getSequenceNumber();
                Xid xids[] = nct.getXids();
                msgLog.debug( "Marked as commit tx-seq[" + seq +
                              "] branch length: " + xids.length );
                for ( Xid xid : xids )
                {
                    if ( !recoveredXidsList.contains( xid ) )
                    {
                        msgLog.debug( "Tx-seq[" + seq + "][" + xid +
                                      "] not found in recovered xid list, "
                                      + "assuming already committed" );
                        continue;
                    }
                    recoveredXidsList.remove( xid );
                    Resource resource = new Resource( xid.getBranchQualifier() );
                    if ( !resourceMap.containsKey( resource ) )
                    {
                        final TransactionFailureException ex = new TransactionFailureException(
                                "Couldn't find XAResource for " + xid );
                        throw logAndReturn( "TM: recovery error", ex );
                    }
                    msgLog.debug( "TM: Committing tx " + xid );
                    resourceMap.get( resource ).getXaConnection().getXaResource().commit( xid, false );
                }
            }

            // rollback the rest
            for ( Xid xid : recoveredXidsList )
            {
                Resource resource = new Resource( xid.getBranchQualifier() );
                if ( !resourceMap.containsKey( resource ) )
                {
                    final TransactionFailureException ex = new TransactionFailureException(
                            "Couldn't find XAResource for " + xid );
                    throw logAndReturn( "TM: recovery error", ex );
                }
                msgLog.debug( "TM: no match found for " + xid + " removing" );
                resourceMap.get( resource ).getXaConnection().getXaResource().rollback( xid );
            }
            if ( rollbackList.size() > 0 )
            {
                msgLog.debug( "TxLog contained unresolved "
                        + "xids that needed rollback. They couldn't be matched to "
                        + "any of the XAResources recover list. " + "Assuming "
                        + rollbackList.size()
                        + " transactions already rolled back." );
            }

            // Rotate the logs of the participated data sources, making sure that
            // done-records are written so that even if the tm log gets truncated,
            // which it will be after this recovery, that transaction information
            // doesn't get lost.
            for ( XaDataSource participant : MapUtil.reverse( resourceMap ).keySet() )
            {
                participant.rotateLogicalLog();
            }
        }
        catch ( IOException | XAException e )
        {
            throw logAndReturn( "TM: recovery failed", new TransactionFailureException( "Recovery failed.", e ) );
        }
    }

    /**
     * Recover all datasources
     */
    public void recover( Iterator<List<TxLog.Record>> knownDanglingRecordList )
    {
        // contains NonCompletedTransaction that needs to be committed
        List<NonCompletedTransaction> commitList =
                new ArrayList<NonCompletedTransaction>();

        // contains Xids that should be rolledback
        final List<Xid> rollbackList = new LinkedList<Xid>();

        // key = Resource(branchId) value = XAResource
        final Map<Resource, XaDataSource> resourceMap =
                new HashMap<Resource, XaDataSource>();
        buildRecoveryInfo( commitList, rollbackList, resourceMap,
                knownDanglingRecordList );
        // invoke recover on all xa resources found
        final List<Xid> recoveredXidsList = new LinkedList<Xid>();

        try
        {

            for ( XaDataSource xaDataSource : dataSources.values() )
            {
                XAResource xaRes = xaDataSource.getXaConnection().getXaResource();
                Xid xids[] = xaRes.recover( XAResource.TMNOFLAGS );

                for ( Xid xid : xids )
                {
                    if ( XidImpl.isThisTm( xid.getGlobalTransactionId() ) )
                    {
                        // linear search
                        if ( rollbackList.contains( xid ) )
                        {
                            msgLog.logMessage( "TM: Found pre commit " + xid + " rolling back ... ", true );
                            rollbackList.remove( xid );
                            xaRes.rollback( xid );
                        }
                        else
                        {
                            Resource resource = new Resource( xid.getBranchQualifier() );
                            if ( !resourceMap.containsKey( resource ) )
                            {
                                resourceMap.put( resource, xaDataSource );
                            }
                            recoveredXidsList.add( xid );
                        }
                    }
                    else
                    {
                        msgLog.warn( "Unknown xid: " + xid );
                    }
                }
            }

            // sort the commit list after sequence number
            Collections.sort( commitList );

            // go through and commit
            for ( NonCompletedTransaction nct : commitList )
            {
                int seq = nct.getSequenceNumber();
                Xid xids[] = nct.getXids();
                msgLog.debug( "Marked as commit tx-seq[" + seq +
                              "] branch length: " + xids.length );
                for ( Xid xid : xids )
                {
                    if ( !recoveredXidsList.contains( xid ) )
                    {
                        msgLog.debug( "Tx-seq[" + seq + "][" + xid +
                                      "] not found in recovered xid list, "
                                      + "assuming already committed" );
                        continue;
                    }
                    recoveredXidsList.remove( xid );
                    Resource resource = new Resource( xid.getBranchQualifier() );
                    if ( !resourceMap.containsKey( resource ) )
                    {
                        final TransactionFailureException ex = new TransactionFailureException(
                                "Couldn't find XAResource for " + xid );
                        throw logAndReturn( "TM: recovery error", ex );
                    }
                    msgLog.debug( "TM: Committing tx " + xid );
                    resourceMap.get( resource ).getXaConnection().getXaResource().commit( xid, false );
                }
            }

            // rollback the rest
            for ( Xid xid : recoveredXidsList )
            {
                Resource resource = new Resource( xid.getBranchQualifier() );
                if ( !resourceMap.containsKey( resource ) )
                {
                    final TransactionFailureException ex = new TransactionFailureException(
                            "Couldn't find XAResource for " + xid );
                    throw logAndReturn( "TM: recovery error", ex );
                }
                msgLog.debug( "TM: no match found for " + xid + " removing" );
                resourceMap.get( resource ).getXaConnection().getXaResource().rollback( xid );
            }
            if ( rollbackList.size() > 0 )
            {
                msgLog.debug( "TxLog contained unresolved "
                        + "xids that needed rollback. They couldn't be matched to "
                        + "any of the XAResources recover list. " + "Assuming "
                        + rollbackList.size()
                        + " transactions already rolled back." );
            }

            // Rotate the logs of the participated data sources, making sure that
            // done-records are written so that even if the tm log gets truncated,
            // which it will be after this recovery, that transaction information
            // doesn't get lost.
            for ( XaDataSource participant : MapUtil.reverse( resourceMap ).keySet() )
            {
                participant.rotateLogicalLog();
            }
        }
        catch ( IOException e )
        {
            throw logAndReturn( "TM: recovery failed", new TransactionFailureException( "Recovery failed.", e ) );
        }
        catch ( XAException e )
        {
            throw logAndReturn( "TM: recovery failed", new TransactionFailureException( "Recovery failed.", e ) );
        }
    }

Merge Catch [catch(IOException e), catch(XAException e)] to catch(IOException|XAException e) in method public recover(knownDanglingRecordList Iterator<List<TxLog.Record>>) : void from class org.neo4j.kernel.impl.transaction.XaDataSourceManager


    synchronized void checkXids() throws IOException
    {
        msgLog.logMessage( "XaResourceManager[" + name + "] sorting " +
                xidMap.size() + " xids" );
        Iterator<Xid> keyIterator = xidMap.keySet().iterator();
        LinkedList<Xid> xids = new LinkedList<>();
        while ( keyIterator.hasNext() )
        {
            xids.add( keyIterator.next() );
        }
        // comparator only used here
        Collections.sort( xids, new Comparator<Xid>()
        {
            @Override
            public int compare( Xid o1, Xid o2 )
            {

                Integer id1 = txOrderMap.get( o1 );
                Integer id2 = txOrderMap.get( o2 );
                if ( id1 == null && id2 == null )
                {
                    return 0;
                }
                if ( id1 == null )
                {
                    return Integer.MAX_VALUE;
                }
                if ( id2 == null )
                {
                    return Integer.MIN_VALUE;
                }
                return id1 - id2;
            }
        } );
        txOrderMap.clear(); // = null;
        while ( !xids.isEmpty() )
        {
            Xid xid = xids.removeFirst();
            XidStatus status = xidMap.get( xid );
            TransactionStatus txStatus = status.getTransactionStatus();
            XaTransaction xaTransaction = txStatus.getTransaction();
            int identifier = xaTransaction.getIdentifier();
            if ( xaTransaction.isRecovered() )
            {
                if ( txStatus.commitStarted() )
                {
                    msgLog.debug( "Marking 1PC [" + name + "] tx "
                            + identifier + " as done" );
                    log.doneInternal( identifier );
                    xidMap.remove( xid );
                    recoveredTxCount--;
                }
                else if ( !txStatus.prepared() )
                {
                    msgLog.debug( "Rolling back non prepared tx [" + name + "]"
                            + "txIdent[" + identifier + "]" );
                    log.doneInternal( xaTransaction.getIdentifier() );
                    xidMap.remove( xid );
                    recoveredTxCount--;
                }
                else
                {
                    msgLog.debug( "2PC tx [" + name + "] " + txStatus +
                            " txIdent[" + identifier + "]" );
                }
            }
        }
        checkIfRecoveryComplete();
    }

    synchronized void checkXids() throws IOException
    {
        msgLog.logMessage( "XaResourceManager[" + name + "] sorting " +
                xidMap.size() + " xids" );
        Iterator<Xid> keyIterator = xidMap.keySet().iterator();
        LinkedList<Xid> xids = new LinkedList<Xid>();
        while ( keyIterator.hasNext() )
        {
            xids.add( keyIterator.next() );
        }
        // comparator only used here
        Collections.sort( xids, new Comparator<Xid>()
        {
            @Override
            public int compare( Xid o1, Xid o2 )
            {

                Integer id1 = txOrderMap.get( o1 );
                Integer id2 = txOrderMap.get( o2 );
                if ( id1 == null && id2 == null )
                {
                    return 0;
                }
                if ( id1 == null )
                {
                    return Integer.MAX_VALUE;
                }
                if ( id2 == null )
                {
                    return Integer.MIN_VALUE;
                }
                return id1 - id2;
            }
        } );
        txOrderMap.clear(); // = null;
        while ( !xids.isEmpty() )
        {
            Xid xid = xids.removeFirst();
            XidStatus status = xidMap.get( xid );
            TransactionStatus txStatus = status.getTransactionStatus();
            XaTransaction xaTransaction = txStatus.getTransaction();
            int identifier = xaTransaction.getIdentifier();
            if ( xaTransaction.isRecovered() )
            {
                if ( txStatus.commitStarted() )
                {
                    msgLog.debug( "Marking 1PC [" + name + "] tx "
                            + identifier + " as done" );
                    log.doneInternal( identifier );
                    xidMap.remove( xid );
                    recoveredTxCount--;
                }
                else if ( !txStatus.prepared() )
                {
                    msgLog.debug( "Rolling back non prepared tx [" + name + "]"
                            + "txIdent[" + identifier + "]" );
                    log.doneInternal( xaTransaction.getIdentifier() );
                    xidMap.remove( xid );
                    recoveredTxCount--;
                }
                else
                {
                    msgLog.debug( "2PC tx [" + name + "] " + txStatus +
                            " txIdent[" + identifier + "]" );
                }
            }
        }
        checkIfRecoveryComplete();
    }

Replace Generic With Diamond LinkedList<Xid> with LinkedList<> in method package checkXids() : void from class org.neo4j.kernel.impl.transaction.xaframework.XaResourceManager


    private Iterable<TransactionInfo> sortByTxId( Collection<TransactionInfo> set )
    {
        List<TransactionInfo> list = new ArrayList<>( set );
        Collections.sort( list );
        return list;
    }

    private Iterable<TransactionInfo> sortByTxId( Collection<TransactionInfo> set )
    {
        List<TransactionInfo> list = new ArrayList<TransactionInfo>( set );
        Collections.sort( list );
        return list;
    }

Replace Generic With Diamond ArrayList<TransactionInfo> with ArrayList<> in method private sortByTxId(set Collection<TransactionInfo>) : Iterable<TransactionInfo> from class org.neo4j.kernel.impl.transaction.xaframework.XaResourceManager


    @Test
    public void shouldBeAbleToSetRelationshipProperties() throws Exception
    {
        long relationshipId = graphdbHelper.createRelationship( "KNOWS" );
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 10 );
        actions.setAllRelationshipProperties( relationshipId, properties );
        assertEquals( properties, graphdbHelper.getRelationshipProperties( relationshipId ) );
    }

    @Test
    public void shouldBeAbleToSetRelationshipProperties() throws Exception
    {
        long relationshipId = graphdbHelper.createRelationship( "KNOWS" );
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 10 );
        actions.setAllRelationshipProperties( relationshipId, properties );
        assertEquals( properties, graphdbHelper.getRelationshipProperties( relationshipId ) );
    }

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


    private void assertIndexedValues( Hit... expectedHits ) throws IOException
    {
        switchToVerification();

        for ( Hit hit : expectedHits )
        {
            TopDocs hits = searcher.search( documentLogic.newQuery( hit.value ), 10 );
            assertEquals( "Unexpected number of index results from " + hit.value, hit.nodeIds.length, hits.totalHits );
            Set<Long> foundNodeIds = new HashSet<>();
            for ( int i = 0; i < hits.totalHits; i++ )
            {
                Document document = searcher.doc( hits.scoreDocs[i].doc );
                foundNodeIds.add( parseLong( document.get( "id" ) ) );
            }
            assertEquals( asSet( hit.nodeIds ), foundNodeIds );
        }
    }

    private void assertIndexedValues( Hit... expectedHits ) throws IOException
    {
        switchToVerification();

        for ( Hit hit : expectedHits )
        {
            TopDocs hits = searcher.search( documentLogic.newQuery( hit.value ), 10 );
            assertEquals( "Unexpected number of index results from " + hit.value, hit.nodeIds.length, hits.totalHits );
            Set<Long> foundNodeIds = new HashSet<Long>();
            for ( int i = 0; i < hits.totalHits; i++ )
            {
                Document document = searcher.doc( hits.scoreDocs[i].doc );
                foundNodeIds.add( parseLong( document.get( "id" ) ) );
            }
            assertEquals( asSet( hit.nodeIds ), foundNodeIds );
        }
    }

Replace Generic With Diamond HashSet<Long> with HashSet<> in method private assertIndexedValues(expectedHits Hit...) : void from class org.neo4j.kernel.api.impl.index.LuceneSchemaIndexPopulatorTest


    public ContractCheckingIndexProxy( IndexProxy delegate, boolean started )
    {
        super( delegate );
        this.state = new AtomicReference<>( started ? State.STARTED : State.INIT );
        this.openCalls = new AtomicInteger( 0 );
    }

    public ContractCheckingIndexProxy( IndexProxy delegate, boolean started )
    {
        super( delegate );
        this.state = new AtomicReference<State>( started ? State.STARTED : State.INIT );
        this.openCalls = new AtomicInteger( 0 );
    }

Replace Generic With Diamond AtomicReference<State> with AtomicReference<> in method public ContractCheckingIndexProxy(delegate IndexProxy, started boolean) from class org.neo4j.kernel.impl.api.index.ContractCheckingIndexProxy


    private void removeLabels( Node node, Label... labels )
    {
        try ( Transaction tx = dbRule.getGraphDatabaseService().beginTx() )
        {
            for ( Label label : labels )
            {
                node.removeLabel( label );
            }
            tx.success();
        }
    }

    private void removeLabels( Node node, Label... labels )
    {
        Transaction tx = dbRule.getGraphDatabaseService().beginTx();
        try
        {
            for ( Label label : labels )
            {
                node.removeLabel( label );
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=dbRule.getGraphDatabaseService().beginTx()) in method private removeLabels(node Node, labels Label...) : void from class org.neo4j.graphdb.LabelScanStoreIT


    private void deleteNode( Node node )
    {
        try ( Transaction tx = dbRule.getGraphDatabaseService().beginTx() )
        {
            node.delete();
            tx.success();
        }
    }

    private void deleteNode( Node node )
    {
        Transaction tx = dbRule.getGraphDatabaseService().beginTx();
        try
        {
            node.delete();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=dbRule.getGraphDatabaseService().beginTx()) in method private deleteNode(node Node) : void from class org.neo4j.graphdb.LabelScanStoreIT


    private Set<Node> getAllNodesWithLabel( Label label )
    {
        try ( Transaction tx = dbRule.getGraphDatabaseService().beginTx() )
        {
            return asSet( GlobalGraphOperations.at( dbRule.getGraphDatabaseService() ).getAllNodesWithLabel( label ) );
        }
    }

    private Set<Node> getAllNodesWithLabel( Label label )
    {
        Transaction tx = dbRule.getGraphDatabaseService().beginTx();
        try
        {
            return asSet( GlobalGraphOperations.at( dbRule.getGraphDatabaseService() ).getAllNodesWithLabel( label ) );
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=dbRule.getGraphDatabaseService().beginTx()) in method private getAllNodesWithLabel(label Label) : Set<Node> from class org.neo4j.graphdb.LabelScanStoreIT


    private Node createLabeledNode( Label... labels )
    {
        try ( Transaction tx = dbRule.getGraphDatabaseService().beginTx() )
        {
            Node node = dbRule.getGraphDatabaseService().createNode( labels );
            tx.success();
            return node;
        }
    }

    private Node createLabeledNode( Label... labels )
    {
        Transaction tx = dbRule.getGraphDatabaseService().beginTx();
        try
        {
            Node node = dbRule.getGraphDatabaseService().createNode( labels );
            tx.success();
            return node;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=dbRule.getGraphDatabaseService().beginTx()) in method private createLabeledNode(labels Label...) : Node from class org.neo4j.graphdb.LabelScanStoreIT


    private void addLabels( Node node, Label... labels )
    {
        try ( Transaction tx = dbRule.getGraphDatabaseService().beginTx() )
        {
            for ( Label label : labels )
            {
                node.addLabel( label );
            }
            tx.success();
        }
    }

    private void addLabels( Node node, Label... labels )
    {
        Transaction tx = dbRule.getGraphDatabaseService().beginTx();
        try
        {
            for ( Label label : labels )
            {
                node.addLabel( label );
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=dbRule.getGraphDatabaseService().beginTx()) in method private addLabels(node Node, labels Label...) : void from class org.neo4j.graphdb.LabelScanStoreIT


    static List<Image> loadIcons()
    {
        List<Image> icons = new ArrayList<>();
        for ( int i = MIN_SIZE; i <= MAX_SIZE; i *= 2 )
        {
            Image image = loadImage( format( LOGO_PATTERN, i ) );
            if ( null != image )
            {
                icons.add( image );
            }
        }
        return icons;
    }

    static List<Image> loadIcons()
    {
        List<Image> icons = new ArrayList<Image>();
        for ( int i = MIN_SIZE; i <= MAX_SIZE; i *= 2 )
        {
            Image image = loadImage( format( LOGO_PATTERN, i ) );
            if ( null != image )
            {
                icons.add( image );
            }
        }
        return icons;
    }

Replace Generic With Diamond ArrayList<Image> with ArrayList<> in method package loadIcons() : List<Image> from class org.neo4j.desktop.ui.Graphics


    @SuppressWarnings("unchecked")
    static Representation getIteratorRepresentation( Iterator data )
    {
        final FirstItemIterable<Representation> results = new FirstItemIterable<>(new IteratorWrapper<Representation, Object>(data) {
            @Override
            protected Representation underlyingObjectToObject(Object value) {
                if ( value instanceof Iterable )
                {
                    FirstItemIterable<Representation> nested = convertValuesToRepresentations( (Iterable) value );
                    return new ListRepresentation( getType( nested ), nested );
                } else {
                    return getSingleRepresentation( value );
                }
            }
        });
        return new ListRepresentation( getType( results ), results );
    }

    static Representation getIteratorRepresentation( Iterator data )
    {
        final FirstItemIterable<Representation> results = new FirstItemIterable<Representation>(new IteratorWrapper<Representation, Object>(data) {
            @Override
            protected Representation underlyingObjectToObject(Object value) {
                if ( value instanceof Iterable )
                {
                    FirstItemIterable<Representation> nested = convertValuesToRepresentations( (Iterable) value );
                    return new ListRepresentation( getType( nested ), nested );
                } else {
                    return getSingleRepresentation( value );
                }
            }
        });
        return new ListRepresentation( getType( results ), results );
    }

Replace Generic With Diamond FirstItemIterable<Representation> with FirstItemIterable<> in method package getIteratorRepresentation(data Iterator) : Representation from class org.neo4j.server.rest.repr.ObjectToRepresentationConverter


    @SuppressWarnings("unchecked")
    static FirstItemIterable<Representation> convertValuesToRepresentations( Iterable data )
    {
        return new FirstItemIterable<>(new IterableWrapper<Representation,Object>(data) {
            @Override
            protected Representation underlyingObjectToObject(Object value) {
               return convert(value);
            }
        });
    }

    static FirstItemIterable<Representation> convertValuesToRepresentations( Iterable data )
    {
        return new FirstItemIterable<Representation>(new IterableWrapper<Representation,Object>(data) {
            @Override
            protected Representation underlyingObjectToObject(Object value) {
               return convert(value);
            }
        });
    }

Replace Generic With Diamond FirstItemIterable<Representation> with FirstItemIterable<> in method package convertValuesToRepresentations(data Iterable) : FirstItemIterable<Representation> from class org.neo4j.server.rest.repr.ObjectToRepresentationConverter


    protected static Map<String, Object> parseJSONMap( String jsonString )
        throws JSONException
	{
        JSONObject object = new JSONObject( jsonString );
        Map<String, Object> result = new HashMap<>();
        for ( String name : JSONObject.getNames( object ) )
        {
            Object value = object.get( name );
            if ( value != null && value instanceof String &&
                ( ( String ) value ).length() == 0 )
            {
                value = null;
            }
            result.put( name, value );
        }
        return result;
	}

    protected static Map<String, Object> parseJSONMap( String jsonString )
        throws JSONException
	{
        JSONObject object = new JSONObject( jsonString );
        Map<String, Object> result = new HashMap<String, Object>();
        for ( String name : JSONObject.getNames( object ) )
        {
            Object value = object.get( name );
            if ( value != null && value instanceof String &&
                ( ( String ) value ).length() == 0 )
            {
                value = null;
            }
            result.put( name, value );
        }
        return result;
	}

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method protected parseJSONMap(jsonString String) : Map<String,Object> from class org.neo4j.shell.impl.AbstractApp


    @Test
    public void indexNumbers() throws Exception
    {
        BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProviderNewImpl( inserter );
        BatchInserterIndex index = provider.nodeIndex( "mine", EXACT_CONFIG );

        long id = inserter.createNode( null );
        Map<String, Object> props = new HashMap<>();
        props.put( "key", 123L );
        index.add( id, props );
        index.flush();

        assertEquals( 1, index.get( "key", 123L ).size() );
        assertEquals( 1, index.get( "key", "123" ).size() );

        provider.shutdown();
    }

    @Test
    public void indexNumbers() throws Exception
    {
        BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProviderNewImpl( inserter );
        BatchInserterIndex index = provider.nodeIndex( "mine", EXACT_CONFIG );

        long id = inserter.createNode( null );
        Map<String, Object> props = new HashMap<String, Object>();
        props.put( "key", 123L );
        index.add( id, props );
        index.flush();

        assertEquals( 1, index.get( "key", 123L ).size() );
        assertEquals( 1, index.get( "key", "123" ).size() );

        provider.shutdown();
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public indexNumbers() : void from class org.neo4j.unsafe.batchinsert.TestLuceneBatchInsert


    @Test
    public void shouldCreateAutoIndexThatIsUsableInEmbedded() throws Exception
    {
        BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProviderNewImpl( inserter );
        BatchInserterIndex index = provider.nodeIndex( "node_auto_index", EXACT_CONFIG );

        long id = inserter.createNode( null );
        Map<String, Object> props = new HashMap<>();
        props.put( "name", "peter" );
        index.add( id, props );
        index.flush();
        provider.shutdown();
        shutdownInserter();

        switchToGraphDatabaseService( configure( GraphDatabaseSettings.node_keys_indexable, "name" ),
                configure( GraphDatabaseSettings.relationship_keys_indexable, "relProp1,relProp2" ),
                configure( GraphDatabaseSettings.node_auto_indexing, "true" ),
                configure( GraphDatabaseSettings.relationship_auto_indexing, "true" ) );
        try ( Transaction tx = db.beginTx() )
        {
            // Create the primitives
            Node node1 = db.createNode();

            // Add indexable and non-indexable properties
            node1.setProperty( "name", "bob" );

            // Make things persistent
            tx.success();
        }

        try ( Transaction tx = db.beginTx() )
        {
            assertTrue( db.index().getNodeAutoIndexer().getAutoIndex().get( "name", "peter" ).hasNext() );
            assertTrue( db.index().getNodeAutoIndexer().getAutoIndex().get( "name", "bob" ).hasNext() );
            assertFalse( db.index().getNodeAutoIndexer().getAutoIndex().get( "name", "joe" ).hasNext() );
            tx.success();
        }
    }

    @Test
    public void shouldCreateAutoIndexThatIsUsableInEmbedded() throws Exception
    {
        BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProviderNewImpl( inserter );
        BatchInserterIndex index = provider.nodeIndex( "node_auto_index", EXACT_CONFIG );

        long id = inserter.createNode( null );
        Map<String, Object> props = new HashMap<String, Object>();
        props.put( "name", "peter" );
        index.add( id, props );
        index.flush();
        provider.shutdown();
        shutdownInserter();

        switchToGraphDatabaseService( configure( GraphDatabaseSettings.node_keys_indexable, "name" ),
                configure( GraphDatabaseSettings.relationship_keys_indexable, "relProp1,relProp2" ),
                configure( GraphDatabaseSettings.node_auto_indexing, "true" ),
                configure( GraphDatabaseSettings.relationship_auto_indexing, "true" ) );
        Transaction tx = db.beginTx();
        try
        {
            // Create the primitives
            Node node1 = db.createNode();

            // Add indexable and non-indexable properties
            node1.setProperty( "name", "bob" );

            // Make things persistent
            tx.success();
        }
        finally
        {
            tx.finish();
        }

        tx = db.beginTx();
        assertTrue(db.index().getNodeAutoIndexer().getAutoIndex().get( "name", "peter" ).hasNext());
        assertTrue(db.index().getNodeAutoIndexer().getAutoIndex().get( "name", "bob" ).hasNext());
        assertFalse(db.index().getNodeAutoIndexer().getAutoIndex().get( "name", "joe" ).hasNext());
        tx.finish();
    }

Try With Resources try(Transaction tx=db.beginTx()) in method public shouldCreateAutoIndexThatIsUsableInEmbedded() : void from class org.neo4j.unsafe.batchinsert.TestLuceneBatchInsert


    @Test
    public void shouldKeepAroundUnusedIndexesAfterConsecutiveInsertion() throws Exception
    {
        // GIVEN -- a batch insertion creating two indexes
        String indexName1 = "first", indexName2 = "second", key = "name";
        {
            BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProvider( inserter );
            BatchInserterIndex index1 = provider.nodeIndex( indexName1, LuceneIndexImplementation.EXACT_CONFIG );
            index1.add( 0, map( key, "Mattias" ) );
            BatchInserterIndex index2 = provider.nodeIndex( indexName1, LuceneIndexImplementation.EXACT_CONFIG );
            index2.add( 0, map( key, "Mattias" ) );
            provider.shutdown();
            shutdownInserter();
        }

        // WHEN -- doing a second insertion, only adding to the second index
        {
            startInserter();
            BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProvider( inserter );
            BatchInserterIndex index2 = provider.nodeIndex( indexName2, LuceneIndexImplementation.EXACT_CONFIG );
            index2.add( 1, map( key, "Mattias" ) );
            provider.shutdown();
            shutdownInserter();
        }

        // THEN -- both indexes should exist when starting up in "graph mode"
        {
            switchToGraphDatabaseService();
            try ( Transaction transaction = db.beginTx() )
            {
                assertTrue( indexName1 + " should exist", db.index().existsForNodes( indexName1 ) );
                assertTrue( indexName2 + " should exist", db.index().existsForNodes( indexName2 ) );
                transaction.success();
            }
        }
    }

    @Test
    public void shouldKeepAroundUnusedIndexesAfterConsecutiveInsertion() throws Exception
    {
        // GIVEN -- a batch insertion creating two indexes
        String indexName1 = "first", indexName2 = "second", key = "name";
        {
            BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProvider( inserter );
            BatchInserterIndex index1 = provider.nodeIndex( indexName1, LuceneIndexImplementation.EXACT_CONFIG );
            index1.add( 0, map( key, "Mattias" ) );
            BatchInserterIndex index2 = provider.nodeIndex( indexName1, LuceneIndexImplementation.EXACT_CONFIG );
            index2.add( 0, map( key, "Mattias" ) );
            provider.shutdown();
            shutdownInserter();
        }

        // WHEN -- doing a second insertion, only adding to the second index
        {
            startInserter();
            BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProvider( inserter );
            BatchInserterIndex index2 = provider.nodeIndex( indexName2, LuceneIndexImplementation.EXACT_CONFIG );
            index2.add( 1, map( key, "Mattias" ) );
            provider.shutdown();
            shutdownInserter();
        }

        // THEN -- both indexes should exist when starting up in "graph mode"
        {
            switchToGraphDatabaseService();
            Transaction transaction = db.beginTx();
            try
            {
                assertTrue( indexName1 + " should exist", db.index().existsForNodes( indexName1 ) );
                assertTrue( indexName2 + " should exist", db.index().existsForNodes( indexName2 ) );
            }
            finally
            {
                transaction.finish();
            }
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method public shouldKeepAroundUnusedIndexesAfterConsecutiveInsertion() : void from class org.neo4j.unsafe.batchinsert.TestLuceneBatchInsert


    @Before
    public void setup()
    {
        cache = new GCResistantCache<>( new AtomicReferenceArray<Entity>( 10 ) );
    }

    @Before
    public void setup()
    {
        cache = new GCResistantCache<Entity>( new AtomicReferenceArray<Entity>( 10 ) );
    }

Replace Generic With Diamond GCResistantCache<Entity> with GCResistantCache<> in method public setup() : void from class org.neo4j.kernel.impl.cache.TestGCResistantCache


    private Set<NodePropertyUpdate> createSomeBananas( Label label )
    {
        Set<NodePropertyUpdate> updates = new HashSet<>();
        try ( Transaction tx = db.beginTx() )
        {
            ThreadToStatementContextBridge ctxProvider = db.getDependencyResolver().resolveDependency(
                    ThreadToStatementContextBridge.class );
            try ( Statement statement = ctxProvider.statement() )
            {
                for ( int number : new int[] {4, 10} )
                {
                    Node node = db.createNode( label );
                    node.setProperty( key, number );
                    updates.add( NodePropertyUpdate.add( node.getId(),
                            statement.readOperations().propertyKeyGetForName( key ), number,
                            new long[]{statement.readOperations().labelGetForName( label.name() )} ) );
                }
            }
            tx.success();
            return updates;
        }
    }

    private Set<NodePropertyUpdate> createSomeBananas( Label label )
            throws PropertyKeyNotFoundException, LabelNotFoundKernelException
    {
        Set<NodePropertyUpdate> updates = new HashSet<>();
        Transaction tx = db.beginTx();
        try
        {
            ThreadToStatementContextBridge ctxProvider = db.getDependencyResolver().resolveDependency(
                    ThreadToStatementContextBridge.class );
            Statement statement = ctxProvider.statement();
            for ( int number : new int[] {4, 10} )
            {
                Node node = db.createNode( label );
                node.setProperty( key, number );
                updates.add( NodePropertyUpdate.add( node.getId(), statement.readOperations().propertyKeyGetForName(
                        key ), number,
                        new long[]{statement.readOperations().labelGetForName( label.name() )} ) );
            }
            statement.close();
            tx.success();
            return updates;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Statement statement=ctxProvider.statement()) in method private createSomeBananas(label Label) : Set<NodePropertyUpdate> from class org.neo4j.kernel.impl.api.index.IndexRecoveryIT


    @Test
    @Graph( { "a TO b", "b TO c", "c TO a" } )
    public void canCreateGraphFromMultipleStrings() throws Exception
    {
        Map<String, Node> graph = data.get();
        Set<Node> unique = new HashSet<Node>();
        Node n = graph.get( "a" );
        while ( unique.add( n ) )
        {
            try(Transaction ignored = graphdb.beginTx())
            {
                n = n.getSingleRelationship(
                        DynamicRelationshipType.withName( "TO" ),
                        Direction.OUTGOING ).getEndNode();
            }
        }
        assertEquals( graph.size(), unique.size() );
    }

    @Test
    @Graph( { "a TO b", "b TO c", "c TO a" } )
    public void canCreateGraphFromMultipleStrings() throws Exception
    {
        Map<String, Node> graph = data.get();
        Set<Node> unique = new HashSet<Node>();
        Node n = graph.get( "a" );
        while ( unique.add( n ) )
        {
            Transaction transaction = graphdb.beginTx();
            try
            {
                n = n.getSingleRelationship(
                        DynamicRelationshipType.withName( "TO" ),
                        Direction.OUTGOING ).getEndNode();
            }
            finally
            {
                transaction.finish();
            }
        }
        assertEquals( graph.size(), unique.size() );
    }

Try With Resources try(Transaction ignored=graphdb.beginTx()) in method public canCreateGraphFromMultipleStrings() : void from class org.neo4j.metatest.TestGraphDescription


    @Test
    @Graph( { "a:Person EATS b:Banana" } )
    public void ensurePeopleCanEatBananas() throws Exception
    {
        Map<String, Node> graph = data.get();
        Node a = graph.get( "a" );
        Node b = graph.get( "b" );

        try(Transaction ignored = graphdb.beginTx())
        {
            assertTrue( a.hasLabel( label( "Person" ) ) );
            assertTrue( b.hasLabel( label( "Banana" ) ) );
        }
    }

    @Test
    @Graph( { "a:Person EATS b:Banana" } )
    public void ensurePeopleCanEatBananas() throws Exception
    {
        Map<String, Node> graph = data.get();
        Node a = graph.get( "a" );
        Node b = graph.get( "b" );

        Transaction transaction = graphdb.beginTx();
        try
        {
            assertTrue( a.hasLabel( label( "Person" ) ) );
            assertTrue( b.hasLabel( label( "Banana" ) ) );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=graphdb.beginTx()) in method public ensurePeopleCanEatBananas() : void from class org.neo4j.metatest.TestGraphDescription


    @Test
    @Graph( { "a:Person EATS b:Banana", "a EATS b:Apple" } )
    public void ensurePeopleCanEatBananasAndApples() throws Exception
    {
        Map<String, Node> graph = data.get();
        Node a = graph.get( "a" );
        Node b = graph.get( "b" );

        try(Transaction ignored = graphdb.beginTx())
        {
            assertTrue( "Person label missing", a.hasLabel( label( "Person" ) ) );
            assertTrue( "Banana label missing", b.hasLabel( label( "Banana" ) ) );
            assertTrue( "Apple label missing", b.hasLabel( label( "Apple" ) ) );
        }
    }

    @Test
    @Graph( { "a:Person EATS b:Banana", "a EATS b:Apple" } )
    public void ensurePeopleCanEatBananasAndApples() throws Exception
    {
        Map<String, Node> graph = data.get();
        Node a = graph.get( "a" );
        Node b = graph.get( "b" );

        Transaction transaction = graphdb.beginTx();
        try
        {
            assertTrue( "Person label missing", a.hasLabel( label( "Person" ) ) );
            assertTrue( "Banana label missing", b.hasLabel( label( "Banana" ) ) );
            assertTrue( "Apple label missing", b.hasLabel( label( "Apple" ) ) );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=graphdb.beginTx()) in method public ensurePeopleCanEatBananasAndApples() : void from class org.neo4j.metatest.TestGraphDescription


    @Test
    @Graph( value = { "I know you" }, autoIndexNodes=true )
    public void canAutoIndexNodes() throws Exception
    {
        data.get();

        try(Transaction ignored = graphdb.beginTx())
        {
            assertTrue(
                    "can't look up node.",
                    graphdb().index().getNodeAutoIndexer().getAutoIndex().get(
                            "name", "I" ).hasNext() );
        }
    }

    @Test
    @Graph( value = { "I know you" }, autoIndexNodes=true )
    public void canAutoIndexNodes() throws Exception
    {
        data.get();

        Transaction transaction = graphdb.beginTx();
        try
        {
            assertTrue(
                    "can't look up node.",
                    graphdb().index().getNodeAutoIndexer().getAutoIndex().get(
                            "name", "I" ).hasNext() );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=graphdb.beginTx()) in method public canAutoIndexNodes() : void from class org.neo4j.metatest.TestGraphDescription


    @Test
    @Graph( nodes = { @NODE( name = "I", setNameProperty=true, properties = {
                    @PROP( key = "name", value = "I" )})}, autoIndexNodes=true )
    public void canAutoIndexNodesExplicitProps() throws Exception
    {
        data.get();

        try(Transaction ignored = graphdb.beginTx())
        {
            assertTrue(
                    "can't look up node.",
                    graphdb().index().getNodeAutoIndexer().getAutoIndex().get(
                            "name", "I" ).hasNext() );
        }
    }

    @Test
    @Graph( nodes = { @NODE( name = "I", setNameProperty=true, properties = {
                    @PROP( key = "name", value = "I" )})}, autoIndexNodes=true )
    public void canAutoIndexNodesExplicitProps() throws Exception
    {
        data.get();

        Transaction transaction = graphdb.beginTx();
        try
        {
            assertTrue(
                    "can't look up node.",
                    graphdb().index().getNodeAutoIndexer().getAutoIndex().get(
                            "name", "I" ).hasNext() );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction ignored=graphdb.beginTx()) in method public canAutoIndexNodesExplicitProps() : void from class org.neo4j.metatest.TestGraphDescription