    /**
     * Get or create unique node (existing).
     *
     * Here,
     * a node is not created but the existing unique node returned, since another node
     * is indexed with the same data already. The node data returned is then that of the
     * already existing node.
     */
    @Documented
    @Test
    public void get_or_create_unique_node_if_already_existing() throws Exception
    {
        final String index = "people", key = "name", value = "Peter";

        GraphDatabaseService graphdb = graphdb();
        try ( Transaction tx = graphdb().beginTx() )
        {
            Node peter = graphdb.createNode();
            peter.setProperty( key, value );
            peter.setProperty( "sequence", 1 );
            graphdb.index().forNodes( index ).add( peter, key, value );

            tx.success();
        }

        helper.createNodeIndex( index );
        ResponseEntity response = gen().noGraph()
                                     .expectedStatus( 200 /* ok */)
                                     .payloadType( MediaType.APPLICATION_JSON_TYPE )
                                     .payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
                                                       + "\", \"properties\": {\"" + key + "\": \"" + value
                                                       + "\", \"sequence\": 2}}" )
                                     .post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=get_or_create" );

        Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
        Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
        assertEquals( value, data.get( key ) );
        assertEquals( 1, data.get( "sequence" ) );
    }

    /**
     * Get or create unique node (existing).
     *
     * Here,
     * a node is not created but the existing unique node returned, since another node
     * is indexed with the same data already. The node data returned is then that of the
     * already existing node.
     */
    @Documented
    @Test
    public void get_or_create_unique_node_if_already_existing() throws Exception
    {
        final String index = "people", key = "name", value = "Peter";

        GraphDatabaseService graphdb = graphdb();
        Transaction tx = graphdb.beginTx();
        try
        {
            Node peter = graphdb.createNode();
            peter.setProperty( key, value );
            peter.setProperty( "sequence", 1 );
            graphdb.index().forNodes( index ).add( peter, key, value );

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

        helper.createNodeIndex( index );
        ResponseEntity response = gen().noGraph()
                                     .expectedStatus( 200 /* ok */)
                                     .payloadType( MediaType.APPLICATION_JSON_TYPE )
                                     .payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
                                                       + "\", \"properties\": {\"" + key + "\": \"" + value
                                                       + "\", \"sequence\": 2}}" )
                                     .post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=get_or_create" );

        Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
        Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
        assertEquals( value, data.get( key ) );
        assertEquals( 1, data.get( "sequence" ) );
    }

Try With Resources try(Transaction tx=graphdb().beginTx()) in method public get_or_create_unique_node_if_already_existing() : void from class org.neo4j.server.rest.IndexNodeDocIT


    /**
     * Create a unique node or return fail (fail).
     *
     * Here, in case
     * of an already existing node, an error should be returned. In this
     * example, an existing node indexed with the same data
     * is found and an error is returned.
     */
    @Documented
    @Test
    public void create_a_unique_node_or_return_fail___fail() throws Exception
    {
        final String index = "people", key = "name", value = "Peter";

        GraphDatabaseService graphdb = graphdb();
        helper.createNodeIndex( index );

        try ( Transaction tx = graphdb.beginTx() )
        {
            Node peter = graphdb.createNode();
            peter.setProperty( key, value );
            peter.setProperty( "sequence", 1 );
            graphdb.index().forNodes( index ).add( peter, key, value );

            tx.success();
        }

        RestRequest.req();

        ResponseEntity response = gen.get().noGraph()
                                    .expectedStatus( 409 /* conflict */)
                                     .payloadType( MediaType.APPLICATION_JSON_TYPE )
                                     .payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
                                                       + "\", \"properties\": {\"" + key + "\": \"" + value
                                                       + "\", \"sequence\": 2}}" )
                                    .post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=create_or_fail" );

        Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
        Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
        assertEquals( value, data.get( key ) );
        assertEquals( 1, data.get( "sequence" ) );
    }

    /**
     * Create a unique node or return fail (fail).
     *
     * Here, in case
     * of an already existing node, an error should be returned. In this
     * example, an existing node indexed with the same data
     * is found and an error is returned.
     */
    @Documented
    @Test
    public void create_a_unique_node_or_return_fail___fail() throws Exception
    {
        final String index = "people", key = "name", value = "Peter";

        GraphDatabaseService graphdb = graphdb();
        helper.createNodeIndex( index );

        Transaction tx = graphdb.beginTx();
        try
        {
            Node peter = graphdb.createNode();
            peter.setProperty( key, value );
            peter.setProperty( "sequence", 1 );
            graphdb.index().forNodes( index ).add( peter, key, value );

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

        final RestRequest request = RestRequest.req();

        ResponseEntity response = gen.get().noGraph()
                                    .expectedStatus( 409 /* conflict */)
                                     .payloadType( MediaType.APPLICATION_JSON_TYPE )
                                     .payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
                                                       + "\", \"properties\": {\"" + key + "\": \"" + value
                                                       + "\", \"sequence\": 2}}" )
                                    .post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=create_or_fail" );

        Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
        Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
        assertEquals( value, data.get( key ) );
        assertEquals( 1, data.get( "sequence" ) );
    }

Try With Resources try(Transaction tx=graphdb.beginTx()) in method public create_a_unique_node_or_return_fail___fail() : void from class org.neo4j.server.rest.IndexNodeDocIT


    /**
     * Add a relationship to an index
     * unless a node already exists for the given mapping then return fail (case fail).
     */
    @Documented
    @Test
    public void put_relationship_if_absent_only_fail() throws Exception
    {
        final String index = "rels", key = "name", value = "Peter";
        GraphDatabaseService graphdb = graphdb();
        helper.createRelationshipIndex( index );
        Relationship rel;
        try ( Transaction tx = graphdb.beginTx() )
        {
            Node node1 = graphdb.createNode();
            Node node2 = graphdb.createNode();
            rel = node1.createRelationshipTo( node2, MyRelationshipTypes.KNOWS );
            graphdb.index().forRelationships( index ).add( rel, key, value );
            tx.success();
        }
        gen.get()
                .noGraph()
                .expectedStatus( 409 /* conflict */)
                .payloadType( MediaType.APPLICATION_JSON_TYPE )
                .payload(
                        "{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\":\""
                                + functionalTestHelper.relationshipUri( rel.getId() ) + "\"}" )
                .post( functionalTestHelper.relationshipIndexUri() + index + "?uniqueness=create_or_fail" );
    }

   /**
    * Add a relationship to an index
    * unless a node already exists for the given mapping then return fail (case fail).
    */
   @Documented
   @Test
   public void put_relationship_if_absent_only_fail() throws Exception
   {
   	final String index = "rels", key = "name", value = "Peter";
       GraphDatabaseService graphdb = graphdb();
       helper.createRelationshipIndex( index );

       Relationship rel;
       Transaction tx = graphdb.beginTx();
       try
       {
	       	Node node1 = graphdb.createNode();
	       	Node node2 = graphdb.createNode();
	       	rel = node1.createRelationshipTo(node2, MyRelationshipTypes.KNOWS);

	        graphdb.index().forRelationships( index ).add( rel, key, value );

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

        gen.get()
                .noGraph()
                .expectedStatus( 409 /* conflict */)
                .payloadType( MediaType.APPLICATION_JSON_TYPE )
                .payload( "{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\":\"" + functionalTestHelper.relationshipUri( rel.getId() ) + "\"}" )
                .post( functionalTestHelper.relationshipIndexUri() + index + "?uniqueness=create_or_fail" );
   }

Try With Resources try(Transaction tx=graphdb.beginTx()) in method public put_relationship_if_absent_only_fail() : void from class org.neo4j.server.rest.IndexRelationshipDocIT


    private <T> Map<String, String> getHeaders( final MultivaluedMap<String, T> headers, final List<String> filter,
            final Collection<String> additionalFilter )
    {
        Map<String, String> filteredHeaders = new TreeMap<>();
        for ( Entry<String, List<T>> header : headers.entrySet() )
        {
            String key = header.getKey();
            if ( filter.contains( key ) || additionalFilter.contains( key ) )
            {
                String values = "";
                for ( T value : header.getValue() )
                {
                    if ( !values.isEmpty() )
                    {
                        values += ", ";
                    }
                    values += String.valueOf( value );
                }
                filteredHeaders.put( key, values );
            }
        }
        return filteredHeaders;
    }

    private <T> Map<String, String> getHeaders( final MultivaluedMap<String, T> headers, final List<String> filter,
            final Collection<String> additionalFilter )
    {
        Map<String, String> filteredHeaders = new TreeMap<String, String>();
        for ( Entry<String, List<T>> header : headers.entrySet() )
        {
            String key = header.getKey();
            if ( filter.contains( key ) || additionalFilter.contains( key ) )
            {
                String values = "";
                for ( T value : header.getValue() )
                {
                    if ( !values.isEmpty() )
                    {
                        values += ", ";
                    }
                    values += String.valueOf( value );
                }
                filteredHeaders.put( key, values );
            }
        }
        return filteredHeaders;
    }

Replace Generic With Diamond TreeMap<String,String> with TreeMap<> in method private getHeaders(headers MultivaluedMap<String,T>, filter List<String>, additionalFilter Collection<String>) : Map<String,String> from class org.neo4j.server.rest.RESTDocsGenerator


    protected void document( final DocumentationData data )
    {
        if (data.ignore)
        {
            return;
        }
        String name = data.title.replace( " ", "-" ).toLowerCase();
        String filename = name + ".asciidoc";
        File dir = new File( new File( new File( "target" ), "docs" ), section );
        data.description = replaceSnippets( data.description, dir, name );
        try ( Writer fw = AsciiDocGenerator.getFW( dir, filename ) )
        {
            String longSection = section.replaceAll( "\\(|\\)", "" )+"-" + name.replaceAll( "\\(|\\)", "" );
            if(longSection.indexOf( "/" )>0)
            {
                longSection = longSection.substring( longSection.indexOf( "/" )+1 );
            }
            line( fw, "[[" + longSection + "]]" );
            //make first Character uppercase
            String firstChar = data.title.substring(  0, 1 ).toUpperCase();
            String heading = firstChar + data.title.substring( 1 );
            line( fw, getAsciidocHeading( heading ) );
            line( fw, "" );
            if ( data.description != null && !data.description.isEmpty() )
            {
                line( fw, data.description );
                line( fw, "" );
            }
            if ( !noGraph && graph != null )
            {
                fw.append( AsciiDocGenerator.dumpToSeparateFile( dir,
                        name + ".graph",
                        AsciidocHelper.createGraphVizWithNodeId( "Final Graph",
                                graph, title ) ) );
                line(fw, "" );
            }
            line( fw, "_Example request_" );
            line( fw, "" );
            StringBuilder sb = new StringBuilder( 512 );
            sb.append( "* *+" )
                    .append( data.method )
                    .append( "+*  +" )
                    .append( data.uri )
                    .append( "+\n" );
            if ( data.requestHeaders != null )
            {
                for ( Entry<String, String> header : data.requestHeaders.entrySet() )
                {
                    sb.append( "* *+" )
                            .append( header.getKey() )
                            .append( ":+* +" )
                            .append( header.getValue() )
                            .append( "+\n" );
                }
            }
            String prettifiedPayload = data.getPayload();
            if ( prettifiedPayload != null )
            {
                writeEntity( sb, prettifiedPayload );
            }
            fw.append( AsciiDocGenerator.dumpToSeparateFile( dir, name
                                                                  + ".request",
                    sb.toString() ) );
            sb = new StringBuilder( 2048 );
            line( fw, "" );
            line( fw, "_Example response_" );
            line( fw, "" );
            sb.append( "* *+" )
                    .append( data.status )
                    .append( ":+* +" )
                    .append( Response.Status.fromStatusCode( data.status ) )
                    .append( "+\n" );
            if ( data.responseHeaders != null )
            {
                for ( Entry<String, String> header : data.responseHeaders.entrySet() )
                {
                    sb.append( "* *+" )
                            .append( header.getKey() )
                            .append( ":+* +" )
                            .append( header.getValue() )
                            .append( "+\n" );
                }
            }
            writeEntity( sb, data.getPrettifiedEntity() );
            fw.append( AsciiDocGenerator.dumpToSeparateFile( dir,
                    name + ".response", sb.toString() ) );
            line( fw, "" );
        }
        catch ( IOException e )
        {
            e.printStackTrace();
            fail();
        }
    }

    protected void document( final DocumentationData data )
    {
        if (data.ignore) return;
        Writer fw = null;
        try
        {
            String name = data.title.replace( " ", "-" )
                    .toLowerCase();
            String filename = name + ".asciidoc";
            File dir = new File( new File( new File( "target" ), "docs" ),
                    section );
            data.description = replaceSnippets( data.description, dir, name );
            fw = AsciiDocGenerator.getFW( dir, filename );
            String longSection = section.replaceAll( "\\(|\\)", "" )+"-" + name.replaceAll( "\\(|\\)", "" );
            if(longSection.indexOf( "/" )>0)
            {
                longSection = longSection.substring( longSection.indexOf( "/" )+1 );
            }
            line( fw, "[[" + longSection + "]]" );
            //make first Character uppercase
            String firstChar = data.title.substring(  0, 1 ).toUpperCase();
            String heading = firstChar + data.title.substring( 1 );
            line( fw, getAsciidocHeading( heading ) );
            line( fw, "" );
            if ( data.description != null && !data.description.isEmpty() )
            {
                line( fw, data.description );
                line( fw, "" );
            }
            if ( !noGraph && graph != null )
            {
                fw.append( AsciiDocGenerator.dumpToSeparateFile( dir,
                        name + ".graph",
                        AsciidocHelper.createGraphVizWithNodeId( "Final Graph",
                                graph, title ) ) );
                line(fw, "" );
            }
            line( fw, "_Example request_" );
            line( fw, "" );
            StringBuilder sb = new StringBuilder( 512 );
            sb.append( "* *+" )
                    .append( data.method )
                    .append( "+*  +" )
                    .append( data.uri )
                    .append( "+\n" );
            if ( data.requestHeaders != null )
            {
                for ( Entry<String, String> header : data.requestHeaders.entrySet() )
                {
                    sb.append( "* *+" )
                            .append( header.getKey() )
                            .append( ":+* +" )
                            .append( header.getValue() )
                            .append( "+\n" );
                }
            }
            String prettifiedPayload = data.getPayload();
            if ( prettifiedPayload != null )
            {
                writeEntity( sb, prettifiedPayload );
            }
            fw.append( AsciiDocGenerator.dumpToSeparateFile( dir, name
                                                                  + ".request",
                    sb.toString() ) );
            sb = new StringBuilder( 2048 );
            line( fw, "" );
            line( fw, "_Example response_" );
            line( fw, "" );
            sb.append( "* *+" )
                    .append( data.status )
                    .append( ":+* +" )
                    .append( Response.Status.fromStatusCode( data.status ) )
                    .append( "+\n" );
            if ( data.responseHeaders != null )
            {
                for ( Entry<String, String> header : data.responseHeaders.entrySet() )
                {
                    sb.append( "* *+" )
                            .append( header.getKey() )
                            .append( ":+* +" )
                            .append( header.getValue() )
                            .append( "+\n" );
                }
            }
            writeEntity( sb, data.getPrettifiedEntity() );
            fw.append( AsciiDocGenerator.dumpToSeparateFile( dir,
                    name + ".response", sb.toString() ) );
            line( fw, "" );
        }
        catch ( IOException e )
        {
            e.printStackTrace();
            fail();
        }
        finally
        {
            if ( fw != null )
            {
                try
                {
                    fw.close();
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                    fail();
                }
            }
        }
    }

Try With Resources try(Writer fw=AsciiDocGenerator.getFW(dir,filename)) in method protected document(data DocumentationData) : void from class org.neo4j.server.rest.RESTDocsGenerator


    @Test
    @Graph("I know you")
    public void get_Relationship_by_ID() throws JsonParseException
    {
        Node node = data.get().get( "I" );
        Relationship relationship;
        try ( Transaction transaction = node.getGraphDatabase().beginTx() )
        {
            relationship = node.getSingleRelationship(
                    DynamicRelationshipType.withName( "know" ),
                    Direction.OUTGOING );
        }
        String response = gen().expectedStatus(
                com.sun.jersey.api.client.ClientResponse.Status.OK.getStatusCode() ).get(
                getRelationshipUri( relationship ) ).entity();
        assertTrue( JsonHelper.jsonToMap( response ).containsKey( "start" ) );
    }

    @Test
    @Graph("I know you")
    public void get_Relationship_by_ID() throws JsonParseException
    {
        Node node = data.get().get( "I" );
        Relationship relationship;
        Transaction transaction = node.getGraphDatabase().beginTx();
        try
        {
            relationship = node.getSingleRelationship(
                    DynamicRelationshipType.withName( "know" ),
                    Direction.OUTGOING );
        }
        finally
        {
            transaction.finish();
        }
        String response = gen().expectedStatus(
                com.sun.jersey.api.client.ClientResponse.Status.OK.getStatusCode() ).get(
                getRelationshipUri( relationship ) ).entity();
        assertTrue( JsonHelper.jsonToMap( response ).containsKey( "start" ) );
    }

Try With Resources try(Transaction transaction=node.getGraphDatabase().beginTx()) in method public get_Relationship_by_ID() : void from class org.neo4j.server.rest.RelationshipDocIT


    private Relationship getFirstRelationshipFromRomeoNode()
    {
        Node romeo = getNode( "Romeo" );

        try ( Transaction transaction = romeo.getGraphDatabase().beginTx() )
        {
            return romeo.getRelationships().iterator().next();
        }
    }

    private Relationship getFirstRelationshipFromRomeoNode()
    {
        Node romeo = getNode( "Romeo" );

        Transaction transaction = romeo.getGraphDatabase().beginTx();
        try
        {
            return romeo.getRelationships().iterator().next();
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=romeo.getGraphDatabase().beginTx()) in method private getFirstRelationshipFromRomeoNode() : Relationship from class org.neo4j.server.rest.RelationshipDocIT


    private ConstraintDefinition createLabelUniquenessPropertyConstraint( String labelName, String propertyKey )
    {
        try ( Transaction tx = graphdb().beginTx() )
        {
            ConstraintDefinition constraintDefinition = graphdb().schema().constraintFor( label( labelName ) ).unique
                    ().on( propertyKey ).create();
            tx.success();
            return constraintDefinition;
        }
    }

    private ConstraintDefinition createLabelUniquenessPropertyConstraint( String labelName, String propertyKey )
    {
        Transaction tx = graphdb().beginTx();
        try
        {
            ConstraintDefinition constraintDefinition = graphdb().schema().constraintFor( label( labelName ) ).unique
                    ().on( propertyKey ).create();
            tx.success();
            return constraintDefinition;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=graphdb().beginTx()) in method private createLabelUniquenessPropertyConstraint(labelName String, propertyKey String) : ConstraintDefinition from class org.neo4j.server.rest.SchemaConstraintsDocIT


    private IndexDefinition createIndex( String labelName, String propertyKey )
    {
        try ( Transaction tx = graphdb().beginTx() )
        {
            IndexDefinition indexDefinition = graphdb().schema().indexFor( label( labelName ) ).on( propertyKey )
                    .create();
            tx.success();
            return indexDefinition;
        }
    }

    private IndexDefinition createIndex( String labelName, String propertyKey )
    {
        Transaction tx = graphdb().beginTx();
        try
        {
            IndexDefinition indexDefinition = graphdb().schema().indexFor( label( labelName ) ).on( propertyKey )
                    .create();
            tx.success();
            return indexDefinition;
        }
        finally
        {
            tx.finish();
        }
    }

Try With Resources try(Transaction tx=graphdb().beginTx()) in method private createIndex(labelName String, propertyKey String) : IndexDefinition from class org.neo4j.server.rest.SchemaIndexDocIT


    @SuppressWarnings("WhileLoopReplaceableByForEach")
    private long countNodes()
    {
        try ( Transaction transaction = graphdb().beginTx() )
        {
            long count = 0;
            Iterator<Node> allNodes = GlobalGraphOperations.at( graphdb() ).getAllNodes().iterator();
            while ( allNodes.hasNext() )
            {
                allNodes.next();
                count++;
            }
            return count;
        }
    }

    @SuppressWarnings("WhileLoopReplaceableByForEach")
    private long countNodes()
    {
        Transaction transaction = graphdb().beginTx();
        try
        {
            long count = 0;
            Iterator<Node> allNodes = GlobalGraphOperations.at( graphdb() ).getAllNodes().iterator();
            while ( allNodes.hasNext() )
            {
                allNodes.next();
                count++;
            }
            return count;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=graphdb().beginTx()) in method private countNodes() : long from class org.neo4j.server.rest.TransactionFunctionalTest


    private Node createLinkedList( final int listLength, final Database db )
    {
        Node startNode = null;
        try ( Transaction tx = db.getGraph().beginTx() )
        {
            Node previous = null;
            for ( int i = 0; i < listLength; i++ )
            {
                Node current = db.getGraph().createNode();
                current.setProperty( "name", String.valueOf( i ) );

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

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

    private Node createLinkedList( final int listLength, final Database db )
    {
        Transaction tx = db.getGraph().beginTx();
        Node startNode = null;
        try
        {
            Node previous = null;
            for ( int i = 0; i < listLength; i++ )
            {
                Node current = db.getGraph().createNode();
                current.setProperty( "name", String.valueOf( i ) );

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

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

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


    private int countNodes()
    {
        try ( Transaction transaction = graphdb().beginTx() )
        {
            return IteratorUtil.count( (Iterable)graphdb().getAllNodes() );
        }
    }

    private int countNodes()
    {
        Transaction transaction = graphdb().beginTx();
        try
        {
            return IteratorUtil.count( (Iterable)graphdb().getAllNodes() );
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(Transaction transaction=graphdb().beginTx()) in method private countNodes() : int from class org.neo4j.server.rest.streaming.StreamingBatchOperationDocIT


    @Override
    protected String getPrompt( Session session ) throws ShellException
    {
        try ( org.neo4j.graphdb.Transaction transaction = this.getDb().beginTx() )
        {
            Object rawCustomPrompt = session.get( PROMPT_KEY );
            String customPrompt = rawCustomPrompt != null ? rawCustomPrompt.toString() : getDefaultPrompt();
            String output = bashInterpreter.interpret( customPrompt, this, session );
            transaction.success();
            return output;
        }
    }

    @Override
    protected String getPrompt( Session session ) throws ShellException
    {
        org.neo4j.graphdb.Transaction transaction = this.getDb().beginTx();

        try
        {
            Object rawCustomPrompt = session.get( PROMPT_KEY );
            String customPrompt = rawCustomPrompt != null ? rawCustomPrompt.toString() : getDefaultPrompt();
            String output = bashInterpreter.interpret( customPrompt, this, session );
            transaction.success();
            return output;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(org.neo4j.graphdb.Transaction transaction=this.getDb().beginTx()) in method protected getPrompt(session Session) : String from class org.neo4j.shell.kernel.GraphDatabaseShellServer


    @Override
    public Welcome welcome( Map<String, Serializable> initialSession ) throws RemoteException, ShellException
    {
        try ( org.neo4j.graphdb.Transaction transaction = graphDb.beginTx() )
        {
            Welcome welcome = super.welcome( initialSession );
            transaction.success();
            return welcome;
        }
    }

    @Override
    public Welcome welcome( Map<String, Serializable> initialSession ) throws RemoteException, ShellException
    {
        org.neo4j.graphdb.Transaction transaction = graphDb.beginTx();

        try
        {
            Welcome welcome = super.welcome( initialSession );
            transaction.success();
            return welcome;
        }
        finally
        {
            transaction.finish();
        }
    }

Try With Resources try(org.neo4j.graphdb.Transaction transaction=graphDb.beginTx()) in method public welcome(initialSession Map<String,Serializable>) : Welcome from class org.neo4j.shell.kernel.GraphDatabaseShellServer


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

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

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


    private List<Tester> createTesters() throws Exception
    {
        List<Tester> testers = new ArrayList<>( 20 );
        for ( int i = 0; i < 20; i++ )
        {
            int x = r.nextInt( 3 );

            Tester t;
            if ( x == 0 )
            {
                t = new Reader();
            } else if ( x == 1 )
            {
                t = new Committer();
            } else if ( x == 2 )
            {
                t = new Rollbacker();
            } else
            {
                throw new Exception( "oh noes" );
            }

            testers.add( t );
        }

        return testers;
    }

    private List<Tester> createTesters() throws Exception
    {
        List<Tester> testers = new ArrayList<Tester>( 20 );
        for ( int i = 0; i < 20; i++ )
        {
            int x = r.nextInt( 3 );

            Tester t;
            if ( x == 0 )
            {
                t = new Reader();
            } else if ( x == 1 )
            {
                t = new Committer();
            } else if ( x == 2 )
            {
                t = new Rollbacker();
            } else
            {
                throw new Exception( "oh noes" );
            }

            testers.add( t );
        }

        return testers;
    }

Replace Generic With Diamond ArrayList<Tester> with ArrayList<> in method private createTesters() : List<Tester> from class org.neo4j.shell.TransactionSoakIT


    @Override
    public void setProperty( String key, Object value )
    {
        boolean success = false;
        try ( DataStatement statement = statementCtxProvider.dataStatement() )
        {
            long propertyKeyId = statement.propertyKeyGetOrCreateForName( key );
            try
            {
                statement.nodeSetProperty( nodeId, Property.property( propertyKeyId, value ) );
            }
            catch ( ConstraintValidationKernelException e )
            {
                success = true;
                throw new ConstraintViolationException( e.getUserMessage( new StatementTokenNameLookup( statement ) ), e );
            }
            success = true;
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
        finally
        {
            if ( !success )
            {
                nodeLookup.getNodeManager().setRollbackOnly();
            }
        }
    }

    @Override
    public void setProperty( String key, Object value )
    {
        StatementOperationParts context = statementCtxProvider.getCtxForWriting();
        StatementState state = statementCtxProvider.statementForWriting();
        boolean success = false;
        try
        {
            long propertyKeyId = context.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            context.entityWriteOperations().nodeSetProperty( state, nodeId, Property.property( propertyKeyId, value ) );
            success = true;
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
        catch ( ConstraintValidationKernelException e )
        {
            throw new ConstraintViolationException( e.getUserMessage( new StatementTokenNameLookup( state, context.keyReadOperations() ) ), e );
        }
        finally
        {
            state.close();
            if ( !success )
            {
                nodeLookup.getNodeManager().setRollbackOnly();
            }
        }
    }

Try With Resources try(DataStatement statement=statementCtxProvider.dataStatement()) in method public setProperty(key String, value Object) : void from class org.neo4j.kernel.impl.core.NodeProxy


    synchronized void doBeforeCompletion()
    {
        beforeCompletionRunning = true;
        try
        {
            for ( Synchronization s : syncHooks )
            {
                try
                {
                    s.beforeCompletion();
                }
                catch ( Throwable t )
                {
                    logger.warn( "Caught exception from tx syncronization[" + s
                            + "] beforeCompletion()", t );
                }
            }
            // execute any hooks added since we entered doBeforeCompletion
            while ( !syncHooksAdded.isEmpty() )
            {
                List<Synchronization> addedHooks = syncHooksAdded;
                syncHooksAdded = new ArrayList<>();
                for ( Synchronization s : addedHooks )
                {
                    s.beforeCompletion();
                    syncHooks.add( s );
                }
            }
        }
        finally
        {
            beforeCompletionRunning = false;
        }
    }

    synchronized void doBeforeCompletion()
    {
        beforeCompletionRunning = true;
        try
        {
            for ( Synchronization s : syncHooks )
            {
                try
                {
                    s.beforeCompletion();
                }
                catch ( Throwable t )
                {
                    logger.warn( "Caught exception from tx syncronization[" + s
                            + "] beforeCompletion()", t );
                }
            }
            // execute any hooks added since we entered doBeforeCompletion
            while ( !syncHooksAdded.isEmpty() )
            {
                List<Synchronization> addedHooks = syncHooksAdded;
                syncHooksAdded = new ArrayList<Synchronization>();
                for ( Synchronization s : addedHooks )
                {
                    s.beforeCompletion();
                    syncHooks.add( s );
                }
            }
        }
        finally
        {
            beforeCompletionRunning = false;
        }
    }

Replace Generic With Diamond ArrayList<Synchronization> with ArrayList<> in method package doBeforeCompletion() : void from class org.neo4j.kernel.impl.transaction.ReadOnlyTransactionImpl


    synchronized void doBeforeCompletion()
    {
        beforeCompletionRunning = true;
        try
        {
            for ( Synchronization s : syncHooks )
            {
                try
                {
                    s.beforeCompletion();
                }
                catch ( Throwable t )
                {
                    addRollbackCause( t );
                }
            }
            // execute any hooks added since we entered doBeforeCompletion
            while ( !syncHooksAdded.isEmpty() )
            {
                List<Synchronization> addedHooks = syncHooksAdded;
                syncHooksAdded = new ArrayList<>();
                for ( Synchronization s : addedHooks )
                {
                    s.beforeCompletion();
                    syncHooks.add( s );
                }
            }
        }
        finally
        {
            beforeCompletionRunning = false;
        }
    }

    synchronized void doBeforeCompletion()
    {
        beforeCompletionRunning = true;
        try
        {
            for ( Synchronization s : syncHooks )
            {
                try
                {
                    s.beforeCompletion();
                }
                catch ( Throwable t )
                {
                    addRollbackCause( t );
                }
            }
            // execute any hooks added since we entered doBeforeCompletion
            while ( !syncHooksAdded.isEmpty() )
            {
                List<Synchronization> addedHooks = syncHooksAdded;
                syncHooksAdded = new ArrayList<Synchronization>();
                for ( Synchronization s : addedHooks )
                {
                    s.beforeCompletion();
                    syncHooks.add( s );
                }
            }
        }
        finally
        {
            beforeCompletionRunning = false;
        }
    }

Replace Generic With Diamond ArrayList<Synchronization> with ArrayList<> in method package doBeforeCompletion() : void from class org.neo4j.kernel.impl.transaction.TransactionImpl


    void doCommit() throws XAException, SystemException
    {
        boolean onePhase = isOnePhase();
        boolean readOnly = true;
        if ( !onePhase )
        {
            // prepare
            status = Status.STATUS_PREPARING;
            LinkedList<Xid> preparedXids = new LinkedList<>();
            for ( ResourceElement re : resourceList )
            {
                if ( !preparedXids.contains( re.getXid() ) )
                {
                    preparedXids.add( re.getXid() );
                    int vote = re.getResource().prepare( re.getXid() );
                    if ( vote == XAResource.XA_OK )
                    {
                        readOnly = false;
                    }
                    else if ( vote == XAResource.XA_RDONLY )
                    {
                        re.setStatus( RS_READONLY );
                    }
                    else
                    {
                        // rollback tx
                        status = Status.STATUS_MARKED_ROLLBACK;
                        return;
                    }
                }
                else
                {
                    // set it to readonly, only need to commit once
                    re.setStatus( RS_READONLY );
                }
            }
            if ( readOnly )
            {
                status = Status.STATUS_COMMITTED;
                return;
            }
            else
            {
                status = Status.STATUS_PREPARED;
            }
            // everyone has prepared - mark as committing
            try
            {
                txManager.getTxLog().markAsCommitting( getGlobalId(), forceMode );
            }
            catch ( IOException e )
            {
                logger.error( "Error writing transaction log", e );
                txManager.setTmNotOk( e );
                throw Exceptions.withCause( new SystemException( "TM encountered a problem, "
                                                                 + " error writing transaction log" ), e );
            }
        }
        // commit
        status = Status.STATUS_COMMITTING;
        for ( ResourceElement re : resourceList )
        {
            if ( re.getStatus() != RS_READONLY )
            {
                try
                {
                    re.getResource().commit( re.getXid(), onePhase );
                }
                catch ( XAException e )
                {
                    throw e;
                }
                catch ( Throwable e )
                {
                    throw Exceptions.withCause( new XAException( XAException.XAER_RMERR ), e );
                }
            }
        }
        status = Status.STATUS_COMMITTED;
    }

    void doCommit() throws XAException, SystemException
    {
        boolean onePhase = isOnePhase();
        boolean readOnly = true;
        if ( !onePhase )
        {
            // prepare
            status = Status.STATUS_PREPARING;
            LinkedList<Xid> preparedXids = new LinkedList<Xid>();
            for ( ResourceElement re : resourceList )
            {
                if ( !preparedXids.contains( re.getXid() ) )
                {
                    preparedXids.add( re.getXid() );
                    int vote = re.getResource().prepare( re.getXid() );
                    if ( vote == XAResource.XA_OK )
                    {
                        readOnly = false;
                    }
                    else if ( vote == XAResource.XA_RDONLY )
                    {
                        re.setStatus( RS_READONLY );
                    }
                    else
                    {
                        // rollback tx
                        status = Status.STATUS_MARKED_ROLLBACK;
                        return;
                    }
                }
                else
                {
                    // set it to readonly, only need to commit once
                    re.setStatus( RS_READONLY );
                }
            }
            if ( readOnly )
            {
                status = Status.STATUS_COMMITTED;
                return;
            }
            else
            {
                status = Status.STATUS_PREPARED;
            }
            // everyone has prepared - mark as committing
            try
            {
                txManager.getTxLog().markAsCommitting( getGlobalId(), forceMode );
            }
            catch ( IOException e )
            {
                logger.error( "Error writing transaction log", e );
                txManager.setTmNotOk( e );
                throw Exceptions.withCause( new SystemException( "TM encountered a problem, "
                                                                 + " error writing transaction log" ), e );
            }
        }
        // commit
        status = Status.STATUS_COMMITTING;
        for ( ResourceElement re : resourceList )
        {
            if ( re.getStatus() != RS_READONLY )
            {
                try
                {
                    re.getResource().commit( re.getXid(), onePhase );
                }
                catch ( XAException e )
                {
                    throw e;
                }
                catch ( Throwable e )
                {
                    throw Exceptions.withCause( new XAException( XAException.XAER_RMERR ), e );
                }
            }
        }
        status = Status.STATUS_COMMITTED;
    }

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


    void doRollback() throws XAException
    {
        status = Status.STATUS_ROLLING_BACK;
        LinkedList<Xid> rolledbackXids = new LinkedList<>();
        for ( ResourceElement re : resourceList )
        {
            if ( !rolledbackXids.contains( re.getXid() ) )
            {
                rolledbackXids.add( re.getXid() );
                re.getResource().rollback( re.getXid() );
            }
        }
        status = Status.STATUS_ROLLEDBACK;
    }

    void doRollback() throws XAException
    {
        status = Status.STATUS_ROLLING_BACK;
        LinkedList<Xid> rolledbackXids = new LinkedList<Xid>();
        for ( ResourceElement re : resourceList )
        {
            if ( !rolledbackXids.contains( re.getXid() ) )
            {
                rolledbackXids.add( re.getXid() );
                re.getResource().rollback( re.getXid() );
            }
        }
        status = Status.STATUS_ROLLEDBACK;
    }

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


    private String getOrCreateFromState( KernelTransaction tx, String key, final String value )
    {
        try ( BaseStatement statement = tx.acquireBaseStatement() )
        {
            return statement.schemaStateGetOrCreate( key, new Function<String, String>()
            {
                @Override
                public String apply( String from )
                {
                    return value;
                }
            } );
        }
    }

    private String getOrCreateFromState( KernelTransaction tx, String key, final String value )
    {
        StatementOperationParts ctx = tx.newStatementOperations();
        StatementState state = ctxProvider.statementForReading();
        try
        {
            return ctx.schemaStateOperations().schemaStateGetOrCreate( state, key, new Function<String, String>()
            {
                @Override
                public String apply( String from )
                {
                    return value;
                }
            } );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(BaseStatement statement=tx.acquireBaseStatement()) in method private getOrCreateFromState(tx KernelTransaction, key String, value String) : String from class org.neo4j.kernel.impl.api.KernelSchemaStateFlushingTest


    public static <T> T awaitFuture( Future<T> future )
    {
        try
        {
            return future.get( 10, SECONDS );
        }
        catch ( InterruptedException e )
        {
            Thread.interrupted();
            throw new RuntimeException( e );
        }
        catch ( ExecutionException | TimeoutException e )
        {
            throw new RuntimeException( e );
        }
    }

    public static <T> T awaitFuture( Future<T> future )
    {
        try
        {
            return future.get( 10, SECONDS );
        }
        catch ( InterruptedException e )
        {
            Thread.interrupted();
            throw new RuntimeException( e );
        }
        catch ( ExecutionException e )
        {
            throw new RuntimeException( e );
        }
        catch ( TimeoutException e )
        {
            throw new RuntimeException( e );
        }
    }

Merge Catch [catch(ExecutionException e), catch(TimeoutException e)] to catch(ExecutionException|TimeoutException e) in method public awaitFuture(future Future<T>) : T from class org.neo4j.kernel.impl.api.index.SchemaIndexTestHelper


    private static Map<String, String> withForcedInMemoryConfiguration( Map<String, String> params )
    {
        // Because EphemeralFileChannel doesn't support memorymapping
        Map<String, String> result = new HashMap<>( params );
        result.put( use_memory_mapped_buffers.name(), FALSE );

        // To signal to index provides that we should be in-memory
        result.put( ephemeral.name(), TRUE );
        return result;
    }

    private static Map<String, String> withForcedInMemoryConfiguration( Map<String, String> params )
    {
        // Because EphemeralFileChannel doesn't support memorymapping
        Map<String, String> result = new HashMap<String, String>( params );
        result.put( use_memory_mapped_buffers.name(), FALSE );

        // To signal to index provides that we should be in-memory
        result.put( ephemeral.name(), TRUE );
        return result;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method private withForcedInMemoryConfiguration(params Map<String,String>) : Map<String,String> from class org.neo4j.test.ImpermanentGraphDatabase


    private void beginTransaction() throws BeginTransactionFailureException
    {
        try
        {
            txManager.begin();
        }
        catch ( NotSupportedException | SystemException e )
        {
            throw new BeginTransactionFailureException( e );
        }
    }

    private void beginTransaction() throws BeginTransactionFailureException
    {
        try
        {
            txManager.begin();
        }
        catch ( NotSupportedException e )
        {
            throw new BeginTransactionFailureException( e );
        }
        catch ( SystemException e )
        {
            throw new BeginTransactionFailureException( e );
        }
    }

Merge Catch [catch(NotSupportedException e), catch(SystemException e)] to catch(NotSupportedException|SystemException e) in method private beginTransaction() : void from class org.neo4j.kernel.api.Transactor


    @Override
    public boolean hasProperty( String key )
    {
        if ( null == key )
            return false;

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if ( propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                return false;
            }
            return ctxForReading.entityReadOperations().graphHasProperty( state, propertyId );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            return false;
        }
    }

    @Override
    public boolean hasProperty( String key )
    {
        if ( null == key )
            return false;

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        StatementState state = statementCtxProvider.statementForReading();
        try
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if(propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                return false;
            }
            return ctxForReading.entityReadOperations().graphHasProperty( state, propertyId );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            return false;
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public hasProperty(key String) : boolean from class org.neo4j.kernel.impl.core.GraphPropertiesImpl


    @Override
    public Object getProperty( String key )
    {
        // TODO: Push this check to getPropertyKeyId
        // ^^^^^ actually, if the key is null, we could fail before getting the statement context...
        if ( null == key )
            throw new IllegalArgumentException( "(null) property key is not allowed" );

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if ( propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                return false;
            }
            return ctxForReading.entityReadOperations().graphGetProperty( state, propertyId ).value();
        }
        catch ( PropertyKeyIdNotFoundException | PropertyNotFoundException e )
        {
            throw new NotFoundException( e );
        }
    }

    @Override
    public Object getProperty( String key )
    {
        // TODO: Push this check to getPropertyKeyId
        // ^^^^^ actually, if the key is null, we could fail before getting the statement context...
        if ( null == key )
            throw new IllegalArgumentException( "(null) property key is not allowed" );

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        StatementState state = statementCtxProvider.statementForReading();
        try
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if(propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                return false;
            }
            return ctxForReading.entityReadOperations().graphGetProperty( state, propertyId ).value();
        }
        catch ( PropertyKeyIdNotFoundException | PropertyNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public getProperty(key String) : Object from class org.neo4j.kernel.impl.core.GraphPropertiesImpl


    @Override
    public Object getProperty( String key, Object defaultValue )
    {
        if ( null == key )
            throw new IllegalArgumentException( "(null) property key is not allowed" );

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if ( propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                return false;
            }
            return ctxForReading.entityReadOperations().graphGetProperty( state, propertyId ).value( defaultValue );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            return defaultValue;
        }
    }

    @Override
    public Object getProperty( String key, Object defaultValue )
    {
        if ( null == key )
            throw new IllegalArgumentException( "(null) property key is not allowed" );

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        StatementState state = statementCtxProvider.statementForReading();
        try
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if(propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                return false;
            }
            return ctxForReading.entityReadOperations().graphGetProperty( state, propertyId ).value(defaultValue);
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            return defaultValue;
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public getProperty(key String, defaultValue Object) : Object from class org.neo4j.kernel.impl.core.GraphPropertiesImpl


    @Override
    public void setProperty( String key, Object value )
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        boolean success = false;
        try ( StatementState state = statementCtxProvider.statementForWriting() )
        {
            long propertyKeyId = ctxForWriting.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            ctxForWriting.entityWriteOperations().graphSetProperty( state, property( propertyKeyId, value ) );
            success = true;
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
        finally
        {
            if ( !success )
            {
                nodeManager.setRollbackOnly();
            }
        }
    }

    @Override
    public void setProperty( String key, Object value )
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        StatementState state = statementCtxProvider.statementForWriting();
        boolean success = false;
        try
        {
            long propertyKeyId = ctxForWriting.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            ctxForWriting.entityWriteOperations().graphSetProperty( state, property( propertyKeyId, value ) );
            success = true;
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
        finally
        {
            state.close();
            if ( !success )
            {
                nodeManager.setRollbackOnly();
            }
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForWriting()) in method public setProperty(key String, value Object) : void from class org.neo4j.kernel.impl.core.GraphPropertiesImpl


    @Override
    public Object removeProperty( String key )
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        try ( StatementState state = statementCtxProvider.statementForWriting() )
        {
            long propertyId = ctxForWriting.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            return ctxForWriting.entityWriteOperations().graphRemoveProperty( state, propertyId ).value( null );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
    }

    @Override
    public Object removeProperty( String key )
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        StatementState state = statementCtxProvider.statementForWriting();
        try
        {
            long propertyId = ctxForWriting.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            return ctxForWriting.entityWriteOperations().graphRemoveProperty( state, propertyId ).value( null );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForWriting()) in method public removeProperty(key String) : Object from class org.neo4j.kernel.impl.core.GraphPropertiesImpl


    @Override
    public Iterable<String> getPropertyKeys()
    {
        final StatementOperationParts context = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            List<String> keys = new ArrayList<>();
            PrimitiveLongIterator keyIds = context.entityReadOperations().graphGetPropertyKeys( state );
            while ( keyIds.hasNext() )
            {
                keys.add( context.keyReadOperations().propertyKeyGetName( state, keyIds.next() ) );
            }
            return keys;
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Jake",
                                                "Property key retrieved through kernel API should exist." );
        }
    }

    @Override
    public Iterable<String> getPropertyKeys()
    {
        final StatementOperationParts context = statementCtxProvider.getCtxForReading();
        final StatementState state = statementCtxProvider.statementForReading();
        try
        {
            List<String> keys = new ArrayList<>();
            PrimitiveLongIterator keyIds = context.entityReadOperations().graphGetPropertyKeys( state );
            while ( keyIds.hasNext() )
            {
                keys.add( context.keyReadOperations().propertyKeyGetName( state, keyIds.next() ) );
            }
            return keys;
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Jake",
                    "Property key retrieved through kernel API should exist." );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public getPropertyKeys() : Iterable<String> from class org.neo4j.kernel.impl.core.GraphPropertiesImpl


    @Override
    public Iterable<Object> getPropertyValues()
    {
        final StatementOperationParts context = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            return asSet( map( new Function<SafeProperty, Object>()
            {
                @Override
                public Object apply( SafeProperty prop )
                {
                    return prop.value();
                }
            }, context.entityReadOperations().graphGetAllProperties( state ) ) );
        }
    }

    @Override
    public Iterable<Object> getPropertyValues()
    {
        final StatementOperationParts context = statementCtxProvider.getCtxForReading();
        StatementState state = statementCtxProvider.statementForReading();
        try
        {
            return asSet( map( new Function<Property,Object>() {
                @Override
                public Object apply( Property prop )
                {
                    try
                    {
                        return prop.value();
                    }
                    catch ( PropertyNotFoundException e )
                    {
                        throw new ThisShouldNotHappenError( "Jake",
                                "Property key retrieved through kernel API should exist." );
                    }
                }
            }, context.entityReadOperations().graphGetAllProperties( state ) ) );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public getPropertyValues() : Iterable<Object> from class org.neo4j.kernel.impl.core.GraphPropertiesImpl


    private Iterator<SafeProperty> ensurePropertiesLoaded( StatementState state, CacheLoader<Iterator<SafeProperty>> loader,
            CacheUpdateListener updateListener )
    {
        if ( !hasLoadedProperties() ) synchronized ( this )
        {
            if ( !hasLoadedProperties() )
            {
                try
                {
                    Iterator<SafeProperty> loadedProperties = loader.load( state, getId() );
                    setProperties( loadedProperties );
                    updateListener.newSize( this, sizeOfObjectInBytesIncludingOverhead() );
                }
                catch ( InvalidRecordException | EntityNotFoundException e )
                {
                    throw new NotFoundException( this + " not found. This can be because someone " +
                            "else deleted this entity while we were trying to read properties from it, or because of " +
                            "concurrent modification of other properties on this entity. The problem should be temporary.", e );
                }
            }
        }
        return getCachedProperties();
    }

    private Iterator<Property> ensurePropertiesLoaded( StatementState state, CacheLoader<Iterator<Property>> loader,
            CacheUpdateListener updateListener )
    {
        if ( !hasLoadedProperties() ) synchronized ( this )
        {
            if ( !hasLoadedProperties() )
            {
                try
                {
                    Iterator<Property> loadedProperties = loader.load( state, getId() );
                    setProperties( loadedProperties );
                    updateListener.newSize( this, sizeOfObjectInBytesIncludingOverhead() );
                }
                catch ( InvalidRecordException e )
                {
                    throw new NotFoundException( this + " not found. This can be because someone " +
                            "else deleted this entity while we were trying to read properties from it, or because of " +
                            "concurrent modification of other properties on this entity. The problem should be temporary.", e );
                }
                catch ( EntityNotFoundException e )
                {
                    throw new NotFoundException( this + " not found. This can be because someone " +
                            "else deleted this entity while we were trying to read properties from it, or because of " +
                            "concurrent modification of other properties on this entity. The problem should be temporary.", e );
                }
            }
        }
        return getCachedProperties();
    }

Merge Catch [catch(InvalidRecordException e), catch(EntityNotFoundException e)] to catch(InvalidRecordException|EntityNotFoundException e) in method private ensurePropertiesLoaded(state StatementState, loader CacheLoader<Iterator<SafeProperty>>, updateListener CacheUpdateListener) : Iterator<SafeProperty> from class org.neo4j.kernel.impl.core.Primitive


    @Override
    public void delete()
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        try ( StatementState state = statementCtxProvider.statementForWriting() )
        {
            ctxForWriting.entityWriteOperations().relationshipDelete( state, getId() );
        }
    }

    @Override
    public void delete()
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        StatementState state = statementCtxProvider.statementForWriting();
        try
        {
            ctxForWriting.entityWriteOperations().relationshipDelete( state, getId() );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForWriting()) in method public delete() : void from class org.neo4j.kernel.impl.core.RelationshipProxy


    @Override
    public Iterable<String> getPropertyKeys()
    {
        final StatementOperationParts context = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            List<String> keys = new ArrayList<>();
            PrimitiveLongIterator keyIds = context.entityReadOperations().relationshipGetPropertyKeys( state, getId() );
            while ( keyIds.hasNext() )
            {
                keys.add( context.keyReadOperations().propertyKeyGetName( state, keyIds.next() ) );
            }
            return keys;
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( "Relationship not found", e );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Jake",
                                                "Property key retrieved through kernel API should exist." );
        }
    }

    @Override
    public Iterable<String> getPropertyKeys()
    {
        final StatementOperationParts context = statementCtxProvider.getCtxForReading();
        final StatementState state = statementCtxProvider.statementForReading();
        try
        {
            List<String> keys = new ArrayList<>();
            PrimitiveLongIterator keyIds = context.entityReadOperations().relationshipGetPropertyKeys( state, getId() );
            while ( keyIds.hasNext() )
            {
                keys.add( context.keyReadOperations().propertyKeyGetName( state, keyIds.next() ) );
            }
            return keys;

        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( "Relationship not found", e );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Jake",
                    "Property key retrieved through kernel API should exist." );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public getPropertyKeys() : Iterable<String> from class org.neo4j.kernel.impl.core.RelationshipProxy


    @Override
    public Iterable<Object> getPropertyValues()
    {
        final StatementOperationParts context = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            return asSet( map( new Function<SafeProperty, Object>()
            {
                @Override
                public Object apply( SafeProperty prop )
                {
                    return prop.value();
                }
            }, context.entityReadOperations().relationshipGetAllProperties( state, getId() ) ) );
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( "Relationship has been deleted", e );
        }
    }

    @Override
    public Iterable<Object> getPropertyValues()
    {
        final StatementOperationParts context = statementCtxProvider.getCtxForReading();
        StatementState state = statementCtxProvider.statementForReading();
        try
        {
            return asSet( map( new Function<Property,Object>() {
                @Override
                public Object apply( Property prop )
                {
                    try
                    {
                        return prop.value();
                    }
                    catch ( PropertyNotFoundException e )
                    {
                        throw new ThisShouldNotHappenError( "Jake",
                                "Property key retrieved through kernel API should exist." );
                    }
                }
            }, context.entityReadOperations().relationshipGetAllProperties( state, getId() )));
        }
        catch ( EntityNotFoundException e )
        {
            throw new NotFoundException( "Relationship has been deleted", e );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public getPropertyValues() : Iterable<Object> from class org.neo4j.kernel.impl.core.RelationshipProxy


    @Override
    public Object getProperty( String key )
    {
        if ( null == key )
            throw new IllegalArgumentException( "(null) property key is not allowed" );

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if ( propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                throw new NotFoundException( String.format( "No such property, '%s'.", key ) );
            }
            return ctxForReading.entityReadOperations().relationshipGetProperty( state, relId, propertyId ).value();
        }
        catch ( EntityNotFoundException | PropertyKeyIdNotFoundException | PropertyNotFoundException e )
        {
            throw new NotFoundException( e );
        }
    }

    @Override
    public Object getProperty( String key )
    {
        if ( null == key )
            throw new IllegalArgumentException( "(null) property key is not allowed" );

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        StatementState state = statementCtxProvider.statementForReading();
        try
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if(propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                throw new NotFoundException( String.format("No such property, '%s'.", key) );
            }
            return ctxForReading.entityReadOperations().relationshipGetProperty( state, relId, propertyId ).value();
        }
        catch ( EntityNotFoundException | PropertyKeyIdNotFoundException | PropertyNotFoundException e )
        {
            throw new NotFoundException( e );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public getProperty(key String) : Object from class org.neo4j.kernel.impl.core.RelationshipProxy


    @Override
    public Object getProperty( String key, Object defaultValue )
    {
        // TODO: Push this check to getPropertyKeyId
        // ^^^^^ actually, if the key is null, we could fail before getting the statement context...
        if ( null == key )
            throw new IllegalArgumentException( "(null) property key is not allowed" );

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if ( propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                return defaultValue;
            }
            return ctxForReading.entityReadOperations().relationshipGetProperty( state, relId, propertyId )
                                .value( defaultValue );
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( e );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            return defaultValue;
        }
    }

    @Override
    public Object getProperty( String key, Object defaultValue )
    {
        // TODO: Push this check to getPropertyKeyId
        // ^^^^^ actually, if the key is null, we could fail before getting the statement context...
        if ( null == key )
            throw new IllegalArgumentException( "(null) property key is not allowed" );

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        StatementState state = statementCtxProvider.statementForReading();
        try
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            if(propertyId == KeyReadOperations.NO_SUCH_PROPERTY_KEY )
            {
                return defaultValue;
            }
            return ctxForReading.entityReadOperations().relationshipGetProperty( state, relId, propertyId ).value(defaultValue);
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( e );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            return defaultValue;
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public getProperty(key String, defaultValue Object) : Object from class org.neo4j.kernel.impl.core.RelationshipProxy


    @Override
    public boolean hasProperty( String key )
    {
        if ( null == key )
            return false;

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        try ( StatementState state = statementCtxProvider.statementForReading() )
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            return propertyId != KeyReadOperations.NO_SUCH_PROPERTY_KEY &&
                   ctxForReading.entityReadOperations().relationshipHasProperty( state, relId, propertyId );
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( e );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            return false;
        }
    }

    @Override
    public boolean hasProperty( String key )
    {
        if ( null == key )
            return false;

        StatementOperationParts ctxForReading = statementCtxProvider.getCtxForReading();
        StatementState state = statementCtxProvider.statementForReading();
        try
        {
            long propertyId = ctxForReading.keyReadOperations().propertyKeyGetForName( state, key );
            return propertyId != KeyReadOperations.NO_SUCH_PROPERTY_KEY &&
                   ctxForReading.entityReadOperations().relationshipHasProperty( state, relId, propertyId );
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( e );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            return false;
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForReading()) in method public hasProperty(key String) : boolean from class org.neo4j.kernel.impl.core.RelationshipProxy


    @Override
    public void setProperty( String key, Object value )
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        boolean success = false;
        try ( StatementState state = statementCtxProvider.statementForWriting() )
        {
            long propertyKeyId = ctxForWriting.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            ctxForWriting.entityWriteOperations()
                         .relationshipSetProperty( state, relId, Property.property( propertyKeyId, value ) );
            success = true;
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( e );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
        finally
        {
            if ( !success )
            {
                relationshipLookups.getNodeManager().setRollbackOnly();
            }
        }
    }

    @Override
    public void setProperty( String key, Object value )
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        StatementState state = statementCtxProvider.statementForWriting();
        boolean success = false;
        try
        {
            long propertyKeyId = ctxForWriting.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            ctxForWriting.entityWriteOperations().relationshipSetProperty( state, relId, Property.property( propertyKeyId, value ) );
            success = true;
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( e );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
        finally
        {
            state.close();
            if ( !success )
            {
                relationshipLookups.getNodeManager().setRollbackOnly();
            }
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForWriting()) in method public setProperty(key String, value Object) : void from class org.neo4j.kernel.impl.core.RelationshipProxy


    @Override
    public Object removeProperty( String key )
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        try ( StatementState state = statementCtxProvider.statementForWriting() )
        {
            long propertyId = ctxForWriting.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            return ctxForWriting.entityWriteOperations().relationshipRemoveProperty( state, relId, propertyId )
                                .value( null );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( e );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
    }

    @Override
    public Object removeProperty( String key )
    {
        StatementOperationParts ctxForWriting = statementCtxProvider.getCtxForWriting();
        StatementState state = statementCtxProvider.statementForWriting();
        try
        {
            long propertyId = ctxForWriting.keyWriteOperations().propertyKeyGetOrCreateForName( state, key );
            return ctxForWriting.entityWriteOperations().relationshipRemoveProperty( state, relId, propertyId ).value( null );
        }
        catch ( PropertyKeyIdNotFoundException e )
        {
            throw new ThisShouldNotHappenError( "Stefan/Jake", "A property key id disappeared under our feet" );
        }
        catch ( EntityNotFoundException e )
        {
            throw new IllegalStateException( e );
        }
        catch ( SchemaKernelException e )
        {
            // TODO: Maybe throw more context-specific error than just IllegalArgument
            throw new IllegalArgumentException( e );
        }
        finally
        {
            state.close();
        }
    }

Try With Resources try(StatementState state=statementCtxProvider.statementForWriting()) in method public removeProperty(key String) : Object from class org.neo4j.kernel.impl.core.RelationshipProxy


    @Override
    public Response<Void> finishTransaction( RequestContext context, final boolean success )
    {
        try
        {
            return sendRequest( HaRequestType20.FINISH, context, new Serializer()
            {
                @Override
                public void write( ChannelBuffer buffer, ByteBuffer readBuffer ) throws IOException
                {
                    buffer.writeByte( success ? 1 : 0 );
                }
            }, VOID_DESERIALIZER );
        }
        catch ( UnableToResumeTransactionException e )
        {
            if ( !success )
            {
                /* Here we are in a state where the client failed while the request
                 * was processing on the server and the tx.finish() in the usual
                 * try-finally transaction block gets called, only to find that
                 * the transaction is already active... which is totally expected.
                 * The fact that the transaction is already active here shouldn't
                 * hide the original exception on the client, the exception which
                 * cause the client to fail while the request was processing on the master.
                 * This is effectively the use case of awaiting a lock that isn't granted
                 * within the lock read timeout period.
                 */
                return new Response<>( null, getStoreId(), TransactionStream.EMPTY, ResourceReleaser.NO_OP );
            }
            throw e;
        }
    }

    @Override
    public Response<Void> finishTransaction( RequestContext context, final boolean success )
    {
        try
        {
            return sendRequest( HaRequestType20.FINISH, context, new Serializer()
            {
                @Override
                public void write( ChannelBuffer buffer, ByteBuffer readBuffer ) throws IOException
                {
                    buffer.writeByte( success ? 1 : 0 );
                }
            }, VOID_DESERIALIZER );
        }
        catch ( UnableToResumeTransactionException e )
        {
            if ( !success )
            {
                /* Here we are in a state where the client failed while the request
                 * was processing on the server and the tx.finish() in the usual
                 * try-finally transaction block gets called, only to find that
                 * the transaction is already active... which is totally expected.
                 * The fact that the transaction is already active here shouldn't
                 * hide the original exception on the client, the exception which
                 * cause the client to fail while the request was processing on the master.
                 * This is effectively the use case of awaiting a lock that isn't granted
                 * within the lock read timeout period.
                 */
                return new Response<Void>( null, getStoreId(), TransactionStream.EMPTY, ResourceReleaser.NO_OP );
            }
            throw e;
        }
    }

Replace Generic With Diamond Response<Void> with Response<> in method public finishTransaction(context RequestContext, success boolean) : Response<Void> from class org.neo4j.kernel.ha.MasterClient20


            /** Create a copy to make iteration safe, while minimizing the duration of the synchronized region. */
            @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
            private Iterable<Map.Entry<RequestContext, MasterTransaction>> transactions()
            {
                Map<RequestContext, MasterTransaction> transactions = MasterImpl.this.transactions;
                synchronized ( transactions )
                {
                    return new HashMap<>( transactions ).entrySet();
                }
            }

            /** Create a copy to make iteration safe, while minimizing the duration of the synchronized region. */
            @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
            private Iterable<Map.Entry<RequestContext, MasterTransaction>> transactions()
            {
                Map<RequestContext, MasterTransaction> transactions = MasterImpl.this.transactions;
                synchronized ( transactions )
                {
                    return new HashMap<RequestContext, MasterTransaction>( transactions ).entrySet();
                }
            }

Replace Generic With Diamond HashMap<RequestContext,MasterTransaction> with HashMap<> in method private transactions() : Iterable<Map.Entry<RequestContext,MasterTransaction>> from class org.neo4j.kernel.ha.com.master.MasterImpl.start.scheduleWithFixedDelay.new Runnable


    @Override
    public void start() throws Throwable
    {
        this.unfinishedTransactionThresholdMillis = config.get( HaSettings.lock_read_timeout );
        this.unfinishedTransactionsExecutor =
                Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory( "Unfinished transaction reaper" ) );
        this.unfinishedTransactionsExecutor.scheduleWithFixedDelay( new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    for ( Map.Entry<RequestContext, MasterTransaction> entry : transactions() )
                    {
                        long time = entry.getValue().timeLastSuspended.get();
                        if ( (time != 0 && System.currentTimeMillis() - time >= unfinishedTransactionThresholdMillis)
                                || entry.getValue().finishAsap() )
                        {
                            long displayableTime = (time == 0 ? 0 : (System.currentTimeMillis() - time));
                            msgLog.logMessage( "Found old tx " + entry.getKey() + ", " +
                                    "" + entry.getValue().transaction + ", " + displayableTime );
                            try
                            {
                                Transaction otherTx = suspendOtherAndResumeThis( entry.getKey(), false );
                                finishThisAndResumeOther( otherTx, entry.getKey(), false );
                                msgLog.logMessage( "Rolled back old tx " + entry.getKey() + ", " +
                                        "" + entry.getValue().transaction + ", " + displayableTime );
                            }
                            catch ( IllegalStateException e )
                            {
                                // Expected for waiting transactions
                            }
                            catch ( Throwable t )
                            {
                                // Not really expected
                                msgLog.logMessage( "Unable to roll back old tx " + entry.getKey() + ", " +
                                        "" + entry.getValue().transaction + ", " + displayableTime, t );
                            }
                        }
                    }
                }
                catch ( Throwable t )
                {
                    // The show must go on
                    msgLog.logMessage( "Exception in MasterImpl", t );
                }
            }

            /** Create a copy to make iteration safe, while minimizing the duration of the synchronized region. */
            @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
            private Iterable<Map.Entry<RequestContext, MasterTransaction>> transactions()
            {
                Map<RequestContext, MasterTransaction> transactions = MasterImpl.this.transactions;
                synchronized ( transactions )
                {
                    return new HashMap<>( transactions ).entrySet();
                }
            }
        }, UNFINISHED_TRANSACTION_CLEANUP_DELAY, UNFINISHED_TRANSACTION_CLEANUP_DELAY, TimeUnit.SECONDS );
    }

    @Override
    public void start() throws Throwable
    {
        this.unfinishedTransactionThresholdMillis = config.get( HaSettings.lock_read_timeout );
        this.unfinishedTransactionsExecutor =
                Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory( "Unfinished transaction reaper" ) );
        this.unfinishedTransactionsExecutor.scheduleWithFixedDelay( new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    for ( Map.Entry<RequestContext, MasterTransaction> entry : transactions() )
                    {
                        long time = entry.getValue().timeLastSuspended.get();
                        if ( (time != 0 && System.currentTimeMillis() - time >= unfinishedTransactionThresholdMillis)
                                || entry.getValue().finishAsap() )
                        {
                            long displayableTime = (time == 0 ? 0 : (System.currentTimeMillis() - time));
                            msgLog.logMessage( "Found old tx " + entry.getKey() + ", " +
                                    "" + entry.getValue().transaction + ", " + displayableTime );
                            try
                            {
                                Transaction otherTx = suspendOtherAndResumeThis( entry.getKey(), false );
                                finishThisAndResumeOther( otherTx, entry.getKey(), false );
                                msgLog.logMessage( "Rolled back old tx " + entry.getKey() + ", " +
                                        "" + entry.getValue().transaction + ", " + displayableTime );
                            }
                            catch ( IllegalStateException e )
                            {
                                // Expected for waiting transactions
                            }
                            catch ( Throwable t )
                            {
                                // Not really expected
                                msgLog.logMessage( "Unable to roll back old tx " + entry.getKey() + ", " +
                                        "" + entry.getValue().transaction + ", " + displayableTime, t );
                            }
                        }
                    }
                }
                catch ( Throwable t )
                {
                    // The show must go on
                    msgLog.logMessage( "Exception in MasterImpl", t );
                }
            }

            /** Create a copy to make iteration safe, while minimizing the duration of the synchronized region. */
            @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
            private Iterable<Map.Entry<RequestContext, MasterTransaction>> transactions()
            {
                Map<RequestContext, MasterTransaction> transactions = MasterImpl.this.transactions;
                synchronized ( transactions )
                {
                    return new HashMap<RequestContext, MasterTransaction>( transactions ).entrySet();
                }
            }
        }, UNFINISHED_TRANSACTION_CLEANUP_DELAY, UNFINISHED_TRANSACTION_CLEANUP_DELAY, TimeUnit.SECONDS );
    }

Replace Generic With Diamond HashMap<RequestContext,MasterTransaction> with HashMap<> in method public start() : void from class org.neo4j.kernel.ha.com.master.MasterImpl


    private Transaction beginTx( RequestContext txId )
    {
        try
        {
            txManager.begin();
            Transaction tx = txManager.getTransaction();
            transactions.put( txId, new MasterTransaction( tx ) );
            return tx;
        }
        catch ( NotSupportedException | SystemException e )
        {
            throw new RuntimeException( e );
        }
    }

    private Transaction beginTx( RequestContext txId )
    {
        try
        {
            txManager.begin();
            Transaction tx = txManager.getTransaction();
            transactions.put( txId, new MasterTransaction( tx ) );
            return tx;
        }
        catch ( NotSupportedException e )
        {
            throw new RuntimeException( e );
        }
        catch ( SystemException e )
        {
            throw new RuntimeException( e );
        }
    }

Merge Catch [catch(NotSupportedException e), catch(SystemException e)] to catch(NotSupportedException|SystemException e) in method private beginTx(txId RequestContext) : Transaction from class org.neo4j.kernel.ha.com.master.MasterImpl