    @Override
    public InternalIndexState getInitialState( long indexId )
    {
        try
        {
            String failure = failureStorage.loadIndexFailure( indexId );
            if ( failure != null )
            {
                return InternalIndexState.FAILED;
            }

            try ( Directory directory = directoryFactory.open( folderLayout.getFolder( indexId ) ) )
            {
                boolean status = writerStatus.isOnline( directory );
                return status ? InternalIndexState.ONLINE : InternalIndexState.POPULATING;
            }
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

    @Override
    public InternalIndexState getInitialState( long indexId )
    {
        try
        {
            String failure = failureStorage.loadIndexFailure( indexId );
            if ( failure != null )
            {
                return InternalIndexState.FAILED;
            }

            Directory directory = directoryFactory.open( folderLayout.getFolder( indexId ) );
            try
            {
                boolean status = writerStatus.isOnline( directory );
                return status ? InternalIndexState.ONLINE : InternalIndexState.POPULATING;
            }
            finally
            {
                directory.close();
            }
        }
        catch ( IOException e )
        {
            throw new RuntimeException( e );
        }
    }

Try With Resources try(Directory directory=directoryFactory.open(folderLayout.getFolder(indexId))) in method public getInitialState(indexId long) : InternalIndexState from class org.neo4j.kernel.api.impl.index.LuceneSchemaIndexProvider


    private Map<Object, Node> createSomeData( GraphDatabaseService db )
    {
        try ( Transaction tx = db.beginTx() )
        {
            Map<Object, Node> result = new HashMap<>();
            for ( int i = 0; i < 10; i++ )
            {
                Node node = db.createNode( label );
                Object propertyValue = i;
                node.setProperty( key, propertyValue );
                result.put( propertyValue, node );
            }
            tx.success();
            return result;
        }
    }

    private Map<Object, Node> createSomeData( GraphDatabaseService db )
    {
        Map<Object, Node> result = new HashMap<Object, Node>();
        Transaction tx = db.beginTx();
        try
        {
            for ( int i = 0; i < 10; i++ )
            {
                Node node = db.createNode( label );
                Object propertyValue = i;
                node.setProperty( key, propertyValue );
                result.put( propertyValue, node );
            }
            tx.success();
            return result;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private createSomeData(db GraphDatabaseService) : Map<Object,Node> from class org.neo4j.kernel.api.SchemaIndexHaIT


    private static void awaitIndexOnline( IndexDefinition requestedIndex, GraphDatabaseService db,
            Map<Object, Node> expectedData ) throws InterruptedException
    {
        try ( Transaction tx = db.beginTx() )
        {
            IndexDefinition index = reHomedIndexDefinition( db, requestedIndex );

            long timeout = System.currentTimeMillis() + SECONDS.toMillis( 60 );
            while( !indexOnline( index, db ) )
            {
                Thread.sleep( 1 );
                if ( System.currentTimeMillis() > timeout )
                {
                    fail( "Expected index to come online within a reasonable time." );
                }
            }

            assertIndexContents( index, db, expectedData );
            tx.success();
        }
    }

    private static void awaitIndexOnline( IndexDefinition requestedIndex, GraphDatabaseService db,
            Map<Object, Node> expectedData ) throws InterruptedException
    {
        Transaction transaction = db.beginTx();
        try
        {
            IndexDefinition index = reHomedIndexDefinition( db, requestedIndex );

            long timeout = System.currentTimeMillis() + SECONDS.toMillis( 60 );
            while( !indexOnline( index, db ) )
            {
                Thread.sleep( 1 );
                if ( System.currentTimeMillis() > timeout )
                {
                    fail( "Expected index to come online within a reasonable time." );
                }
            }

            assertIndexContents( index, db, expectedData );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private awaitIndexOnline(requestedIndex IndexDefinition, db GraphDatabaseService, expectedData Map<Object,Node>) : void from class org.neo4j.kernel.api.SchemaIndexHaIT


    /**
     * Create read only database.
     */
    @Before
    public void prepareReadOnlyDatabase() throws IOException
    {
        File dir = new File( "target/read-only-db/location" );
        if ( dir.exists() )
        {
            FileUtils.deleteRecursively( dir );
        }
        new GraphDatabaseFactory().newEmbeddedDatabase(
                "target/read-only-db/location" )
                .shutdown();
        // START SNIPPET: createReadOnlyInstance
        Map<String, String> config = new HashMap<>();
        config.put( "read_only", "true" );
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(
                "target/read-only-db/location" )
                .setConfig( config )
                .newGraphDatabase();
        // END SNIPPET: createReadOnlyInstance
    }

    /**
     * Create read only database.
     */
    @Before
    public void prepareReadOnlyDatabase() throws IOException
    {
        File dir = new File( "target/read-only-db/location" );
        if ( dir.exists() )
        {
            FileUtils.deleteRecursively( dir );
        }
        new GraphDatabaseFactory().newEmbeddedDatabase(
                "target/read-only-db/location" )
                .shutdown();
        // START SNIPPET: createReadOnlyInstance
        Map<String, String> config = new HashMap<String, String>();
        config.put( "read_only", "true" );
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(
                "target/read-only-db/location" )
                .setConfig( config )
                .newGraphDatabase();
        // END SNIPPET: createReadOnlyInstance
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public prepareReadOnlyDatabase() : void from class org.neo4j.examples.ReadOnlyDocTest


    @SuppressWarnings("unchecked")
    public Iterator<Node> getAllNodes()
    {
        Iterator<Node> committedNodes = new PrefetchingIterator<Node>()
        {
            private long highId = getHighestPossibleIdInUse( Node.class );
            private long currentId;

            @Override
            protected Node fetchNextOrNull()
            {
                while ( true )
                {   // This outer loop is for checking if highId has changed since we started.
                    while ( currentId <= highId )
                    {
                        try
                        {
                            Node node = getNodeByIdOrNull( currentId );
                            if ( node != null )
                            {
                                return node;
                            }
                        }
                        finally
                        {
                            currentId++;
                        }
                    }

                    long newHighId = getHighestPossibleIdInUse( Node.class );
                    if ( newHighId > highId )
                    {
                        highId = newHighId;
                    }
                    else
                    {
                        break;
                    }
                }
                return null;
            }
        };

        final TransactionState txState = getTransactionState();
        if ( !txState.hasChanges() )
        {
            return committedNodes;
        }

        /* Created nodes are put in the cache right away, even before the transaction is committed.
         * We want this iterator to include nodes that have been created, but not yes committed in
         * this transaction. The thing with the cache is that stuff can be evicted at any point in time
         * so we can't rely on created nodes to be there during the whole life time of this iterator.
         * That's why we filter them out from the "committed/cache" iterator and add them at the end instead.*/
        final Set<Long> createdNodes = new HashSet<>( txState.getCreatedNodes() );
        if ( !createdNodes.isEmpty() )
        {
            committedNodes = new FilteringIterator<>( committedNodes, new Predicate<Node>()
            {
                @Override
                public boolean accept( Node node )
                {
                    return !createdNodes.contains( node.getId() );
                }
            } );
        }

        // Filter out nodes deleted in this transaction
        Iterator<Node> filteredRemovedNodes = new FilteringIterator<>( committedNodes, new Predicate<Node>()
        {
            @Override
            public boolean accept( Node node )
            {
                return !txState.nodeIsDeleted( node.getId() );
            }
        } );

        // Append nodes created in this transaction
        return new CombiningIterator<>( asList( filteredRemovedNodes,
                new IteratorWrapper<Node, Long>( createdNodes.iterator() )
                {
                    @Override
                    protected Node underlyingObjectToObject( Long id )
                    {
                        return getNodeById( id );
                    }
                } ) );
    }

    @SuppressWarnings("unchecked")
    public Iterator<Node> getAllNodes()
    {
        Iterator<Node> committedNodes = new PrefetchingIterator<Node>()
        {
            private long highId = getHighestPossibleIdInUse( Node.class );
            private long currentId;

            @Override
            protected Node fetchNextOrNull()
            {
                while ( true )
                {   // This outer loop is for checking if highId has changed since we started.
                    while ( currentId <= highId )
                    {
                        try
                        {
                            Node node = getNodeByIdOrNull( currentId );
                            if ( node != null )
                            {
                                return node;
                            }
                        }
                        finally
                        {
                            currentId++;
                        }
                    }

                    long newHighId = getHighestPossibleIdInUse( Node.class );
                    if ( newHighId > highId )
                    {
                        highId = newHighId;
                    }
                    else
                    {
                        break;
                    }
                }
                return null;
            }
        };

        final TransactionState txState = getTransactionState();
        if ( !txState.hasChanges() )
        {
            return committedNodes;
        }

        /* Created nodes are put in the cache right away, even before the transaction is committed.
         * We want this iterator to include nodes that have been created, but not yes committed in
         * this transaction. The thing with the cache is that stuff can be evicted at any point in time
         * so we can't rely on created nodes to be there during the whole life time of this iterator.
         * That's why we filter them out from the "committed/cache" iterator and add them at the end instead.*/
        final Set<Long> createdNodes = new HashSet<Long>( txState.getCreatedNodes() );
        if ( !createdNodes.isEmpty() )
        {
            committedNodes = new FilteringIterator<Node>( committedNodes, new Predicate<Node>()
            {
                @Override
                public boolean accept( Node node )
                {
                    return !createdNodes.contains( node.getId() );
                }
            } );
        }

        // Filter out nodes deleted in this transaction
        Iterator<Node> filteredRemovedNodes = new FilteringIterator<Node>( committedNodes, new Predicate<Node>()
        {
            @Override
            public boolean accept( Node node )
            {
                return !txState.nodeIsDeleted( node.getId() );
            }
        } );

        // Append nodes created in this transaction
        return new CombiningIterator<Node>( asList( filteredRemovedNodes,
                new IteratorWrapper<Node, Long>( createdNodes.iterator() )
                {
                    @Override
                    protected Node underlyingObjectToObject( Long id )
                    {
                        return getNodeById( id );
                    }
                } ) );
    }

Replace Generic With Diamond FilteringIterator<Node> with FilteringIterator<> in method public getAllNodes() : Iterator<Node> from class org.neo4j.kernel.impl.core.NodeManager


    public Iterator<Relationship> getAllRelationships()
    {
        Iterator<Relationship> committedRelationships = new PrefetchingIterator<Relationship>()
        {
            private long highId = getHighestPossibleIdInUse( Relationship.class );
            private long currentId;

            @Override
            protected Relationship fetchNextOrNull()
            {
                while ( true )
                {   // This outer loop is for checking if highId has changed since we started.
                    while ( currentId <= highId )
                    {
                        try
                        {
                            Relationship relationship = getRelationshipByIdOrNull( currentId );
                            if ( relationship != null )
                            {
                                return relationship;
                            }
                        }
                        finally
                        {
                            currentId++;
                        }
                    }

                    long newHighId = getHighestPossibleIdInUse( Node.class );
                    if ( newHighId > highId )
                    {
                        highId = newHighId;
                    }
                    else
                    {
                        break;
                    }
                }
                return null;
            }
        };

        final TransactionState txState = getTransactionState();
        if ( !txState.hasChanges() )
        {
            return committedRelationships;
        }

        /* Created relationships are put in the cache right away, even before the transaction is committed.
         * We want this iterator to include relationships that have been created, but not yes committed in
         * this transaction. The thing with the cache is that stuff can be evicted at any point in time
         * so we can't rely on created relationships to be there during the whole life time of this iterator.
         * That's why we filter them out from the "committed/cache" iterator and add them at the end instead.*/
        final Set<Long> createdRelationships = new HashSet<>( txState.getCreatedRelationships() );
        if ( !createdRelationships.isEmpty() )
        {
            committedRelationships = new FilteringIterator<>( committedRelationships,
                    new Predicate<Relationship>()
                    {
                        @Override
                        public boolean accept( Relationship relationship )
                        {
                            return !createdRelationships.contains( relationship.getId() );
                        }
                    } );
        }

        // Filter out relationships deleted in this transaction
        Iterator<Relationship> filteredRemovedRelationships =
                new FilteringIterator<>( committedRelationships, new Predicate<Relationship>()
                {
                    @Override
                    public boolean accept( Relationship relationship )
                    {
                        return !txState.relationshipIsDeleted( relationship.getId() );
                    }
                } );

        // Append relationships created in this transaction
        return new CombiningIterator<>( asList( filteredRemovedRelationships,
                new IteratorWrapper<Relationship, Long>( createdRelationships.iterator() )
                {
                    @Override
                    protected Relationship underlyingObjectToObject( Long id )
                    {
                        return getRelationshipById( id );
                    }
                } ) );
    }

    public Iterator<Relationship> getAllRelationships()
    {
        Iterator<Relationship> committedRelationships = new PrefetchingIterator<Relationship>()
        {
            private long highId = getHighestPossibleIdInUse( Relationship.class );
            private long currentId;

            @Override
            protected Relationship fetchNextOrNull()
            {
                while ( true )
                {   // This outer loop is for checking if highId has changed since we started.
                    while ( currentId <= highId )
                    {
                        try
                        {
                            Relationship relationship = getRelationshipByIdOrNull( currentId );
                            if ( relationship != null )
                            {
                                return relationship;
                            }
                        }
                        finally
                        {
                            currentId++;
                        }
                    }

                    long newHighId = getHighestPossibleIdInUse( Node.class );
                    if ( newHighId > highId )
                    {
                        highId = newHighId;
                    }
                    else
                    {
                        break;
                    }
                }
                return null;
            }
        };

        final TransactionState txState = getTransactionState();
        if ( !txState.hasChanges() )
        {
            return committedRelationships;
        }

        /* Created relationships are put in the cache right away, even before the transaction is committed.
         * We want this iterator to include relationships that have been created, but not yes committed in
         * this transaction. The thing with the cache is that stuff can be evicted at any point in time
         * so we can't rely on created relationships to be there during the whole life time of this iterator.
         * That's why we filter them out from the "committed/cache" iterator and add them at the end instead.*/
        final Set<Long> createdRelationships = new HashSet<Long>( txState.getCreatedRelationships() );
        if ( !createdRelationships.isEmpty() )
        {
            committedRelationships = new FilteringIterator<Relationship>( committedRelationships,
                    new Predicate<Relationship>()
                    {
                        @Override
                        public boolean accept( Relationship relationship )
                        {
                            return !createdRelationships.contains( relationship.getId() );
                        }
                    } );
        }

        // Filter out relationships deleted in this transaction
        Iterator<Relationship> filteredRemovedRelationships =
                new FilteringIterator<Relationship>( committedRelationships, new Predicate<Relationship>()
                {
                    @Override
                    public boolean accept( Relationship relationship )
                    {
                        return !txState.relationshipIsDeleted( relationship.getId() );
                    }
                } );

        // Append relationships created in this transaction
        return new CombiningIterator<Relationship>( asList( filteredRemovedRelationships,
                new IteratorWrapper<Relationship, Long>( createdRelationships.iterator() )
                {
                    @Override
                    protected Relationship underlyingObjectToObject( Long id )
                    {
                        return getRelationshipById( id );
                    }
                } ) );
    }

Replace Generic With Diamond FilteringIterator<Relationship> with FilteringIterator<> in method public getAllRelationships() : Iterator<Relationship> from class org.neo4j.kernel.impl.core.NodeManager


    public static void main( final String[] args )
    {
        deleteFileOrDirectory( new File( DB_PATH ) );
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
        indexService = graphDb.index().forNodes( "nodes" );
        registerShutdownHook();
        try ( Transaction tx = graphDb.beginTx() )
        {
            /*
             *  (Neo) --> (Trinity)
             *     \       ^
             *      v     /
             *    (Morpheus) --> (Cypher)
             *            \         |
             *             v        v
             *            (Agent Smith)
             */
            createChain( "Neo", "Trinity" );
            createChain( "Neo", "Morpheus", "Trinity" );
            createChain( "Morpheus", "Cypher", "Agent Smith" );
            createChain( "Morpheus", "Agent Smith" );
            tx.success();
        }

        // So let's find the shortest path between Neo and Agent Smith
        Node neo = getOrCreateNode( "Neo" );
        Node agentSmith = getOrCreateNode( "Agent Smith" );
        // START SNIPPET: shortestPathUsage
        PathFinder<Path> finder = GraphAlgoFactory.shortestPath(
                Traversal.expanderForTypes( KNOWS, Direction.BOTH ), 4 );
        Path foundPath = finder.findSinglePath( neo, agentSmith );
        System.out.println( "Path from Neo to Agent Smith: "
                            + Traversal.simplePathToString( foundPath, NAME_KEY ) );
        // END SNIPPET: shortestPathUsage

        System.out.println( "Shutting down database ..." );
        graphDb.shutdown();
    }

    public static void main( final String[] args )
    {
        deleteFileOrDirectory( new File( DB_PATH ) );
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
        indexService = graphDb.index().forNodes( "nodes" );
        registerShutdownHook();
        Transaction tx = graphDb.beginTx();
        try
        {
            /*
             *  (Neo) --> (Trinity)
             *     \       ^
             *      v     /
             *    (Morpheus) --> (Cypher)
             *            \         |
             *             v        v
             *            (Agent Smith)
             */
            createChain( "Neo", "Trinity" );
            createChain( "Neo", "Morpheus", "Trinity" );
            createChain( "Morpheus", "Cypher", "Agent Smith" );
            createChain( "Morpheus", "Agent Smith" );
            tx.success();
        }
        finally
        {
            tx.finish();
        }

        // So let's find the shortest path between Neo and Agent Smith
        Node neo = getOrCreateNode( "Neo" );
        Node agentSmith = getOrCreateNode( "Agent Smith" );
        // START SNIPPET: shortestPathUsage
        PathFinder<Path> finder = GraphAlgoFactory.shortestPath(
                Traversal.expanderForTypes( KNOWS, Direction.BOTH ), 4 );
        Path foundPath = finder.findSinglePath( neo, agentSmith );
        System.out.println( "Path from Neo to Agent Smith: "
                            + Traversal.simplePathToString( foundPath, NAME_KEY ) );
        // END SNIPPET: shortestPathUsage

        System.out.println( "Shutting down database ..." );
        graphDb.shutdown();
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public main(args String[]) : void from class org.neo4j.examples.CalculateShortestPath


    private void createRelationshipsInGraphdb( String sourceEntity,
            String sourceMatchAttribute, String targetEntity,
            String targetMatchAttribute, Object[][] relationships,
            String relationshipType )
    {
        try ( Transaction tx = graphdb.beginTx() )
        {
            RelationshipType type = DynamicRelationshipType.withName( relationshipType );
            Index<Node> sourceIndex = graphdb.index()
                    .forNodes( sourceEntity );
            Index<Node> targetIndex = graphdb.index()
                    .forNodes( targetEntity );
            for ( Object[] relationship : relationships )
            {
                Node sourceNode = sourceIndex.get( sourceMatchAttribute,
                        relationship[0] )
                        .getSingle();
                Node targetNode = targetIndex.get( targetMatchAttribute,
                        relationship[1] )
                        .getSingle();
                sourceNode.createRelationshipTo( targetNode, type );
            }
            tx.success();
        }
    }

    private void createRelationshipsInGraphdb( String sourceEntity,
            String sourceMatchAttribute, String targetEntity,
            String targetMatchAttribute, Object[][] relationships,
            String relationshipType )
    {
        Transaction tx = graphdb.beginTx();
        try
        {
            RelationshipType type = DynamicRelationshipType.withName( relationshipType );
            Index<Node> sourceIndex = graphdb.index()
                    .forNodes( sourceEntity );
            Index<Node> targetIndex = graphdb.index()
                    .forNodes( targetEntity );
            for ( Object[] relationship : relationships )
            {
                Node sourceNode = sourceIndex.get( sourceMatchAttribute,
                        relationship[0] )
                        .getSingle();
                Node targetNode = targetIndex.get( targetMatchAttribute,
                        relationship[1] )
                        .getSingle();
                sourceNode.createRelationshipTo( targetNode, type );
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=graphdb.beginTx()) in method private createRelationshipsInGraphdb(sourceEntity String, sourceMatchAttribute String, targetEntity String, targetMatchAttribute String, relationships Object[][], relationshipType String) : void from class org.neo4j.examples.CypherSql


    private void insertIntoGraphdb( String tableName, String[] fields,
            Object[][] values )
    {
        try ( Transaction tx = graphdb.beginTx() )
        {
            Index<Node> index = graphdb.index()
                    .forNodes( tableName );
            for ( Object[] value : values )
            {
                Node node = graphdb.createNode();
                for ( int i = 0; i < fields.length; i++ )
                {
                    node.setProperty( fields[i], value[i] );
                    if ( i == 0 )
                    {
                        index.add( node, fields[i], value[i] );
                    }
                }
            }

            tx.success();
        }
    }

    private void insertIntoGraphdb( String tableName, String[] fields,
            Object[][] values ) throws SQLException
    {
        Transaction tx = graphdb.beginTx();
        try
        {
            Index<Node> index = graphdb.index()
                    .forNodes( tableName );
            for ( Object[] value : values )
            {
                Node node = graphdb.createNode();
                for ( int i = 0; i < fields.length; i++ )
                {
                    node.setProperty( fields[i], value[i] );
                    if ( i == 0 )
                    {
                        index.add( node, fields[i], value[i] );
                    }
                }
            }

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

Try With Resources try(Transaction tx=graphdb.beginTx()) in method private insertIntoGraphdb(tableName String, fields String[], values Object[][]) : void from class org.neo4j.examples.CypherSql


    private void createTable( String name, String definition )
            throws SQLException
    {
        String sql = "CREATE TABLE " + identifierQuoteString + name
                     + identifierQuoteString + "(" + definition + ")";

        try ( Statement statement = sqldb.createStatement() )
        {
            statement.execute( sql );
        }
    }

    private void createTable( String name, String definition )
            throws SQLException
    {
        String sql = "CREATE TABLE " + identifierQuoteString + name
                     + identifierQuoteString + "(" + definition + ")";

        Statement statement = sqldb.createStatement();
        try
        {
            statement.execute( sql );
        } finally
        {
            statement.close();
        }
    }

Try With Resources try(Statement statement=sqldb.createStatement()) in method private createTable(name String, definition String) : void from class org.neo4j.examples.CypherSql


    String executeCypher( String cypher )
    {
        try ( Transaction transaction = graphdb.beginTx() )
        {
            ExecutionResult executionResult = engine.execute( cypher );
            return executionResult.dumpToString();
        }
    }

    String executeCypher( String cypher )
    {
        Transaction transaction = graphdb.beginTx();
        try
        {
            ExecutionResult executionResult = engine.execute( cypher );
            return executionResult.dumpToString();
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=graphdb.beginTx()) in method package executeCypher(cypher String) : String from class org.neo4j.examples.CypherSql


    String executeSql( String sql ) throws SQLException
    {
        StringBuilder builder = new StringBuilder( 512 );
        try ( Statement statement = sqldb.createStatement() )
        {
            if ( statement.execute( sql ) )
            {
                try ( ResultSet result = statement.getResultSet() )
                {
                    ResultSetMetaData meta = result.getMetaData();
                    int rowCount = 0;
                    int columnCount = meta.getColumnCount();
                    String line = new String( new char[columnCount] ).replace( "\0",
                            "+" + LINE_SEGMENT ) + "+\n";
                    builder.append( line );

                    for ( int i = 1; i <= columnCount; i++ )
                    {
                        String output = meta.getColumnLabel( i );
                        printColumn( builder, output );
                    }
                    builder.append( "|\n" )
                            .append( line );
                    while ( result.next() )
                    {
                        rowCount++;
                        for ( int i = 1; i <= columnCount; i++ )
                        {
                            String output = result.getString( i );
                            printColumn( builder, output );
                        }
                        builder.append( "|\n" );
                    }

                    builder.append( line )
                            .append( rowCount )
                            .append( " rows\n" );
                }
            }
            else
            {
                throw new RuntimeException( "Couldn't execute: " + sql );
            }
        }
        return builder.toString();
    }

    String executeSql( String sql ) throws SQLException
    {
        StringBuilder builder = new StringBuilder( 512 );
        Statement statement = null;
        try
        {
            statement = sqldb.createStatement();
            if ( statement.execute( sql ) )
            {
                ResultSet result = null;
                try
                {
                    result  = statement.getResultSet();

                    ResultSetMetaData meta = result.getMetaData();
                    int rowCount = 0;
                    int columnCount = meta.getColumnCount();
                    String line = new String( new char[columnCount] ).replace( "\0",
                            "+" + LINE_SEGMENT ) + "+\n";
                    builder.append( line );

                    for ( int i = 1; i <= columnCount; i++ )
                    {
                        String output = meta.getColumnLabel( i );
                        printColumn( builder, output );
                    }
                    builder.append( "|\n" )
                            .append( line );
                    while ( result.next() )
                    {
                        rowCount++;
                        for ( int i = 1; i <= columnCount; i++ )
                        {
                            String output = result.getString( i );
                            printColumn( builder, output );
                        }
                        builder.append( "|\n" );
                    }

                    builder.append( line )
                            .append( rowCount )
                            .append( " rows\n" );
                } finally
                {
                    if(result != null)
                    {
                        result.close();
                    }
                }
            }
            else
            {
                throw new RuntimeException( "Couldn't execute: " + sql );
            }
        } finally
        {
            if(statement != null)
            {
                statement.close();
            }
        }
        return builder.toString();
    }

Try With Resources try(ResultSet result=statement.getResultSet()) in method package executeSql(sql String) : String from class org.neo4j.examples.CypherSql


    void createDb()
    {
        clearDb();
        // START SNIPPET: startDb
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
        registerShutdownHook( graphDb );
        // END SNIPPET: startDb

        // START SNIPPET: transaction
        try ( Transaction tx = graphDb.beginTx() )
        {
            // Updating operations go here
            // END SNIPPET: transaction
            // START SNIPPET: addData
            firstNode = graphDb.createNode();
            firstNode.setProperty( "message", "Hello, " );
            secondNode = graphDb.createNode();
            secondNode.setProperty( "message", "World!" );

            relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
            relationship.setProperty( "message", "brave Neo4j " );
            // END SNIPPET: addData

            // START SNIPPET: readData
            System.out.print( firstNode.getProperty( "message" ) );
            System.out.print( relationship.getProperty( "message" ) );
            System.out.print( secondNode.getProperty( "message" ) );
            // END SNIPPET: readData

            greeting = ( (String) firstNode.getProperty( "message" ) )
                       + ( (String) relationship.getProperty( "message" ) )
                       + ( (String) secondNode.getProperty( "message" ) );

            // START SNIPPET: transaction
            tx.success();
        }
        // END SNIPPET: transaction
    }

    void createDb()
    {
        clearDb();
        // START SNIPPET: startDb
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
        registerShutdownHook( graphDb );
        // END SNIPPET: startDb

        // START SNIPPET: transaction
        Transaction tx = graphDb.beginTx();
        try
        {
            // Updating operations go here
            // END SNIPPET: transaction
            // START SNIPPET: addData
            firstNode = graphDb.createNode();
            firstNode.setProperty( "message", "Hello, " );
            secondNode = graphDb.createNode();
            secondNode.setProperty( "message", "World!" );

            relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
            relationship.setProperty( "message", "brave Neo4j " );
            // END SNIPPET: addData

            // START SNIPPET: readData
            System.out.print( firstNode.getProperty( "message" ) );
            System.out.print( relationship.getProperty( "message" ) );
            System.out.print( secondNode.getProperty( "message" ) );
            // END SNIPPET: readData

            greeting = ( (String) firstNode.getProperty( "message" ) )
                       + ( (String) relationship.getProperty( "message" ) )
                       + ( (String) secondNode.getProperty( "message" ) );

            // START SNIPPET: transaction
            tx.success();
        }
        finally
        {
            tx.finish();
        }
        // END SNIPPET: transaction
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method package createDb() : void from class org.neo4j.examples.EmbeddedNeo4j


    void removeData()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // START SNIPPET: removingData
            // let's remove the data
            firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
            firstNode.delete();
            secondNode.delete();
            // END SNIPPET: removingData

            tx.success();
        }
    }

    void removeData()
    {
        Transaction tx = graphDb.beginTx();
        try
        {
            // START SNIPPET: removingData
            // let's remove the data
            firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
            firstNode.delete();
            secondNode.delete();
            // END SNIPPET: removingData

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

Try With Resources try(Transaction tx=graphDb.beginTx()) in method package removeData() : void from class org.neo4j.examples.EmbeddedNeo4j


    public static void main( final String[] args )
    {
        // START SNIPPET: startDb
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
        registerShutdownHook();
        // END SNIPPET: startDb

        // START SNIPPET: addUsers
        try ( Transaction tx = graphDb.beginTx() )
        {
            nodeIndex = graphDb.index().forNodes( "nodes" );
            // Create some users and index their names with the IndexService
            for ( int id = 0; id < 100; id++ )
            {
                createAndIndexUser( idToUserName( id ) );
            }
            // END SNIPPET: addUsers

            // Find a user through the search index
            // START SNIPPET: findUser
            int idToFind = 45;
            String userName = idToUserName( idToFind );
            Node foundUser = nodeIndex.get( USERNAME_KEY, userName ).getSingle();

            System.out.println( "The username of user " + idToFind + " is "
                + foundUser.getProperty( USERNAME_KEY ) );
            // END SNIPPET: findUser

            // Delete the persons and remove them from the index
            for ( Node user : nodeIndex.query( USERNAME_KEY, "*" ) )
            {
                nodeIndex.remove(  user, USERNAME_KEY,
                        user.getProperty( USERNAME_KEY ) );
                user.delete();
            }
            tx.success();
        }
        shutdown();
    }

    public static void main( final String[] args )
    {
        // START SNIPPET: startDb
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
        registerShutdownHook();
        // END SNIPPET: startDb

        // START SNIPPET: addUsers
        Transaction tx = graphDb.beginTx();
        try
        {
            nodeIndex = graphDb.index().forNodes( "nodes" );
            // Create some users and index their names with the IndexService
            for ( int id = 0; id < 100; id++ )
            {
                createAndIndexUser( idToUserName( id ) );
            }
            // END SNIPPET: addUsers

            // Find a user through the search index
            // START SNIPPET: findUser
            int idToFind = 45;
            String userName = idToUserName( idToFind );
            Node foundUser = nodeIndex.get( USERNAME_KEY, userName ).getSingle();

            System.out.println( "The username of user " + idToFind + " is "
                + foundUser.getProperty( USERNAME_KEY ) );
            // END SNIPPET: findUser

            // Delete the persons and remove them from the index
            for ( Node user : nodeIndex.query( USERNAME_KEY, "*" ) )
            {
                nodeIndex.remove(  user, USERNAME_KEY,
                        user.getProperty( USERNAME_KEY ) );
                user.delete();
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
        shutdown();
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public main(args String[]) : void from class org.neo4j.examples.EmbeddedNeo4jWithIndexing


    public void createNodespace()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // Create base Matrix node
            Node matrix = graphDb.createNode();
            matrixNodeId = matrix.getId();

            // Create Neo
            Node thomas = graphDb.createNode();
            thomas.setProperty( "name", "Thomas Anderson" );
            thomas.setProperty( "age", 29 );

            // connect Neo/Thomas to the reference node
            matrix.createRelationshipTo( thomas, RelTypes.NEO_NODE );

            Node trinity = graphDb.createNode();
            trinity.setProperty( "name", "Trinity" );
            Relationship rel = thomas.createRelationshipTo( trinity,
                    RelTypes.KNOWS );
            rel.setProperty( "age", "3 days" );
            Node morpheus = graphDb.createNode();
            morpheus.setProperty( "name", "Morpheus" );
            morpheus.setProperty( "rank", "Captain" );
            morpheus.setProperty( "occupation", "Total badass" );
            thomas.createRelationshipTo( morpheus, RelTypes.KNOWS );
            rel = morpheus.createRelationshipTo( trinity, RelTypes.KNOWS );
            rel.setProperty( "age", "12 years" );
            Node cypher = graphDb.createNode();
            cypher.setProperty( "name", "Cypher" );
            cypher.setProperty( "last name", "Reagan" );
            trinity.createRelationshipTo( cypher, RelTypes.KNOWS );
            rel = morpheus.createRelationshipTo( cypher, RelTypes.KNOWS );
            rel.setProperty( "disclosure", "public" );
            Node smith = graphDb.createNode();
            smith.setProperty( "name", "Agent Smith" );
            smith.setProperty( "version", "1.0b" );
            smith.setProperty( "language", "C++" );
            rel = cypher.createRelationshipTo( smith, RelTypes.KNOWS );
            rel.setProperty( "disclosure", "secret" );
            rel.setProperty( "age", "6 months" );
            Node architect = graphDb.createNode();
            architect.setProperty( "name", "The Architect" );
            smith.createRelationshipTo( architect, RelTypes.CODED_BY );

            tx.success();
        }
    }

    public void createNodespace()
    {
        Transaction tx = graphDb.beginTx();
        try
        {
            // Create base Matrix node
            Node matrix = graphDb.createNode();
            matrixNodeId = matrix.getId();

            // Create Neo
            Node thomas = graphDb.createNode();
            thomas.setProperty( "name", "Thomas Anderson" );
            thomas.setProperty( "age", 29 );

            // connect Neo/Thomas to the reference node
            matrix.createRelationshipTo( thomas, RelTypes.NEO_NODE );

            Node trinity = graphDb.createNode();
            trinity.setProperty( "name", "Trinity" );
            Relationship rel = thomas.createRelationshipTo( trinity,
                    RelTypes.KNOWS );
            rel.setProperty( "age", "3 days" );
            Node morpheus = graphDb.createNode();
            morpheus.setProperty( "name", "Morpheus" );
            morpheus.setProperty( "rank", "Captain" );
            morpheus.setProperty( "occupation", "Total badass" );
            thomas.createRelationshipTo( morpheus, RelTypes.KNOWS );
            rel = morpheus.createRelationshipTo( trinity, RelTypes.KNOWS );
            rel.setProperty( "age", "12 years" );
            Node cypher = graphDb.createNode();
            cypher.setProperty( "name", "Cypher" );
            cypher.setProperty( "last name", "Reagan" );
            trinity.createRelationshipTo( cypher, RelTypes.KNOWS );
            rel = morpheus.createRelationshipTo( cypher, RelTypes.KNOWS );
            rel.setProperty( "disclosure", "public" );
            Node smith = graphDb.createNode();
            smith.setProperty( "name", "Agent Smith" );
            smith.setProperty( "version", "1.0b" );
            smith.setProperty( "language", "C++" );
            rel = cypher.createRelationshipTo( smith, RelTypes.KNOWS );
            rel.setProperty( "disclosure", "secret" );
            rel.setProperty( "age", "6 months" );
            Node architect = graphDb.createNode();
            architect.setProperty( "name", "The Architect" );
            smith.createRelationshipTo( architect, RelTypes.CODED_BY );

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

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public createNodespace() : void from class org.neo4j.examples.Matrix


    public String printNeoFriends()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            Node neoNode = getNeoNode();
            // START SNIPPET: friends-usage
            int numberOfFriends = 0;
            StringBuilder output = new StringBuilder( String.format( "%s's friends:\n", neoNode.getProperty( "name" ) ) );
            Traverser friendsTraverser = getFriends( neoNode );
            for ( Node friendNode : friendsTraverser )
            {
                output.append( String.format( "At depth %d => %s\n",
                        friendsTraverser.currentPosition().depth(),
                        friendNode.getProperty( "name" ) ) );
                numberOfFriends++;
            }
            output.append( String.format( "Number of friends found: %d\n", numberOfFriends ) );
            // END SNIPPET: friends-usage
            return output.toString();
        }
    }

    public String printNeoFriends()
    {
        Transaction transaction = graphDb.beginTx();
        try
        {
            Node neoNode = getNeoNode();
            // START SNIPPET: friends-usage
            int numberOfFriends = 0;
            StringBuilder output = new StringBuilder( String.format( "%s's friends:\n", neoNode.getProperty( "name" ) ) );
            Traverser friendsTraverser = getFriends( neoNode );
            for ( Node friendNode : friendsTraverser )
            {
                output.append( String.format( "At depth %d => %s\n",
                        friendsTraverser.currentPosition().depth(),
                        friendNode.getProperty( "name" ) ) );
                numberOfFriends++;
            }
            output.append( String.format( "Number of friends found: %d\n", numberOfFriends ) );
            // END SNIPPET: friends-usage
            return output.toString();
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public printNeoFriends() : String from class org.neo4j.examples.Matrix


    public String printMatrixHackers()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // START SNIPPET: find--hackers-usage
            StringBuilder output = new StringBuilder("Hackers:\n");
            int numberOfHackers = 0;
            Traverser traverser = findHackers( getNeoNode() );
            for ( Node hackerNode : traverser )
            {
                output.append( String.format( "At depth %d => %s\n",
                        traverser.currentPosition().depth(),
                        hackerNode.getProperty( "name" ) ) );
                numberOfHackers++;
            }
            output.append( String.format( "Number of hackers found: %d\n", numberOfHackers ) );
            // END SNIPPET: find--hackers-usage
            return output.toString();
        }
    }

    public String printMatrixHackers()
    {
        Transaction transaction = graphDb.beginTx();
        try
        {
            // START SNIPPET: find--hackers-usage
            StringBuilder output = new StringBuilder("Hackers:\n");
            int numberOfHackers = 0;
            Traverser traverser = findHackers( getNeoNode() );
            for ( Node hackerNode : traverser )
            {
                output.append( String.format( "At depth %d => %s\n",
                        traverser.currentPosition().depth(),
                        hackerNode.getProperty( "name" ) ) );
                numberOfHackers++;
            }
            output.append( String.format( "Number of hackers found: %d\n", numberOfHackers ) );
            // END SNIPPET: find--hackers-usage
            return output.toString();
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public printMatrixHackers() : String from class org.neo4j.examples.Matrix


    private static void createExampleGraph()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // Create users sub reference node.
            System.out.println( "Creating example graph ..." );
            Random random = new Random();
            Node usersReferenceNode = graphDb.createNode();
            Index<Node> references = graphDb.index().forNodes( "references" );
            usersReferenceNode.setProperty( "reference", "users" );
            references.add( usersReferenceNode, "reference", "users" );
            // Create some users and index their names with the IndexService
            List<Node> users = new ArrayList<Node>();
            for ( int id = 0; id < 100; id++ )
            {
                Node userNode = createUser( formUserName( id ) );
                usersReferenceNode.createRelationshipTo( userNode,
                        RelTypes.USER );
                if ( id > 10 )
                {
                    int numberOfFriends = random.nextInt( 5 );
                    Set<Node> knows = new HashSet<Node>();
                    for ( int i = 0; i < numberOfFriends; i++ )
                    {
                        Node friend = users
                                .get( random.nextInt( users.size() ) );
                        if ( knows.add( friend ) )
                        {
                            userNode.createRelationshipTo( friend,
                                    RelTypes.KNOWS );
                        }
                    }
                }
                users.add( userNode );
            }
            tx.success();
        }
    }

    private static void createExampleGraph()
    {
        Transaction tx = graphDb.beginTx();
        try
        {
            // Create users sub reference node.
            System.out.println( "Creating example graph ..." );
            Random random = new Random();
            Node usersReferenceNode = graphDb.createNode();
            Index<Node> references = graphDb.index().forNodes( "references" );
            usersReferenceNode.setProperty( "reference", "users" );
            references.add( usersReferenceNode, "reference", "users" );
            // Create some users and index their names with the IndexService
            List<Node> users = new ArrayList<Node>();
            for ( int id = 0; id < 100; id++ )
            {
                Node userNode = createUser( formUserName( id ) );
                usersReferenceNode.createRelationshipTo( userNode,
                        RelTypes.USER );
                if ( id > 10 )
                {
                    int numberOfFriends = random.nextInt( 5 );
                    Set<Node> knows = new HashSet<Node>();
                    for ( int i = 0; i < numberOfFriends; i++ )
                    {
                        Node friend = users
                                .get( random.nextInt( users.size() ) );
                        if ( knows.add( friend ) )
                        {
                            userNode.createRelationshipTo( friend,
                                    RelTypes.KNOWS );
                        }
                    }
                }
                users.add( userNode );
            }
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method private createExampleGraph() : void from class org.neo4j.examples.Neo4jShell


    private static void deleteExampleNodeSpace()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // Delete the persons and remove them from the index
            System.out.println( "Deleting example graph ..." );
            Node usersReferenceNode = graphDb.index().forNodes( "references" ).get( "reference", "users" ).getSingle();
            for ( Relationship relationship : usersReferenceNode
                    .getRelationships( RelTypes.USER, Direction.OUTGOING ) )
            {
                Node user = relationship.getEndNode();
                for ( Relationship knowsRelationship : user
                        .getRelationships( RelTypes.KNOWS ) )
                {
                    knowsRelationship.delete();
                }
                user.delete();
                relationship.delete();
            }
            usersReferenceNode.getSingleRelationship( RelTypes.USERS_REFERENCE,
                    Direction.INCOMING ).delete();
            usersReferenceNode.delete();
            tx.success();
        }
    }

    private static void deleteExampleNodeSpace()
    {
        Transaction tx = graphDb.beginTx();
        try
        {
            // Delete the persons and remove them from the index
            System.out.println( "Deleting example graph ..." );
            Node usersReferenceNode = graphDb.index().forNodes( "references" ).get( "reference", "users" ).getSingle();
            for ( Relationship relationship : usersReferenceNode
                    .getRelationships( RelTypes.USER, Direction.OUTGOING ) )
            {
                Node user = relationship.getEndNode();
                for ( Relationship knowsRelationship : user
                        .getRelationships( RelTypes.KNOWS ) )
                {
                    knowsRelationship.delete();
                }
                user.delete();
                relationship.delete();
            }
            usersReferenceNode.getSingleRelationship( RelTypes.USERS_REFERENCE,
                    Direction.INCOMING ).delete();
            usersReferenceNode.delete();
            tx.success();
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method private deleteExampleNodeSpace() : void from class org.neo4j.examples.Neo4jShell


    public void createNodespace()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // Create matrix node
            Node matrix = graphDb.createNode();
            matrixNodeId = matrix.getId();

            // Create Neo
            Node thomas = graphDb.createNode();
            thomas.setProperty( "name", "Thomas Anderson" );
            thomas.setProperty( "age", 29 );

            // connect Neo/Thomas to the reference node
            matrix.createRelationshipTo( thomas, RelTypes.NEO_NODE );

            Node trinity = graphDb.createNode();
            trinity.setProperty( "name", "Trinity" );
            Relationship rel = thomas.createRelationshipTo( trinity,
                    RelTypes.KNOWS );
            rel.setProperty( "age", "3 days" );
            Node morpheus = graphDb.createNode();
            morpheus.setProperty( "name", "Morpheus" );
            morpheus.setProperty( "rank", "Captain" );
            morpheus.setProperty( "occupation", "Total badass" );
            thomas.createRelationshipTo( morpheus, RelTypes.KNOWS );
            rel = morpheus.createRelationshipTo( trinity, RelTypes.KNOWS );
            rel.setProperty( "age", "12 years" );
            Node cypher = graphDb.createNode();
            cypher.setProperty( "name", "Cypher" );
            cypher.setProperty( "last name", "Reagan" );
            trinity.createRelationshipTo( cypher, RelTypes.KNOWS );
            rel = morpheus.createRelationshipTo( cypher, RelTypes.KNOWS );
            rel.setProperty( "disclosure", "public" );
            Node smith = graphDb.createNode();
            smith.setProperty( "name", "Agent Smith" );
            smith.setProperty( "version", "1.0b" );
            smith.setProperty( "language", "C++" );
            rel = cypher.createRelationshipTo( smith, RelTypes.KNOWS );
            rel.setProperty( "disclosure", "secret" );
            rel.setProperty( "age", "6 months" );
            Node architect = graphDb.createNode();
            architect.setProperty( "name", "The Architect" );
            smith.createRelationshipTo( architect, RelTypes.CODED_BY );

            tx.success();
        }
    }

    public void createNodespace()
    {
        Transaction tx = graphDb.beginTx();
        try
        {
            // Create matrix node
            Node matrix = graphDb.createNode();
            matrixNodeId = matrix.getId();

            // Create Neo
            Node thomas = graphDb.createNode();
            thomas.setProperty( "name", "Thomas Anderson" );
            thomas.setProperty( "age", 29 );

            // connect Neo/Thomas to the reference node
            matrix.createRelationshipTo( thomas, RelTypes.NEO_NODE );

            Node trinity = graphDb.createNode();
            trinity.setProperty( "name", "Trinity" );
            Relationship rel = thomas.createRelationshipTo( trinity,
                    RelTypes.KNOWS );
            rel.setProperty( "age", "3 days" );
            Node morpheus = graphDb.createNode();
            morpheus.setProperty( "name", "Morpheus" );
            morpheus.setProperty( "rank", "Captain" );
            morpheus.setProperty( "occupation", "Total badass" );
            thomas.createRelationshipTo( morpheus, RelTypes.KNOWS );
            rel = morpheus.createRelationshipTo( trinity, RelTypes.KNOWS );
            rel.setProperty( "age", "12 years" );
            Node cypher = graphDb.createNode();
            cypher.setProperty( "name", "Cypher" );
            cypher.setProperty( "last name", "Reagan" );
            trinity.createRelationshipTo( cypher, RelTypes.KNOWS );
            rel = morpheus.createRelationshipTo( cypher, RelTypes.KNOWS );
            rel.setProperty( "disclosure", "public" );
            Node smith = graphDb.createNode();
            smith.setProperty( "name", "Agent Smith" );
            smith.setProperty( "version", "1.0b" );
            smith.setProperty( "language", "C++" );
            rel = cypher.createRelationshipTo( smith, RelTypes.KNOWS );
            rel.setProperty( "disclosure", "secret" );
            rel.setProperty( "age", "6 months" );
            Node architect = graphDb.createNode();
            architect.setProperty( "name", "The Architect" );
            smith.createRelationshipTo( architect, RelTypes.CODED_BY );

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

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public createNodespace() : void from class org.neo4j.examples.NewMatrix


    public String printNeoFriends()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            Node neoNode = getNeoNode();
            // START SNIPPET: friends-usage
            int numberOfFriends = 0;
            String output = neoNode.getProperty( "name" ) + "'s friends:\n";
            Traverser friendsTraverser = getFriends( neoNode );
            for ( Path friendPath : friendsTraverser )
            {
                output += "At depth " + friendPath.length() + " => "
                          + friendPath.endNode()
                                  .getProperty( "name" ) + "\n";
                numberOfFriends++;
            }
            output += "Number of friends found: " + numberOfFriends + "\n";
            // END SNIPPET: friends-usage
            return output;
        }
    }

    public String printNeoFriends()
    {
        Transaction transaction = graphDb.beginTx();
        try
        {
            Node neoNode = getNeoNode();
            // START SNIPPET: friends-usage
            int numberOfFriends = 0;
            String output = neoNode.getProperty( "name" ) + "'s friends:\n";
            Traverser friendsTraverser = getFriends( neoNode );
            for ( Path friendPath : friendsTraverser )
            {
                output += "At depth " + friendPath.length() + " => "
                          + friendPath.endNode()
                                  .getProperty( "name" ) + "\n";
                numberOfFriends++;
            }
            output += "Number of friends found: " + numberOfFriends + "\n";
            // END SNIPPET: friends-usage
            return output;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public printNeoFriends() : String from class org.neo4j.examples.NewMatrix


    public String printMatrixHackers()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // START SNIPPET: find--hackers-usage
            String output = "Hackers:\n";
            int numberOfHackers = 0;
            Traverser traverser = findHackers( getNeoNode() );
            for ( Path hackerPath : traverser )
            {
                output += "At depth " + hackerPath.length() + " => "
                          + hackerPath.endNode()
                                  .getProperty( "name" ) + "\n";
                numberOfHackers++;
            }
            output += "Number of hackers found: " + numberOfHackers + "\n";
            // END SNIPPET: find--hackers-usage
            return output;
        }
    }

    public String printMatrixHackers()
    {
        Transaction transaction = graphDb.beginTx();
        try
        {
            // START SNIPPET: find--hackers-usage
            String output = "Hackers:\n";
            int numberOfHackers = 0;
            Traverser traverser = findHackers( getNeoNode() );
            for ( Path hackerPath : traverser )
            {
                output += "At depth " + hackerPath.length() + " => "
                          + hackerPath.endNode()
                                  .getProperty( "name" ) + "\n";
                numberOfHackers++;
            }
            output += "Number of hackers found: " + numberOfHackers + "\n";
            // END SNIPPET: find--hackers-usage
            return output;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public printMatrixHackers() : String from class org.neo4j.examples.NewMatrix


    String printPaths( TraversalDescription td, Node A )
    {
        try ( Transaction transaction = db.beginTx() )
        {
            String output = "";
            // START SNIPPET: printPath
            Traverser traverser = td.traverse( A );
            PathPrinter pathPrinter = new PathPrinter( "name" );
            for ( Path path : traverser )
            {
                output += Traversal.pathToString( path, pathPrinter );
            }
            // END SNIPPET: printPath
            output += "\n";
            return output;
        }
    }

    String printPaths( TraversalDescription td, Node A )
    {
        Transaction transaction = db.beginTx();
        try
        {
            String output = "";
            // START SNIPPET: printPath
            Traverser traverser = td.traverse( A );
            PathPrinter pathPrinter = new PathPrinter( "name" );
            for ( Path path : traverser )
            {
                output += Traversal.pathToString( path, pathPrinter );
            }
            // END SNIPPET: printPath
            output += "\n";
            return output;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=db.beginTx()) in method package printPaths(td TraversalDescription, A Node) : String from class org.neo4j.examples.orderedpath.OrderedPath


        private Node createLockNode()
        {
            // START SNIPPET: prepareLockNode
            try ( Transaction tx = graphdb().beginTx() )
            {
                final Node lockNode = graphdb().createNode();
                tx.success();
                return lockNode;
            }
            // END SNIPPET: prepareLockNode
        }

        private Node createLockNode()
        {
            // START SNIPPET: prepareLockNode
            Transaction tx = graphdb().beginTx();
            try
            {
                final Node lockNode = graphdb().createNode();
                tx.success();
                return lockNode;
            }
            finally
            {
                tx.finish();
            }
            // END SNIPPET: prepareLockNode
        }

Try With Resources try(Transaction tx=graphdb().beginTx()) in method private createLockNode() : Node from class org.neo4j.examples.GetOrCreateDocIT.ThreadRunner


        private UniqueFactory<Node> createUniqueFactory()
        {
            GraphDatabaseService graphDb = graphdb();
            // START SNIPPET: prepareUniqueFactory
            try ( Transaction tx = graphDb.beginTx() )
            {
                UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory( graphDb, "users" )
                {
                    @Override
                    protected void initialize( Node created, Map<String, Object> properties )
                    {
                        created.setProperty( "name", properties.get( "name" ) );
                    }
                };
                return factory;
            }
            // END SNIPPET: prepareUniqueFactory
        }

        private UniqueFactory<Node> createUniqueFactory()
        {
            GraphDatabaseService graphDb = graphdb();
            // START SNIPPET: prepareUniqueFactory
            Transaction transaction = graphDb.beginTx();
            try
            {
                UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory( graphDb, "users" )
                {
                    @Override
                    protected void initialize( Node created, Map<String, Object> properties )
                    {
                        created.setProperty( "name", properties.get( "name" ) );
                    }
                };
                return factory;
            }
            finally
            {
                transaction.finish();
            }
            // END SNIPPET: prepareUniqueFactory
        }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method private createUniqueFactory() : UniqueFactory<Node> from class org.neo4j.examples.GetOrCreateDocIT.ThreadRunner


        private void assertUserExistsUniquely( String username )
        {
            try ( Transaction tx = graphdb().beginTx() )
            {
                assertNotNull( "User '" + username + "' not created.", graphdb().index()
                        .forNodes( "users" )
                        .get( "name", username )
                        .getSingle() );
            }
            catch ( NoSuchElementException e )
            {
                throw new RuntimeException( "User '" + username + "' not created uniquely.", e );
            }
        }

        private void assertUserExistsUniquely( String username )
        {
            Transaction transaction = graphdb().beginTx();
            try
            {
                assertNotNull( "User '" + username + "' not created.", graphdb().index()
                        .forNodes( "users" )
                        .get( "name", username )
                        .getSingle() );
            }
            catch ( NoSuchElementException e )
            {
                throw new RuntimeException( "User '" + username + "' not created uniquely.", e );
            }
            finally {
                transaction.finish();
            }
        }

Try With Resources try(Transaction tx=graphdb().beginTx()) in method private assertUserExistsUniquely(username String) : void from class org.neo4j.examples.GetOrCreateDocIT.ThreadRunner


        @Override
        public void run()
        {
            try
            {
                List<Node> subresult = new ArrayList<>();
                for ( int j = 0; j < numUsers; j++ )
                {
                    subresult.add( impl.getOrCreateUser( getUsername( j ), db, lockNode, uniqueFactory ) );
                }
                this.result = subresult;
            }
            catch ( RuntimeException e )
            {
                failure = e;
                throw e;
            }
        }

        @Override
        public void run()
        {
            try
            {
                List<Node> subresult = new ArrayList<Node>();
                for ( int j = 0; j < numUsers; j++ )
                {
                    subresult.add( impl.getOrCreateUser( getUsername( j ), db, lockNode, uniqueFactory ) );
                }
                this.result = subresult;
            }
            catch ( RuntimeException e )
            {
                failure = e;
                throw e;
            }
        }

Replace Generic With Diamond ArrayList<Node> with ArrayList<> in method public run() : void from class org.neo4j.examples.GetOrCreateDocIT.GetOrCreateTask


    public Node getOrCreateUserPessimistically( String username, GraphDatabaseService graphDb, Node lockNode )
    {
        // START SNIPPET: pessimisticLocking
        try ( Transaction tx = graphDb.beginTx() )
        {
            Index<Node> usersIndex = graphDb.index().forNodes( "users" );
            Node userNode = usersIndex.get( "name", username ).getSingle();
            if ( userNode != null )
            {
                return userNode;
            }

            tx.acquireWriteLock( lockNode );
            userNode = usersIndex.get( "name", username ).getSingle();
            if ( userNode == null )
            {
                userNode = graphDb.createNode();
                userNode.setProperty( "name", username );
                usersIndex.add( userNode, "name", username );
            }
            tx.success();
            return userNode;
        }
        // END SNIPPET: pessimisticLocking
    }

    public Node getOrCreateUserPessimistically( String username, GraphDatabaseService graphDb, Node lockNode )
    {
        // START SNIPPET: pessimisticLocking
        Transaction tx = graphDb.beginTx();
        try
        {
            Index<Node> usersIndex = graphDb.index().forNodes( "users" );
            Node userNode = usersIndex.get( "name", username ).getSingle();
            if ( userNode != null ) return userNode;

            tx.acquireWriteLock( lockNode );
            userNode = usersIndex.get( "name", username ).getSingle();
            if ( userNode == null )
            {
                userNode = graphDb.createNode();
                userNode.setProperty( "name", username );
                usersIndex.add( userNode, "name", username );
            }
            tx.success();
            return userNode;
        }
        finally
        {
            tx.finish();
        }
        // END SNIPPET: pessimisticLocking
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public getOrCreateUserPessimistically(username String, graphDb GraphDatabaseService, lockNode Node) : Node from class org.neo4j.examples.GetOrCreateDocIT


    public Node getOrCreateUserWithUniqueFactory( String username, GraphDatabaseService graphDb,
            UniqueFactory<Node> factory )
    {
        // START SNIPPET: getOrCreate
        try ( Transaction tx = graphDb.beginTx() )
        {
            Node node = factory.getOrCreate( "name", username );
            tx.success();
            return node;
        }
        // END SNIPPET: getOrCreate
    }

    public Node getOrCreateUserWithUniqueFactory( String username, GraphDatabaseService graphDb,
            UniqueFactory<Node> factory )
    {
        // START SNIPPET: getOrCreate
        Transaction transaction = graphDb.beginTx();
        try
        {
            Node node = factory.getOrCreate( "name", username );
            transaction.success();
            return node;
        }
        finally
        {
            transaction.finish();
        }
        // END SNIPPET: getOrCreate
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public getOrCreateUserWithUniqueFactory(username String, graphDb GraphDatabaseService, factory UniqueFactory<Node>) : Node from class org.neo4j.examples.GetOrCreateDocIT


    @Test
    public void shouldCreateNode()
    {
        // START SNIPPET: unitTest
        Node n = null;
        try ( Transaction tx = graphDb.beginTx() )
        {
            n = graphDb.createNode();
            n.setProperty( "name", "Nancy" );
            tx.success();
        }

        // The node should have an id greater than 0, which is the id of the
        // reference node.
        assertThat( n.getId(), is( greaterThan( 0L ) ) );

        // Retrieve a node by using the id of the created node. The id's and
        // property should match.
        try ( Transaction tx = graphDb.beginTx() )
        {
            Node foundNode = graphDb.getNodeById( n.getId() );
            assertThat( foundNode.getId(), is( n.getId() ) );
            assertThat( (String) foundNode.getProperty( "name" ), is( "Nancy" ) );
        }
        // END SNIPPET: unitTest
    }

    @Test
    public void shouldCreateNode()
    {
        // START SNIPPET: unitTest
        Transaction tx = graphDb.beginTx();

        Node n = null;
        try
        {
            n = graphDb.createNode();
            n.setProperty( "name", "Nancy" );
            tx.success();
        }
        catch ( Exception e )
        {
            tx.failure();
        }
        finally
        {
            tx.finish();
        }

        // The node should have an id greater than 0, which is the id of the
        // reference node.
        assertThat( n.getId(), is( greaterThan( 0L ) ) );

        // Retrieve a node by using the id of the created node. The id's and
        // property should match.
        Transaction transaction = graphDb.beginTx();
        Node foundNode = graphDb.getNodeById( n.getId() );
        assertThat( foundNode.getId(), is( n.getId() ) );
        assertThat( (String) foundNode.getProperty( "name" ), is( "Nancy" ) );
        transaction.finish();
        // END SNIPPET: unitTest
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public shouldCreateNode() : void from class org.neo4j.examples.Neo4jBasicDocTest


    /**
     * A
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/TraversalDescription.html[traversal description] is built using a
     * fluent interface and such a description can then spawn
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html[traversers].
     *
     * @@graph
     *
     * With the definition of the +RelationshipTypes+ as
     *
     * @@sourceRels
     *
     * The graph can be traversed with for example the following traverser, starting at the ``Joe'' node:
     *
     * @@knowslikestraverser
     *
     * The traversal will output:
     *
     * @@knowslikesoutput
     *
     * Since http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/TraversalDescription.html[+TraversalDescription+]s
     * are immutable it is also useful to create template descriptions which holds common
     * settings shared by different traversals. For example, let's start with this traverser:
     *
     * @@basetraverser
     *
     * This traverser would yield the following output (we will keep starting from the ``Joe'' node):
     *
     * @@baseoutput
     *
     * Now let's create a new traverser from it, restricting depth to three:
     *
     * @@depth3
     *
     * This will give us the following result:
     *
     * @@output3
     *
     * Or how about from depth two to four?
     * That's done like this:
     *
     * @@depth4
     *
     * This traversal gives us:
     *
     * @@output4
     *
     * For various useful evaluators, see the
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Evaluators.html[Evaluators] Java API
     * or simply implement the
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Evaluator.html[Evaluator] interface yourself.
     *
     * If you're not interested in the http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/Path.html[+Path+]s,
     * but the http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/Node.html[+Node+]s
     * you can transform the traverser into an iterable of http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html#nodes()[nodes]
     * like this:
     *
     * @@nodes
     *
     * In this case we use it to retrieve the names:
     *
     * @@nodeoutput
     *
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html#relationships()[Relationships]
     * are fine as well, here's how to get them:
     *
     * @@relationships
     *
     * Here the relationship types are written, and we get:
     *
     * @@relationshipoutput
     *
     * TIP: The source code for the traversers in this example is available at:
     * @@github
     */
    @Test
    @Documented
    @Graph( { "Joe KNOWS Sara", "Lisa LIKES Joe", "Peter KNOWS Sara",
            "Dirk KNOWS Peter", "Lars KNOWS Dirk", "Ed KNOWS Lars",
            "Lisa KNOWS Lars" } )
    public void how_to_use_the_Traversal_framework()
    {
        Node joe = data.get().get( "Joe" );
        TraversalExample example = new TraversalExample();
        gen.get().addSnippet(
                "graph",
                        createGraphVizWithNodeId( "Traversal Example Graph", graphdb(),
                        gen.get().getTitle() ) );

        try ( Transaction tx = db.beginTx() )
        {
            String output = example.knowsLikesTraverser( joe );
            gen.get().addSnippet( "knowslikesoutput", createOutputSnippet( output ) );

            output = example.traverseBaseTraverser( joe );
            gen.get().addSnippet( "baseoutput", createOutputSnippet( output ) );

            output = example.depth3( joe );
            gen.get().addSnippet( "output3", createOutputSnippet( output ) );

            output = example.depth4( joe );
            gen.get().addSnippet( "output4", createOutputSnippet( output ) );

            output = example.nodes( joe );
            gen.get().addSnippet( "nodeoutput", createOutputSnippet( output ) );

            output = example.relationships( joe );
            gen.get().addSnippet( "relationshipoutput", createOutputSnippet( output ) );

            gen.get().addSourceSnippets( example.getClass(), "knowslikestraverser",
                    "sourceRels", "basetraverser", "depth3", "depth4",
                    "nodes", "relationships" );
            gen.get().addGithubSourceLink( "github", example.getClass(), "community/embedded-examples" );
        }
    }

    /**
     * A
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/TraversalDescription.html[traversal description] is built using a
     * fluent interface and such a description can then spawn
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html[traversers].
     *
     * @@graph
     *
     * With the definition of the +RelationshipTypes+ as
     *
     * @@sourceRels
     *
     * The graph can be traversed with for example the following traverser, starting at the ``Joe'' node:
     *
     * @@knowslikestraverser
     *
     * The traversal will output:
     *
     * @@knowslikesoutput
     *
     * Since http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/TraversalDescription.html[+TraversalDescription+]s
     * are immutable it is also useful to create template descriptions which holds common
     * settings shared by different traversals. For example, let's start with this traverser:
     *
     * @@basetraverser
     *
     * This traverser would yield the following output (we will keep starting from the ``Joe'' node):
     *
     * @@baseoutput
     *
     * Now let's create a new traverser from it, restricting depth to three:
     *
     * @@depth3
     *
     * This will give us the following result:
     *
     * @@output3
     *
     * Or how about from depth two to four?
     * That's done like this:
     *
     * @@depth4
     *
     * This traversal gives us:
     *
     * @@output4
     *
     * For various useful evaluators, see the
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Evaluators.html[Evaluators] Java API
     * or simply implement the
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Evaluator.html[Evaluator] interface yourself.
     *
     * If you're not interested in the http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/Path.html[+Path+]s,
     * but the http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/Node.html[+Node+]s
     * you can transform the traverser into an iterable of http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html#nodes()[nodes]
     * like this:
     *
     * @@nodes
     *
     * In this case we use it to retrieve the names:
     *
     * @@nodeoutput
     *
     * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html#relationships()[Relationships]
     * are fine as well, here's how to get them:
     *
     * @@relationships
     *
     * Here the relationship types are written, and we get:
     *
     * @@relationshipoutput
     *
     * TIP: The source code for the traversers in this example is available at:
     * @@github
     */
    @Test
    @Documented
    @Graph( { "Joe KNOWS Sara", "Lisa LIKES Joe", "Peter KNOWS Sara",
            "Dirk KNOWS Peter", "Lars KNOWS Dirk", "Ed KNOWS Lars",
            "Lisa KNOWS Lars" } )
    public void how_to_use_the_Traversal_framework()
    {
        Node joe = data.get().get( "Joe" );
        TraversalExample example = new TraversalExample();
        gen.get().addSnippet(
                "graph",
                        createGraphVizWithNodeId( "Traversal Example Graph", graphdb(),
                        gen.get().getTitle() ) );

        Transaction transaction = db.beginTx();
        try
        {
            String output = example.knowsLikesTraverser( joe );
            gen.get()
                    .addSnippet( "knowslikesoutput", createOutputSnippet( output ) );

            output = example.traverseBaseTraverser( joe );
            gen.get()
                    .addSnippet( "baseoutput", createOutputSnippet( output ) );

            output = example.depth3( joe );
            gen.get()
                    .addSnippet( "output3", createOutputSnippet( output ) );

            output = example.depth4( joe );
            gen.get()
                    .addSnippet( "output4", createOutputSnippet( output ) );

            output = example.nodes( joe );
            gen.get()
                    .addSnippet( "nodeoutput", createOutputSnippet( output ) );

            output = example.relationships( joe );
            gen.get()
                    .addSnippet( "relationshipoutput", createOutputSnippet( output ) );

            gen.get()
                    .addSourceSnippets( example.getClass(), "knowslikestraverser",
                            "sourceRels", "basetraverser", "depth3", "depth4",
                            "nodes", "relationships" );
            gen.get()
                    .addGithubSourceLink( "github", example.getClass(),
                            "community/embedded-examples" );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=db.beginTx()) in method public how_to_use_the_Traversal_framework() : void from class org.neo4j.examples.TraversalDocTest


    @Test
    public void testPath()
    {
        Node A = orderedPath.createTheGraph();
        TraversalDescription traversalDescription = orderedPath.findPaths();
        try ( Transaction tx = db.beginTx() )
        {
            assertEquals( 1, count( traversalDescription.traverse( A ) ) );
        }
        String output = orderedPath.printPaths( traversalDescription, A );
        assertTrue( output.contains( "(A)--[REL1]-->(B)--[REL2]-->(C)--[REL3]-->(D)" ) );
        String graph = AsciidocHelper.createGraphVizDeletingReferenceNode(
                "Ordered Path Graph", orderedPath.db, "java" );
        assertFalse( graph.isEmpty() );
        gen.saveToFile( "graph", graph );
        gen.saveToFile( "output", createOutputSnippet( output ) );
    }

    @Test
    public void testPath()
    {
        Node A = orderedPath.createTheGraph();
        TraversalDescription traversalDescription = orderedPath.findPaths();
        Transaction transaction = db.beginTx();
        try
        {
            assertEquals( 1, count( traversalDescription.traverse( A ) ) );
        }
        finally
        {
            transaction.finish();
        }
        String output = orderedPath.printPaths( traversalDescription, A );
        assertTrue( output.contains( "(A)--[REL1]-->(B)--[REL2]-->(C)--[REL3]-->(D)" ) );
        String graph = AsciidocHelper.createGraphVizDeletingReferenceNode(
                "Ordered Path Graph", orderedPath.db, "java" );
        assertFalse( graph.isEmpty() );
        gen.saveToFile( "graph", graph );
        gen.saveToFile( "output", createOutputSnippet( output ) );
    }

Try With Resources try(Transaction tx=db.beginTx()) in method public testPath() : void from class org.neo4j.examples.orderedpath.OrderedPathDocTest


    @Override
    public void start( BundleContext context ) throws Exception
    {
        //the cache providers
        ArrayList<CacheProvider> cacheList = new ArrayList<CacheProvider>();
        cacheList.add( new SoftCacheProvider() );

        //the kernel extensions
        LuceneKernelExtensionFactory lucene = new LuceneKernelExtensionFactory();
        List<KernelExtensionFactory<?>> extensions = new ArrayList<KernelExtensionFactory<?>>();
        extensions.add( lucene );

        //the database setup
        GraphDatabaseFactory gdbf = new GraphDatabaseFactory();
        gdbf.setKernelExtensions( extensions );
        gdbf.setCacheProviders( cacheList );
        db = gdbf.newEmbeddedDatabase( "target/db" );

        //the OSGi registration
        serviceRegistration = context.registerService(
                GraphDatabaseService.class.getName(), db, new Hashtable<String, String>() );
        System.out.println( "registered " + serviceRegistration.getReference() );
        indexServiceRegistration = context.registerService(
                Index.class.getName(), db.index().forNodes( "nodes" ),
                new Hashtable<String, String>() );
        try ( Transaction tx = db.beginTx() )
        {
            Node firstNode = db.createNode();
            Node secondNode = db.createNode();
            Relationship relationship = firstNode.createRelationshipTo(
                    secondNode, DynamicRelationshipType.withName( "KNOWS" ) );

            firstNode.setProperty( "message", "Hello, " );
            secondNode.setProperty( "message", "world!" );
            relationship.setProperty( "message", "brave Neo4j " );
            db.index().forNodes( "nodes" ).add( firstNode, "message", "Hello" );
            tx.success();
        }
    }

    @Override
    public void start( BundleContext context ) throws Exception
    {
        //the cache providers
        ArrayList<CacheProvider> cacheList = new ArrayList<CacheProvider>();
        cacheList.add( new SoftCacheProvider() );

        //the kernel extensions
        LuceneKernelExtensionFactory lucene = new LuceneKernelExtensionFactory();
        List<KernelExtensionFactory<?>> extensions = new ArrayList<KernelExtensionFactory<?>>();
        extensions.add( lucene );

        //the database setup
        GraphDatabaseFactory gdbf = new GraphDatabaseFactory();
        gdbf.setKernelExtensions( extensions );
        gdbf.setCacheProviders( cacheList );
        db = gdbf.newEmbeddedDatabase( "target/db" );

        //the OSGi registration
        serviceRegistration = context.registerService(
                GraphDatabaseService.class.getName(), db, new Hashtable<String, String>() );
        System.out.println( "registered " + serviceRegistration.getReference() );
        indexServiceRegistration = context.registerService(
                Index.class.getName(), db.index().forNodes( "nodes" ),
                new Hashtable<String, String>() );
        Transaction tx = db.beginTx();
        try
        {
            Node firstNode = db.createNode();
            Node secondNode = db.createNode();
            Relationship relationship = firstNode.createRelationshipTo(
                    secondNode, DynamicRelationshipType.withName( "KNOWS" ) );

            firstNode.setProperty( "message", "Hello, " );
            secondNode.setProperty( "message", "world!" );
            relationship.setProperty( "message", "brave Neo4j " );
            db.index().forNodes( "nodes" ).add( firstNode, "message", "Hello" );
            tx.success();
        }
        catch ( Exception e )
        {
            e.printStackTrace();
            throw new RuntimeException( e );
        }
        finally
        {
            tx.finish();
        }

    }

Try With Resources try(Transaction tx=db.beginTx()) in method public start(context BundleContext) : void from class org.neo4j.examples.osgi.Neo4jActivator


    @Before
    public void setup() throws Exception
    {
        graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase();
        try ( Transaction tx = graphDb.beginTx() )
        {
            Index<Node> index = graphDb.index().forNodes( "nodes" );
            personRepository = new PersonRepository( graphDb, index );
            createPersons();
            setupFriendsBetweenPeople( 10 );
            tx.success();
        }
    }

    @Before
    public void setup() throws Exception
    {
        graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase();
        Transaction transaction = graphDb.beginTx();
        try
        {
            Index<Node> index = graphDb.index().forNodes( "nodes" );
            personRepository = new PersonRepository( graphDb, index );
            createPersons();
            setupFriendsBetweenPeople( 10 );
            transaction.success();
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public setup() : void from class org.neo4j.examples.socnet.SocnetTest


    @Test
    public void multipleStatusesComeOutInTheRightOrder() throws Exception
    {
        ArrayList<String> statuses = new ArrayList<>();
        statuses.add( "Test1" );
        statuses.add( "Test2" );
        statuses.add( "Test3" );

        try ( Transaction tx = graphDb.beginTx() )
        {
            Person person = getRandomPerson();
            for ( String status : statuses )
            {
                person.addStatus( status );
            }

            int i = statuses.size();
            for ( StatusUpdate update : person.getStatus() )
            {
                i--;
                assertThat( update.getStatusText(), equalTo( statuses.get( i ) ) );
            }
        }
    }

    @Test
    public void multipleStatusesComeOutInTheRightOrder() throws Exception
    {
        ArrayList<String> statuses = new ArrayList<String>();
        statuses.add( "Test1" );
        statuses.add( "Test2" );
        statuses.add( "Test3" );

        Transaction transaction = graphDb.beginTx();
        try
        {
            Person person = getRandomPerson();
            for ( String status : statuses )
            {
                person.addStatus( status );
            }

            int i = statuses.size();
            for ( StatusUpdate update : person.getStatus() )
            {
                i--;
                assertThat( update.getStatusText(), equalTo( statuses.get( i ) ) );
            }
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public multipleStatusesComeOutInTheRightOrder() : void from class org.neo4j.examples.socnet.SocnetTest


    @Test
    public void retrieveStatusUpdatesInDateOrder() throws Exception
    {
        Person person;
        int numberOfStatuses;
        try ( Transaction tx = graphDb.beginTx() )
        {
            person = getRandomPersonWithFriends();
            numberOfStatuses = 20;

            for ( int i = 0; i < numberOfStatuses; i++ )
            {
                Person friend = getRandomFriendOf( person );
                friend.addStatus( "Dum-deli-dum..." );
            }
            tx.success();
        }

        ArrayList<StatusUpdate> updates;
        try ( Transaction tx = graphDb.beginTx() )
        {
            updates = fromIterableToArrayList( person.friendStatuses() );

            assertThat( updates.size(), equalTo( numberOfStatuses ) );
            assertUpdatesAreSortedByDate( updates );
        }
    }

    @Test
    public void retrieveStatusUpdatesInDateOrder() throws Exception
    {
        Person person;
        int numberOfStatuses;
        Transaction transaction = graphDb.beginTx();
        try
        {
            person = getRandomPersonWithFriends();
            numberOfStatuses = 20;

            for ( int i = 0; i < numberOfStatuses; i++ )
            {
                Person friend = getRandomFriendOf( person );
                friend.addStatus( "Dum-deli-dum..." );
            }
            transaction.success();
        }
        finally
        {
            transaction.finish();
        }

        transaction = graphDb.beginTx();
        ArrayList<StatusUpdate> updates;
        try
        {
            updates = fromIterableToArrayList( person.friendStatuses() );

            assertThat( updates.size(), equalTo( numberOfStatuses ) );
            assertUpdatesAreSortedByDate( updates );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public retrieveStatusUpdatesInDateOrder() : void from class org.neo4j.examples.socnet.SocnetTest


    @Test
    public void friendsOfFriendsWorks() throws Exception
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            Person person = getRandomPerson();
            Person friend = getRandomFriendOf( person );

            for ( Person friendOfFriend : friend.getFriends() )
            {
                if ( !friendOfFriend.equals( person ) )
                { // You can't be friends with yourself.
                    assertThat( person.getFriendsOfFriends(), hasItems( friendOfFriend ) );
                }
            }
        }
    }

    @Test
    public void friendsOfFriendsWorks() throws Exception
    {
        Transaction transaction = graphDb.beginTx();
        try
        {
            Person person = getRandomPerson();
            Person friend = getRandomFriendOf( person );

            for ( Person friendOfFriend : friend.getFriends() )
            {
                if ( !friendOfFriend.equals( person ) )
                { // You can't be friends with yourself.
                    assertThat( person.getFriendsOfFriends(), hasItems( friendOfFriend ) );
                }
            }
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public friendsOfFriendsWorks() : void from class org.neo4j.examples.socnet.SocnetTest


    @Test
    public void shouldReturnTheCorrectPersonFromAnyStatusUpdate() throws Exception
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            Person person = getRandomPerson();
            person.addStatus( "Foo" );
            person.addStatus( "Bar" );
            person.addStatus( "Baz" );

            for ( StatusUpdate status : person.getStatus() )
            {
                assertThat( status.getPerson(), equalTo( person ) );
            }
        }
    }

    @Test
    public void shouldReturnTheCorrectPersonFromAnyStatusUpdate() throws Exception
    {
        Transaction transaction = graphDb.beginTx();
        try
        {
            Person person = getRandomPerson();
            person.addStatus( "Foo" );
            person.addStatus( "Bar" );
            person.addStatus( "Baz" );

            for(StatusUpdate status : person.getStatus())
            {
                assertThat(status.getPerson(), equalTo( person ));
            }
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction tx=graphDb.beginTx()) in method public shouldReturnTheCorrectPersonFromAnyStatusUpdate() : void from class org.neo4j.examples.socnet.SocnetTest