    @Override
    protected JMXServiceURL getJMXServiceURL( KernelData kernel )
    {
        JMXServiceURL url = null;
        Log log = kernel.graphDatabase().getDependencyResolver().resolveDependency( LogService.class )
                .getInternalLog( HotspotManagementSupport.class );
        try
        {
            Class<?> cal = Class.forName( "sun.management.ConnectorAddressLink" );
            try
            {
                Method importRemoteFrom = cal.getMethod( "importRemoteFrom", int.class );
                @SuppressWarnings("unchecked")
                Map<String, String> remote = (Map<String, String>) importRemoteFrom.invoke( null, 0 );
                url = getUrlFrom( remote );
            }
            catch ( NoSuchMethodException ex )
            {
                // handled by null check
            }
            if ( url == null )
            {
                Method importFrom = cal.getMethod( "importFrom", int.class );
                url = getUrlFrom( (String) importFrom.invoke( null, 0 ) );
            }
        }
        catch ( InvocationTargetException e )
        {
            log.warn( "Failed to load local JMX connection URL.", e.getTargetException() );
        }
        catch ( LinkageError | Exception e )
        {
            log.warn( "Failed to load local JMX connection URL.", e );
        }
        // No previous connection server -- create one!
        if ( url == null )
        {
            int port = 0;
            try
            {
                port = kernel.getConfig().get( setting( "jmx.port", INTEGER, "0" ) );
            }
            catch ( NumberFormatException ok )
            {
                // handled by 0-check
            }
            if ( port > 0 )
            {
                boolean useSSL = kernel.getConfig().get( setting( "jmx.use_ssl", BOOLEAN, "false" ) );
                log.debug( "Creating new MBean server on port %s%s", port, useSSL ? " using ssl" : "" );
                JMXConnectorServer server = createServer( port, useSSL, log );
                if ( server != null )
                {
                    try
                    {
                        server.start();
                    }
                    catch ( IOException e )
                    {
                        log.warn( "Failed to start MBean server", e );
                        server = null;
                    }
                    if ( server != null )
                    {
                        try
                        {
                            server.getMBeanServer().registerMBean( server,
                                    KernelProxy.createObjectName( kernel.instanceId(), "JMX Server" ) );
                        }
                        catch ( Exception e )
                        {
                            log.warn( "Failed to register MBean server as JMX bean", e );
                        }
                        url = server.getAddress();
                    }
                }
            }
        }
        return url;
    }

    @Override
    protected JMXServiceURL getJMXServiceURL( KernelData kernel )
    {
        JMXServiceURL url = null;
        Log log = kernel.graphDatabase().getDependencyResolver().resolveDependency( LogService.class )
                .getInternalLog( HotspotManagementSupport.class );
        try
        {
            Class<?> cal = Class.forName( "sun.management.ConnectorAddressLink" );
            try
            {
                Method importRemoteFrom = cal.getMethod( "importRemoteFrom", int.class );
                @SuppressWarnings("unchecked")
                Map<String, String> remote = (Map<String, String>) importRemoteFrom.invoke( null, 0 );
                url = getUrlFrom( remote );
            }
            catch ( NoSuchMethodException ex )
            {
                // handled by null check
            }
            if ( url == null )
            {
                Method importFrom = cal.getMethod( "importFrom", int.class );
                url = getUrlFrom( (String) importFrom.invoke( null, 0 ) );
            }
        }
        catch ( InvocationTargetException e )
        {
            log.warn( "Failed to load local JMX connection URL.", e.getTargetException() );
        }
        catch ( LinkageError e )
        {
            log.warn( "Failed to load local JMX connection URL.", e );
        }
        catch ( Exception e )
        {
            log.warn( "Failed to load local JMX connection URL.", e );
        }
        // No previous connection server -- create one!
        if ( url == null )
        {
            int port = 0;
            try
            {
                port = Integer.parseInt( kernel.getConfig().getParams().get( "jmx.port" ) );
            }
            catch ( NumberFormatException ok )
            {
                // handled by 0-check
            }
            if ( port > 0 )
            {
                boolean useSSL = Boolean.parseBoolean( kernel.getConfig().getParams().get( "jmx.use_ssl" ) );
                log.debug( "Creating new MBean server on port %s%s", port, useSSL ? " using ssl" : "" );
                JMXConnectorServer server = createServer( port, useSSL, log );
                if ( server != null )
                {
                    try
                    {
                        server.start();
                    }
                    catch ( IOException e )
                    {
                        log.warn( "Failed to start MBean server", e );
                        server = null;
                    }
                    if ( server != null )
                    {
                        try
                        {
                            server.getMBeanServer().registerMBean( server,
                                    KernelProxy.createObjectName( kernel.instanceId(), "JMX Server" ) );
                        }
                        catch ( Exception e )
                        {
                            log.warn( "Failed to register MBean server as JMX bean", e );
                        }
                        url = server.getAddress();
                    }
                }
            }
        }
        return url;
    }

Merge Catch [catch(LinkageError e), catch(Exception e)] to catch(LinkageError|Exception e) in method protected getJMXServiceURL(kernel KernelData) : JMXServiceURL from class org.neo4j.management.impl.HotspotManagementSupport


    private JMXServiceURL getUrlFrom( Map<String, String> remote )
    {
        Set<Integer> instances = new HashSet<>();
        for ( String key : remote.keySet() )
        {
            if ( key.startsWith( "sun.management.JMXConnectorServer" ) )
            {
                int end = key.lastIndexOf( '.' );
                if ( end < 0 )
                {
                    continue;
                }
                int start = key.lastIndexOf( '.', end );
                if ( start < 0 )
                {
                    continue;
                }
                final int id;
                try
                {
                    id = Integer.parseInt( key.substring( start, end ) );
                }
                catch ( NumberFormatException e )
                {
                    continue;
                }
                instances.add( id );
            }
        }
        if ( !instances.isEmpty() )
        {
            String prefix = "sun.management.JMXConnectorServer.";
            if ( instances.size() > 1 )
            {
                for ( Object key : instances.toArray() )
                {
                    if ( !remote.containsKey( "sun.management.JMXConnectorServer." + key + ".remoteAddress" ) )
                    {
                        instances.remove( key );
                    }
                }
                if ( instances.contains( Integer.valueOf( 0 ) ) )
                {
                    prefix = prefix + "0.";
                }
            }
            if ( instances.size() == 1 )
            {
                String remoteAddress = remote.get( prefix + instances.iterator().next() + "remoteAddress" );
                try
                {
                    return new JMXServiceURL( remoteAddress );
                }
                catch ( MalformedURLException e )
                {
                    return null;
                }
            }
            else if ( !instances.isEmpty() )
            {
                // TODO: find the appropriate one
            }
        }
        return null;
    }

    private JMXServiceURL getUrlFrom( Map<String, String> remote )
    {
        Set<Integer> instances = new HashSet<Integer>();
        for ( String key : remote.keySet() )
        {
            if ( key.startsWith( "sun.management.JMXConnectorServer" ) )
            {
                int end = key.lastIndexOf( '.' );
                if ( end < 0 )
                {
                    continue;
                }
                int start = key.lastIndexOf( '.', end );
                if ( start < 0 )
                {
                    continue;
                }
                final int id;
                try
                {
                    id = Integer.parseInt( key.substring( start, end ) );
                }
                catch ( NumberFormatException e )
                {
                    continue;
                }
                instances.add( id );
            }
        }
        if ( !instances.isEmpty() )
        {
            String prefix = "sun.management.JMXConnectorServer.";
            if ( instances.size() > 1 )
            {
                for ( Object key : instances.toArray() )
                {
                    if ( !remote.containsKey( "sun.management.JMXConnectorServer." + key + ".remoteAddress" ) )
                    {
                        instances.remove( key );
                    }
                }
                if ( instances.contains( Integer.valueOf( 0 ) ) )
                {
                    prefix = prefix + "0.";
                }
            }
            if ( instances.size() == 1 )
            {
                String remoteAddress = remote.get( prefix + instances.iterator().next() + "remoteAddress" );
                try
                {
                    return new JMXServiceURL( remoteAddress );
                }
                catch ( MalformedURLException e )
                {
                    return null;
                }
            }
            else if ( !instances.isEmpty() )
            {
                // TODO: find the appropriate one
            }
        }
        return null;
    }

Replace Generic With Diamond HashSet<Integer> with HashSet<> in method private getUrlFrom(remote Map<String,String>) : JMXServiceURL from class org.neo4j.management.impl.HotspotManagementSupport


    private JMXConnectorServer createServer( int port, boolean useSSL, Log log )
    {
        MBeanServer server = getMBeanServer();
        final JMXServiceURL url;
        try
        {
            url = new JMXServiceURL( "rmi", null, port );
        }
        catch ( MalformedURLException e )
        {
            log.warn( "Failed to start JMX Server", e );
            return null;
        }
        Map<String, Object> env = new HashMap<>();
        if ( useSSL )
        {
            env.put( RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new SslRMIClientSocketFactory() );
            env.put( RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, new SslRMIServerSocketFactory() );
        }
        try
        {
            return JMXConnectorServerFactory.newJMXConnectorServer( url, env, server );
        }
        catch ( IOException e )
        {
            log.warn( "Failed to start JMX Server", e );
            return null;
        }
    }

    private JMXConnectorServer createServer( int port, boolean useSSL, Log log )
    {
        MBeanServer server = getMBeanServer();
        final JMXServiceURL url;
        try
        {
            url = new JMXServiceURL( "rmi", null, port );
        }
        catch ( MalformedURLException e )
        {
            log.warn( "Failed to start JMX Server", e );
            return null;
        }
        Map<String, Object> env = new HashMap<String, Object>();
        if ( useSSL )
        {
            env.put( RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new SslRMIClientSocketFactory() );
            env.put( RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, new SslRMIServerSocketFactory() );
        }
        try
        {
            return JMXConnectorServerFactory.newJMXConnectorServer( url, env, server );
        }
        catch ( IOException e )
        {
            log.warn( "Failed to start JMX Server", e );
            return null;
        }
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method private createServer(port int, useSSL boolean, log Log) : JMXConnectorServer from class org.neo4j.management.impl.HotspotManagementSupport


    @Test
    public void shouldApplyDefaults()
    {
        Config config = new Config( new HashMap<>(), MySettingsWithDefaults.class );

        assertThat( config.get( MySettingsWithDefaults.hello ), is( "Hello, World!" ) );
    }

    @Test
    public void shouldApplyDefaults()
    {
        Config config = new Config( new HashMap<String, String>(), MySettingsWithDefaults.class );

        assertThat( config.get( MySettingsWithDefaults.hello ), is( "Hello, World!" ) );
    }

Replace Generic With Diamond Config with Config in method public shouldApplyDefaults() : void from class org.neo4j.kernel.configuration.ConfigTest


    @Test
    public void shouldRespondWith200ForGetNodeProperties() throws Exception
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        helper.setNodeProperties( nodeId, properties );
        Response response = service.getAllNodeProperties( nodeId );
        assertEquals( 200, response.getStatus() );

        checkContentTypeCharsetUtf8( response );
    }

    @Test
    public void shouldRespondWith200ForGetNodeProperties() throws Exception
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        helper.setNodeProperties( nodeId, properties );
        Response response = service.getAllNodeProperties( nodeId );
        assertEquals( 200, response.getStatus() );

        checkContentTypeCharsetUtf8( response );
    }

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


    @Test
    public void shouldGetPropertiesForGetNodeProperties() throws Exception
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        properties.put( "double", 15.7 );
        helper.setNodeProperties( nodeId, properties );
        Response response = service.getAllNodeProperties( nodeId );
        String jsonBody = entityAsString( response );
        Map<String, Object> readProperties = JsonHelper.jsonToMap( jsonBody );
        assertEquals( properties, readProperties );
    }

    @Test
    public void shouldGetPropertiesForGetNodeProperties() throws Exception
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        properties.put( "double", 15.7 );
        helper.setNodeProperties( nodeId, properties );
        Response response = service.getAllNodeProperties( nodeId );
        String jsonBody = entityAsString( response );
        Map<String, Object> readProperties = JsonHelper.jsonToMap( jsonBody );
        assertEquals( properties, readProperties );
    }

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


    @Test
    public void shouldRespondWith204ForRemoveNodeProperties()
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        helper.setNodeProperties( nodeId, properties );
        Response response = service.deleteAllNodeProperties( nodeId );
        assertEquals( 204, response.getStatus() );
    }

    @Test
    public void shouldRespondWith204ForRemoveNodeProperties()
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        helper.setNodeProperties( nodeId, properties );
        Response response = service.deleteAllNodeProperties( nodeId );
        assertEquals( 204, response.getStatus() );
    }

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


    @Test
    public void shouldBeAbleToRemoveNodeProperties()
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        helper.setNodeProperties( nodeId, properties );
        service.deleteAllNodeProperties( nodeId );
        assertEquals( true, helper.getNodeProperties( nodeId )
                .isEmpty() );
    }

    @Test
    public void shouldBeAbleToRemoveNodeProperties()
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        helper.setNodeProperties( nodeId, properties );
        service.deleteAllNodeProperties( nodeId );
        assertEquals( true, helper.getNodeProperties( nodeId )
                .isEmpty() );
    }

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


    @Test
    public void shouldBeAbleToRemoveNodeProperty()
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        helper.setNodeProperties( nodeId, properties );
        service.deleteNodeProperty( nodeId, "foo" );
        assertEquals( Collections.singletonMap( "number", (Object) 15 ),
                helper.getNodeProperties( nodeId ) );
    }

    @Test
    public void shouldBeAbleToRemoveNodeProperty()
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        helper.setNodeProperties( nodeId, properties );
        service.deleteNodeProperty( nodeId, "foo" );
        assertEquals( Collections.singletonMap( "number", (Object) 15 ),
                helper.getNodeProperties( nodeId ) );
    }

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


    @Test
    public void shouldGet404WhenRemovingNonExistingProperty() throws Exception
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        helper.setNodeProperties( nodeId, properties );
        Response response = service.deleteNodeProperty( nodeId, "baz" );
        assertEquals( 404, response.getStatus() );
        assertEquals( Statement.NoSuchProperty.code().serialize(), singleErrorCode( response ) );
    }

    @Test
    public void shouldGet404WhenRemovingNonExistingProperty() throws Exception
    {
        long nodeId = helper.createNode();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        properties.put( "number", 15 );
        helper.setNodeProperties( nodeId, properties );
        Response response = service.deleteNodeProperty( nodeId, "baz" );
        assertEquals( 404, response.getStatus() );
        assertEquals( Statement.NoSuchProperty.code().serialize(), singleErrorCode( response ) );
    }

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


    @Test
    public void shouldRespondWith200AndDataForGetRelationshipProperties() throws Exception
    {
        long relationshipId = helper.createRelationship( "knows" );
        Map<String, Object> properties = new HashMap<>();
        properties.put( "foo", "bar" );
        helper.setRelationshipProperties( relationshipId, properties );
        Response response = service.getAllRelationshipProperties( relationshipId );
        assertEquals( 200, response.getStatus() );

        checkContentTypeCharsetUtf8( response );

        Map<String, Object> readProperties = JsonHelper.jsonToMap( entityAsString( response ) );
        assertEquals( properties, readProperties );
    }

    @Test
    public void shouldRespondWith200AndDataForGetRelationshipProperties() throws Exception
    {
        long relationshipId = helper.createRelationship( "knows" );
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "foo", "bar" );
        helper.setRelationshipProperties( relationshipId, properties );
        Response response = service.getAllRelationshipProperties( relationshipId );
        assertEquals( 200, response.getStatus() );

        checkContentTypeCharsetUtf8( response );

        Map<String, Object> readProperties = JsonHelper.jsonToMap( entityAsString( response ) );
        assertEquals( properties, readProperties );
    }

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


    @Test
    public void shouldGet200WhenSuccessfullyRetrievedPropertyOnRelationship()
            throws Exception
    {

        long relationshipId = helper.createRelationship( "knows" );
        Map<String, Object> properties = new HashMap<>();
        properties.put( "some-key", "some-value" );
        helper.setRelationshipProperties( relationshipId, properties );

        Response response = service.getRelationshipProperty( relationshipId, "some-key" );

        assertEquals( 200, response.getStatus() );
        assertEquals( "some-value", JsonHelper.readJson( entityAsString( response ) ) );

        checkContentTypeCharsetUtf8( response );
    }

    @Test
    public void shouldGet200WhenSuccessfullyRetrievedPropertyOnRelationship()
            throws Exception
    {

        long relationshipId = helper.createRelationship( "knows" );
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put( "some-key", "some-value" );
        helper.setRelationshipProperties( relationshipId, properties );

        Response response = service.getRelationshipProperty( relationshipId, "some-key" );

        assertEquals( 200, response.getStatus() );
        assertEquals( "some-value", JsonHelper.readJson( entityAsString( response ) ) );

        checkContentTypeCharsetUtf8( response );
    }

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


    @Test
    public void shouldRespondWith204AndSetCorrectDataWhenSettingRelationshipProperties()

    {
        long relationshipId = helper.createRelationship( "KNOWS" );
        String json = "{\"name\": \"Mattias\", \"age\": 30}";
        Response response = service.setAllRelationshipProperties( relationshipId, json );
        assertEquals( 204, response.getStatus() );
        Map<String, Object> setProperties = new HashMap<>();
        setProperties.put( "name", "Mattias" );
        setProperties.put( "age", 30 );
        assertEquals( setProperties, helper.getRelationshipProperties( relationshipId ) );
    }

    @Test
    public void shouldRespondWith204AndSetCorrectDataWhenSettingRelationshipProperties()

    {
        long relationshipId = helper.createRelationship( "KNOWS" );
        String json = "{\"name\": \"Mattias\", \"age\": 30}";
        Response response = service.setAllRelationshipProperties( relationshipId, json );
        assertEquals( 204, response.getStatus() );
        Map<String, Object> setProperties = new HashMap<String, Object>();
        setProperties.put( "name", "Mattias" );
        setProperties.put( "age", 30 );
        assertEquals( setProperties, helper.getRelationshipProperties( relationshipId ) );
    }

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


    @Test
    public void shouldBeAbleToIndexNode()
    {
        Response response = service.createNode( null );
        URI nodeUri = (URI) response.getMetadata()
                .getFirst( "Location" );

        Map<String, String> postBody = new HashMap<>();
        postBody.put( "key", "mykey" );
        postBody.put( "value", "my/key" );
        postBody.put( "uri", nodeUri.toString() );

        response = service.addToNodeIndex( "node", null, null, JsonHelper.createJsonFrom( postBody ) );

        assertEquals( 201, response.getStatus() );
        assertNotNull( response.getMetadata()
                .getFirst( "Location" ) );
    }

    @Test
    public void shouldBeAbleToIndexNode()
    {
        Response response = service.createNode( null );
        URI nodeUri = (URI) response.getMetadata()
                .getFirst( "Location" );

        Map<String, String> postBody = new HashMap<String, String>();
        postBody.put( "key", "mykey" );
        postBody.put( "value", "my/key" );
        postBody.put( "uri", nodeUri.toString() );

        response = service.addToNodeIndex( "node", null, null, JsonHelper.createJsonFrom( postBody ) );

        assertEquals( 201, response.getStatus() );
        assertNotNull( response.getMetadata()
                .getFirst( "Location" ) );
    }

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


    @Test
    public void shouldBeAbleToIndexNodeUniquely()
    {
        Map<String, String> postBody = new HashMap<>();
        postBody.put( "key", "mykey" );
        postBody.put( "value", "my/key" );

        Response response = service.addToNodeIndex( "unique-nodes", "", "",
                JsonHelper.createJsonFrom( postBody ) );

        assertEquals( 201, response.getStatus() );
        assertNotNull( response.getMetadata().getFirst( "Location" ) );

        response = service.addToNodeIndex( "unique-nodes", "", "",
                JsonHelper.createJsonFrom( postBody ) );

        assertEquals( 200, response.getStatus() );
    }

    @Test
    public void shouldBeAbleToIndexNodeUniquely()
    {
        Map<String, String> postBody = new HashMap<String, String>();
        postBody.put( "key", "mykey" );
        postBody.put( "value", "my/key" );

        Response response = service.addToNodeIndex( "unique-nodes", "", "",
                JsonHelper.createJsonFrom( postBody ) );

        assertEquals( 201, response.getStatus() );
        assertNotNull( response.getMetadata().getFirst( "Location" ) );

        response = service.addToNodeIndex( "unique-nodes", "", "",
                JsonHelper.createJsonFrom( postBody ) );

        assertEquals( 200, response.getStatus() );
    }

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


    @Test
    public void shouldNotBeAbleToIndexNodeUniquelyWithBothUriAndPropertiesInPayload() throws Exception
    {
        URI node = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );
        Map<String, Object> postBody = new HashMap<>();
        postBody.put( "key", "mykey" );
        postBody.put( "value", "my/key" );
        postBody.put( "uri", node.toString() );
        postBody.put( "properties", new HashMap<String,Object>() );

        Response response = service.addToNodeIndex( "unique-nodes", "", "",
                JsonHelper.createJsonFrom( postBody ) );
        assertEquals( 400, response.getStatus() );
        assertEquals( Statement.InvalidArguments.code().serialize(), singleErrorCode( response ) );
    }

    @Test
    public void shouldNotBeAbleToIndexNodeUniquelyWithBothUriAndPropertiesInPayload() throws Exception
    {
        URI node = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );
        Map<String, Object> postBody = new HashMap<String, Object>();
        postBody.put( "key", "mykey" );
        postBody.put( "value", "my/key" );
        postBody.put( "uri", node.toString() );
        postBody.put( "properties", new HashMap<String,Object>() );

        Response response = service.addToNodeIndex( "unique-nodes", "", "",
                JsonHelper.createJsonFrom( postBody ) );
        assertEquals( 400, response.getStatus() );
        assertEquals( Statement.InvalidArguments.code().serialize(), singleErrorCode( response ) );
    }

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


    @Test
    public void uniquelyIndexedNodeGetsTheSpecifiedKeyAndValueAsPropertiesIfNoPropertiesAreSpecified() throws Exception
    {
        final String key = "somekey", value = "somevalue";

        Map<String, Object> postBody = new HashMap<>();
        postBody.put( "key", key );
        postBody.put( "value", value );

        Response response = service.addToNodeIndex( "unique-nodes", "", "",
                JsonHelper.createJsonFrom( postBody ) );
        assertEquals( 201, response.getStatus() );
        Object node = response.getMetadata().getFirst( "Location" );
        assertNotNull( node );
        String uri = node.toString();
        Map<String, Object> properties = helper.getNodeProperties( parseLong( uri.substring( uri.lastIndexOf(
                '/' ) + 1 ) ) );
        assertEquals( 1, properties.size() );
        assertEquals( value, properties.get( key ) );
    }

    @Test
    public void uniquelyIndexedNodeGetsTheSpecifiedKeyAndValueAsPropertiesIfNoPropertiesAreSpecified() throws Exception
    {
        final String key = "somekey", value = "somevalue";

        Map<String, Object> postBody = new HashMap<String, Object>();
        postBody.put( "key", key );
        postBody.put( "value", value );

        Response response = service.addToNodeIndex( "unique-nodes", "", "",
                JsonHelper.createJsonFrom( postBody ) );
        assertEquals( 201, response.getStatus() );
        Object node = response.getMetadata().getFirst( "Location" );
        assertNotNull( node );
        String uri = node.toString();
        Map<String, Object> properties = helper.getNodeProperties( parseLong( uri.substring( uri.lastIndexOf(
                '/' ) + 1 ) ) );
        assertEquals( 1, properties.size() );
        assertEquals( value, properties.get( key ) );
    }

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


    @Test
    public void shouldBeAbleToIndexRelationshipUniquely() throws Exception
    {
        URI start = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );
        URI end = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );
        Map<String, String> postBody = new HashMap<>();
        postBody.put( "key", "mykey" );
        postBody.put( "value", "my/key" );
        postBody.put( "start", start.toString() );
        postBody.put( "end", end.toString() );
        postBody.put( "type", "knows" );
        for ( int i = 0; i < 2; i++ )
        {
            Response response = service.addToNodeIndex( "unique-relationships", "", "",
                    JsonHelper.createJsonFrom( postBody ) );

            assertEquals( 201 - i, response.getStatus() );
            if ( i == 0 )
            {
                assertNotNull( response.getMetadata().getFirst( "Location" ) );
            }
        }
    }

    @Test
    public void shouldBeAbleToIndexRelationshipUniquely() throws Exception
    {
        URI start = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );
        URI end = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );
        Map<String, String> postBody = new HashMap<String, String>();
        postBody.put( "key", "mykey" );
        postBody.put( "value", "my/key" );
        postBody.put( "start", start.toString() );
        postBody.put( "end", end.toString() );
        postBody.put( "type", "knows" );
        for ( int i = 0; i < 2; i++ )
        {
            Response response = service.addToNodeIndex( "unique-relationships", "", "",
                    JsonHelper.createJsonFrom( postBody ) );

            assertEquals( 201 - i, response.getStatus() );
            if ( i == 0 )
            {
                assertNotNull( response.getMetadata().getFirst( "Location" ) );
            }
        }
    }

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


    @Test
    public void uniquelyIndexedRelationshipGetsTheSpecifiedKeyAndValueAsPropertiesIfNoPropertiesAreSpecified() throws
            Exception
    {
        final String key = "somekey", value = "somevalue";
        URI start = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );
        URI end = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );

        Map<String, Object> postBody = new HashMap<>();
        postBody.put( "key", key );
        postBody.put( "value", value );
        postBody.put( "start", start.toString() );
        postBody.put( "end", end.toString() );
        postBody.put( "type", "knows" );

        Response response = service.addToRelationshipIndex( "unique-relationships", "", "",
                JsonHelper.createJsonFrom( postBody ) );
        assertEquals( 201, response.getStatus() );
        Object rel = response.getMetadata().getFirst( "Location" );
        assertNotNull( rel );
        String uri = rel.toString();
        Map<String, Object> properties = helper.getRelationshipProperties( parseLong( uri.substring( uri
                .lastIndexOf( '/' ) + 1 ) ) );
        assertEquals( 1, properties.size() );
        assertEquals( value, properties.get( key ) );
    }

    @Test
    public void uniquelyIndexedRelationshipGetsTheSpecifiedKeyAndValueAsPropertiesIfNoPropertiesAreSpecified() throws
            Exception
    {
        final String key = "somekey", value = "somevalue";
        URI start = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );
        URI end = (URI) service.createNode( null ).getMetadata().getFirst( "Location" );

        Map<String, Object> postBody = new HashMap<String, Object>();
        postBody.put( "key", key );
        postBody.put( "value", value );
        postBody.put( "start", start.toString() );
        postBody.put( "end", end.toString() );
        postBody.put( "type", "knows" );

        Response response = service.addToRelationshipIndex( "unique-relationships", "", "",
                JsonHelper.createJsonFrom( postBody ) );
        assertEquals( 201, response.getStatus() );
        Object rel = response.getMetadata().getFirst( "Location" );
        assertNotNull( rel );
        String uri = rel.toString();
        Map<String, Object> properties = helper.getRelationshipProperties( parseLong( uri.substring( uri
                .lastIndexOf( '/' ) + 1 ) ) );
        assertEquals( 1, properties.size() );
        assertEquals( value, properties.get( key ) );
    }

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


    private RawIterator<Object[],ProcedureException> callProcedure(
            ProcedureName name, Object[] input, AccessMode read )
            throws ProcedureException
    {
        statement.assertOpen();

        try ( KernelTransaction.Revertable revertable = tx.restrict( read ) )
        {
            CallableProcedure.BasicContext ctx = new CallableProcedure.BasicContext();
            ctx.put( CallableProcedure.Context.KERNEL_TRANSACTION, tx );
            return procedures.call( ctx, name, input );
        }
    }

    private RawIterator<Object[],ProcedureException> callProcedure(
            ProcedureName name, Object[] input, AccessMode read )
            throws ProcedureException
    {
        statement.assertOpen();
        AccessMode originalMode = tx.mode();
        try
        {
            tx.setMode( read );
            CallableProcedure.BasicContext ctx = new CallableProcedure.BasicContext();
            ctx.put( CallableProcedure.Context.KERNEL_TRANSACTION, tx );
            return procedures.call( ctx, name, input );
        }
        finally
        {
            tx.setMode( originalMode );
        }
    }

Try With Resources try(KernelTransaction.Revertable revertable=tx.restrict(read)) in method private callProcedure(name ProcedureName, input Object[], read AccessMode) : RawIterator<Object[],ProcedureException> from class org.neo4j.kernel.impl.api.OperationsFacade


    @Test
    public void begin_and_execute_periodic_commit_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, url -> {
            long nodesInDatabaseBeforeTransaction = countNodes();

            // begin and execute and commit
            Response response = http.POST(
                    "/db/data/transaction/commit",
                    quotedJson( "{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                url + "\\\" AS line CREATE ()' } ] }" )
            );

            assertThat( response.status(), equalTo( 200 ) );
            assertThat( response, containsNoErrors() );
            assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) );
        } );
    }

    @Test
    public void begin_and_execute_periodic_commit_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, new ServerTestUtils.BlockWithCSVFileURL()
        {
            @Override
            public void execute( String url )
            {
                long nodesInDatabaseBeforeTransaction = countNodes();

                // begin and execute and commit
                Response response = http.POST(
                        "/db/data/transaction/commit",
                        quotedJson( "{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                    url + "\\\" AS line CREATE ()' } ] }" )
                );

                assertThat( response.status(), equalTo( 200 ) );
                assertThat( response, containsNoErrors() );
                assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.TransactionIT.begin_and_execute_periodic_commit_and_commit.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {long nodesInDatabaseBeforeTransaction=countNodes(); in method public begin_and_execute_periodic_commit_and_commit() : void from class org.neo4j.server.rest.transactional.integration.TransactionIT


    @Test
    public void begin_and_execute_periodic_commit_that_returns_data_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, url -> {
            long nodesInDatabaseBeforeTransaction = countNodes();

            // begin and execute and commit
            Response response = http.POST(
                    "/db/data/transaction/commit",
                    quotedJson( "{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                url + "\\\" AS line CREATE (n {id: 23}) RETURN n' } ] }" )
            );

            assertThat( response.status(), equalTo( 200 ) );

            assertThat( response, containsNoErrors() );

            JsonNode columns = response.get( "results" ).get( 0 ).get( "columns" );
            assertThat( columns.toString(), equalTo( "[\"n\"]" ) );

            assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) );
        } );
    }

    @Test
    public void begin_and_execute_periodic_commit_that_returns_data_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, new ServerTestUtils.BlockWithCSVFileURL()
        {
            @Override
            public void execute( String url ) throws Exception
            {
                long nodesInDatabaseBeforeTransaction = countNodes();

                // begin and execute and commit
                Response response = http.POST(
                        "/db/data/transaction/commit",
                        quotedJson( "{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                    url + "\\\" AS line CREATE (n {id: 23}) RETURN n' } ] }" )
                );

                assertThat( response.status(), equalTo( 200 ) );

                assertThat( response, containsNoErrors() );

                JsonNode columns = response.get( "results" ).get( 0 ).get( "columns" );
                assertThat( columns.toString(), equalTo( "[\"n\"]" ) );

                assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.TransactionIT.begin_and_execute_periodic_commit_that_returns_data_and_commit.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {long nodesInDatabaseBeforeTransaction=countNodes(); in method public begin_and_execute_periodic_commit_that_returns_data_and_commit() : void from class org.neo4j.server.rest.transactional.integration.TransactionIT


    @Test
    public void begin_and_execute_cypher_23_periodic_commit_that_returns_data_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, url -> {
            long nodesInDatabaseBeforeTransaction = countNodes();

            // begin and execute and commit
            Response response = http.POST(
                    "/db/data/transaction/commit",
                    quotedJson( "{ 'statements': [ { 'statement': 'CYPHER 2.3 USING PERIODIC COMMIT LOAD CSV FROM" +
                                " \\\"" + url + "\\\" AS line CREATE (n {id: 23}) RETURN n' } ] }" )
            );

            assertThat( response.status(), equalTo( 200 ) );

            assertThat( response, containsNoErrors() );

            JsonNode columns = response.get( "results" ).get( 0 ).get( "columns" );
            assertThat( columns.toString(), equalTo( "[\"n\"]" ) );

            assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) );
        } );
    }

    @Test
    public void begin_and_execute_cypher_23_periodic_commit_that_returns_data_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, new ServerTestUtils.BlockWithCSVFileURL()
        {
            @Override
            public void execute( String url ) throws Exception
            {
                long nodesInDatabaseBeforeTransaction = countNodes();

                // begin and execute and commit
                Response response = http.POST(
                        "/db/data/transaction/commit",
                        quotedJson( "{ 'statements': [ { 'statement': 'CYPHER 2.3 USING PERIODIC COMMIT LOAD CSV FROM" +
                                    " \\\"" + url + "\\\" AS line CREATE (n {id: 23}) RETURN n' } ] }" )
                );

                assertThat( response.status(), equalTo( 200 ) );

                assertThat( response, containsNoErrors() );

                JsonNode columns = response.get( "results" ).get( 0 ).get( "columns" );
                assertThat( columns.toString(), equalTo( "[\"n\"]" ) );

                assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.TransactionIT.begin_and_execute_cypher_23_periodic_commit_that_returns_data_and_commit.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {long nodesInDatabaseBeforeTransaction=countNodes(); in method public begin_and_execute_cypher_23_periodic_commit_that_returns_data_and_commit() : void from class org.neo4j.server.rest.transactional.integration.TransactionIT


    @Test
    public void begin_and_execute_periodic_commit_followed_by_another_statement_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, url -> {
            // begin and execute and commit
            Response response = http.POST(
                    "/db/data/transaction/commit",
                    quotedJson( "{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                url +
                                "\\\" AS line CREATE (n {id: 23}) RETURN n' }, { 'statement': 'RETURN 1' } ] }" )
            );

            assertThat( response.status(), equalTo( 200 ) );
            assertThat( response, hasErrors( Status.Statement.InvalidSemantics ) );
        } );
    }

    @Test
    public void begin_and_execute_periodic_commit_followed_by_another_statement_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, new ServerTestUtils.BlockWithCSVFileURL()
        {
            @Override
            public void execute( String url )
            {
                // begin and execute and commit
                Response response = http.POST(
                        "/db/data/transaction/commit",
                        quotedJson( "{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                    url +
                                    "\\\" AS line CREATE (n {id: 23}) RETURN n' }, { 'statement': 'RETURN 1' } ] }" )
                );

                assertThat( response.status(), equalTo( 200 ) );
                assertThat( response, hasErrors( Status.Statement.InvalidSemantics ) );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.TransactionIT.begin_and_execute_periodic_commit_followed_by_another_statement_and_commit.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {Response response=http.POST("/db/data/transaction/commit",quotedJson("{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" + url + "\\\" AS line CREATE (n {id: 23}) RETURN n' }, { 'statement': 'RETURN 1' } ] }")); in method public begin_and_execute_periodic_commit_followed_by_another_statement_and_commit() : void from class org.neo4j.server.rest.transactional.integration.TransactionIT


    @Test
    public void begin_and_execute_multiple_periodic_commit_last_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, url -> {
            // begin and execute and commit
            Response response = http.POST(
                    "/db/data/transaction/commit",
                    quotedJson( "{ 'statements': [ { 'statement': 'CREATE ()' }, " +
                                "{ 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" + url + "\\\" AS line " +
                                "CREATE ()' } ] }" )
            );

            assertThat( response, hasErrors( Status.Statement.InvalidSemantics ) );
        } );
    }

    @Test
    public void begin_and_execute_multiple_periodic_commit_last_and_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, new ServerTestUtils.BlockWithCSVFileURL()
        {
            @Override
            public void execute( String url )
            {
                // begin and execute and commit
                Response response = http.POST(
                        "/db/data/transaction/commit",
                        quotedJson( "{ 'statements': [ { 'statement': 'CREATE ()' }, " +
                                    "{ 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" + url + "\\\" AS line " +
                                    "CREATE ()' } ] }" )
                );

                assertThat( response, hasErrors( Status.Statement.InvalidSemantics ) );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.TransactionIT.begin_and_execute_multiple_periodic_commit_last_and_commit.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {Response response=http.POST("/db/data/transaction/commit",quotedJson("{ 'statements': [ { 'statement': 'CREATE ()' }, " + "{ 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" + url + "\\\" AS line " + "CREATE ()' } ] }")); in method public begin_and_execute_multiple_periodic_commit_last_and_commit() : void from class org.neo4j.server.rest.transactional.integration.TransactionIT


    @Test
    public void begin__execute__execute_and_periodic_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, url -> {
            // begin
            Response begin = http.POST( "/db/data/transaction" );

            // execute
            http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE ()' } ] }" ) );

            // execute
            Response response = http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'USING" +
                                                                         " PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                                                         url + "\\\" AS line CREATE ()' } ] }" ) );

            assertThat( response, hasErrors( Status.Statement.InvalidSemantics ) );
        } );
    }

    @Test
    public void begin__execute__execute_and_periodic_commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, new ServerTestUtils.BlockWithCSVFileURL()
        {
            @Override
            public void execute( String url )
            {
                // begin
                Response begin = http.POST( "/db/data/transaction" );

                // execute
                http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE ()' } ] }" ) );

                // execute
                Response response = http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'USING" +
                                                                             " PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                                                             url + "\\\" AS line CREATE ()' } ] }" ) );

                assertThat( response, hasErrors( Status.Statement.InvalidSemantics ) );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.TransactionIT.begin__execute__execute_and_periodic_commit.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {Response begin=http.POST("/db/data/transaction"); in method public begin__execute__execute_and_periodic_commit() : void from class org.neo4j.server.rest.transactional.integration.TransactionIT


    @Test
    public void begin_and_execute_periodic_commit__commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, url -> {
            // begin and execute
            Response begin = http.POST(
                    "/db/data/transaction",
                    quotedJson( "{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                url + "\\\" AS line CREATE ()' } ] }" )
            );

            assertThat( begin, hasErrors( Status.Statement.InvalidSemantics ) );
        } );
    }

    @Test
    public void begin_and_execute_periodic_commit__commit() throws Exception
    {
        ServerTestUtils.withCSVFile( 1, new ServerTestUtils.BlockWithCSVFileURL()
        {
            @Override
            public void execute( String url )
            {
                // begin and execute
                Response begin = http.POST(
                        "/db/data/transaction",
                        quotedJson( "{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" +
                                    url + "\\\" AS line CREATE ()' } ] }" )
                );

                assertThat( begin, hasErrors( Status.Statement.InvalidSemantics ) );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.TransactionIT.begin_and_execute_periodic_commit__commit.withCSVFile.new ServerTestUtils.BlockWithCSVFileURL with url -> {Response begin=http.POST("/db/data/transaction",quotedJson("{ 'statements': [ { 'statement': 'USING PERIODIC COMMIT LOAD CSV FROM \\\"" + url + "\\\" AS line CREATE ()' } ] }")); in method public begin_and_execute_periodic_commit__commit() : void from class org.neo4j.server.rest.transactional.integration.TransactionIT


    @Test
    public void begin__execute__rollback_concurrently() throws Exception
    {
        // begin
        final Response begin = http.POST( "/db/data/transaction" );
        assertThat( begin.status(), equalTo( 201 ) );
        assertHasTxLocation( begin );

        // execute
        final String executeResource = begin.location();
        final String statement =
                "WITH range(0, 100000) AS r UNWIND r AS i CREATE (n {number: i}) RETURN count(n)";

        final CountDownLatch latch = new CountDownLatch( 1 );

        final Future<Response> executeFuture = Executors.newSingleThreadExecutor().submit( () -> {
            latch.countDown();
            Response response = http.POST( executeResource, quotedJson( "{ 'statements': [ { 'statement': '" +
                                                                        statement + "' } ] }" ) );
            assertThat( response.status(), equalTo( 200 ) );
            return response;

        } );

        // terminate
        final Future<Response> interruptFuture = Executors.newSingleThreadExecutor().submit( () -> {
            try
            {
                latch.await();
                Thread.sleep( 100 );
            }
            catch ( InterruptedException ignored )
            {
                // go
            }
            Response response = http.DELETE( begin.location() );
            assertThat( response.status(), equalTo( 200 ) );
            return response;
        } );

        interruptFuture.get();
        Response execute = executeFuture.get();
        assertThat( execute, hasErrors( Status.Statement.ExecutionFailure ) );

        Response execute2 =
                http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE (n)' } ] }" ) );
        assertThat( execute2.status(), equalTo( 404 ) );
        assertThat( execute2, hasErrors( Status.Transaction.UnknownId ) );
    }

    @Test
    public void begin__execute__rollback_concurrently() throws Exception
    {
        // begin
        final Response begin = http.POST( "/db/data/transaction" );
        assertThat( begin.status(), equalTo( 201 ) );
        assertHasTxLocation( begin );

        // execute
        final String executeResource = begin.location();
        final String statement =
                "WITH range(0, 100000) AS r UNWIND r AS i CREATE (n {number: i}) RETURN count(n)";

        final CountDownLatch latch = new CountDownLatch( 1 );

        final Future<Response> executeFuture = Executors.newSingleThreadExecutor().submit( new Callable<Response>()
        {
            @Override
            public Response call()
            {
                latch.countDown();
                Response response = http.POST( executeResource, quotedJson( "{ 'statements': [ { 'statement': '" +
                                                                            statement + "' } ] }" ) );
                assertThat( response.status(), equalTo( 200 ) );
                return response;

            }
        } );

        // terminate
        final Future<Response> interruptFuture = Executors.newSingleThreadExecutor().submit( new Callable<Response>()
        {
            @Override
            public Response call()
            {
                try
                {
                    latch.await();
                    Thread.sleep( 100 );
                }
                catch ( InterruptedException ignored )
                {
                    // go
                }
                Response response = http.DELETE( begin.location() );
                assertThat( response.status(), equalTo( 200 ) );
                return response;
            }
        } );

        interruptFuture.get();
        Response execute = executeFuture.get();
        assertThat( execute, hasErrors( Status.Statement.ExecutionFailure ) );

        Response execute2 =
                http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE (n)' } ] }" ) );
        assertThat( execute2.status(), equalTo( 404 ) );
        assertThat( execute2, hasErrors( Status.Transaction.UnknownId ) );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.transactional.integration.TransactionIT.begin__execute__rollback_concurrently.interruptFuture.submit.new Callable<Response> with () -> {trylatch.await(); in method public begin__execute__rollback_concurrently() : void from class org.neo4j.server.rest.transactional.integration.TransactionIT


    private StreamingOutput rollback( final TransactionHandle transactionHandle, final URI baseUri )
    {
        return output -> {
            if ( transactionHandle != null )
            {
                transactionHandle.rollback( facade.serializer( output, baseUri ) );
            }
        };
    }

    private StreamingOutput rollback( final TransactionHandle transactionHandle, final URI baseUri )
    {
        return new StreamingOutput()
        {
            @Override
            public void write( OutputStream output ) throws IOException, WebApplicationException
            {
                if ( transactionHandle != null )
                {
                    transactionHandle.rollback( facade.serializer( output, baseUri ) );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.server.rest.web.TransactionalService.rollback.new StreamingOutput with output -> {if(transactionHandle != null){transactionHandle.rollback(facade.serializer(output,baseUri)); in method private rollback(transactionHandle TransactionHandle, baseUri URI) : StreamingOutput from class org.neo4j.server.rest.web.TransactionalService


    private StreamingOutput serializeError( final Neo4jError neo4jError, final URI baseUri )
    {
        return output -> {
            ExecutionResultSerializer serializer = facade.serializer( output, baseUri );
            serializer.errors( Collections.singletonList( neo4jError ) );
            serializer.finish();
        };
    }

    private StreamingOutput serializeError( final Neo4jError neo4jError, final URI baseUri )
    {
        return new StreamingOutput()
        {
            @Override
            public void write( OutputStream output ) throws IOException, WebApplicationException
            {
                ExecutionResultSerializer serializer = facade.serializer( output, baseUri );
                serializer.errors( asList( neo4jError ) );
                serializer.finish();
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.server.rest.web.TransactionalService.serializeError.new StreamingOutput with output -> {ExecutionResultSerializer serializer=facade.serializer(output,baseUri); in method private serializeError(neo4jError Neo4jError, baseUri URI) : StreamingOutput from class org.neo4j.server.rest.web.TransactionalService


    @Test
    public void shouldAllowTerminatingFromADifferentThread() throws Exception
    {
        // GIVEN
        final ChildException childException = new ChildException();
        final DoubleLatch latch = new DoubleLatch( 1 );
        final KernelTransaction transaction = newTransaction();
        transactionConsumer.accept( transaction );

        Thread thread = new Thread( () -> {
            try
            {
                latch.awaitStart();
                transaction.markForTermination();
                latch.finish();
            }
            catch ( Exception e )
            {
                childException.exception = e;
            }
        } );

        // WHEN
        thread.start();
        transaction.success();
        latch.startAndAwaitFinish();

        if ( childException.exception != null )
        {
            throw childException.exception;
        }

        boolean exceptionReceived = false;
        try
        {
            transaction.close();
        }
        catch ( TransactionFailureException e )
        {
            // Expected.
            exceptionReceived = true;
        }

        // THEN
        assertTrue( exceptionReceived );
        verify( transactionMonitor, times( 1 ) ).transactionFinished( false, isWriteTx );
        verify( transactionMonitor, times( 1 ) ).transactionTerminated( isWriteTx );
        verifyExtraInteractionWithTheMonitor( transactionMonitor, isWriteTx );
    }

    @Test
    public void shouldAllowTerminatingFromADifferentThread() throws Exception
    {
        // GIVEN
        final ChildException childException = new ChildException();
        final DoubleLatch latch = new DoubleLatch( 1 );
        final KernelTransaction transaction = newTransaction();
        transactionConsumer.accept( transaction );

        Thread thread = new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    latch.awaitStart();
                    transaction.markForTermination();
                    latch.finish();
                }
                catch ( Exception e )
                {
                    childException.exception = e;
                }
            }
        } );

        // WHEN
        thread.start();
        transaction.success();
        latch.startAndAwaitFinish();

        if ( childException.exception != null )
        {
            throw childException.exception;
        }

        boolean exceptionReceived = false;
        try
        {
            transaction.close();
        }
        catch ( TransactionFailureException e )
        {
            // Expected.
            exceptionReceived = true;
        }

        // THEN
        assertTrue( exceptionReceived );
        verify( transactionMonitor, times( 1 ) ).transactionFinished( false, isWriteTx );
        verify( transactionMonitor, times( 1 ) ).transactionTerminated( isWriteTx );
        verifyExtraInteractionWithTheMonitor( transactionMonitor, isWriteTx );
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.KernelTransactionImplementationTest.shouldAllowTerminatingFromADifferentThread.thread.new Thread.new Runnable with () -> {trylatch.awaitStart(); in method public shouldAllowTerminatingFromADifferentThread() : void from class org.neo4j.kernel.api.KernelTransactionImplementationTest


    @Test
    public void shouldUseStartTimeAndTxIdFromWhenStartingTxAsHeader() throws Exception
    {
        // GIVEN a transaction starting at one point in time
        long startingTime = clock.currentTimeMillis();
        when( legacyIndexState.hasChanges() ).thenReturn( true );
        doAnswer( invocation -> {
            Collection<StorageCommand> commands = invocation.getArgumentAt( 0, Collection.class );
            commands.add( mock( Command.class ) );
            return null;
        } ).when( storageEngine ).createCommands(
                any( Collection.class ),
                any( TransactionState.class ),
                any( ResourceLocker.class ),
                anyLong() );

        try ( KernelTransactionImplementation transaction = newTransaction() )
        {
            transaction.initialize( 5L, mock( Locks.Client.class ), KernelTransaction.Type.implicit );
            try ( KernelStatement statement = transaction.acquireStatement() )
            {
                statement.legacyIndexTxState(); // which will pull it from the supplier and the mocking above
                                                // will have it say that it has changes.
            }
            // WHEN committing it at a later point
            clock.forward( 5, MILLISECONDS );
            // ...and simulating some other transaction being committed
            when( metaDataStore.getLastCommittedTransactionId() ).thenReturn( 7L );
            transaction.success();
        }

        // THEN start time and last tx when started should have been taken from when the transaction started
        assertEquals( 5L, commitProcess.transaction.getLatestCommittedTxWhenStarted() );
        assertEquals( startingTime, commitProcess.transaction.getTimeStarted() );
        assertEquals( startingTime + 5, commitProcess.transaction.getTimeCommitted() );
    }

    @Test
    public void shouldUseStartTimeAndTxIdFromWhenStartingTxAsHeader() throws Exception
    {
        // GIVEN a transaction starting at one point in time
        long startingTime = clock.currentTimeMillis();
        when( legacyIndexState.hasChanges() ).thenReturn( true );
        doAnswer( new Answer<Void>()
        {
            @Override
            public Void answer( InvocationOnMock invocation ) throws Throwable
            {
                Collection<StorageCommand> commands = invocation.getArgumentAt( 0, Collection.class );
                commands.add( mock( Command.class ) );
                return null;
            }
        } ).when( storageEngine ).createCommands(
                any( Collection.class ),
                any( TransactionState.class ),
                any( ResourceLocker.class ),
                anyLong() );

        try ( KernelTransactionImplementation transaction = newTransaction() )
        {
            transaction.initialize( 5L, mock( Locks.Client.class ) );
            try ( KernelStatement statement = transaction.acquireStatement() )
            {
                statement.legacyIndexTxState(); // which will pull it from the supplier and the mocking above
                                                // will have it say that it has changes.
            }
            // WHEN committing it at a later point
            clock.forward( 5, MILLISECONDS );
            // ...and simulating some other transaction being committed
            when( metaDataStore.getLastCommittedTransactionId() ).thenReturn( 7L );
            transaction.success();
        }

        // THEN start time and last tx when started should have been taken from when the transaction started
        assertEquals( 5L, commitProcess.transaction.getLatestCommittedTxWhenStarted() );
        assertEquals( startingTime, commitProcess.transaction.getTimeStarted() );
        assertEquals( startingTime + 5, commitProcess.transaction.getTimeCommitted() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.KernelTransactionImplementationTest.shouldUseStartTimeAndTxIdFromWhenStartingTxAsHeader.createCommands.when.doAnswer.new Answer<Void> with invocation -> {Collection<StorageCommand> commands=invocation.getArgumentAt(0,Collection.class); in method public shouldUseStartTimeAndTxIdFromWhenStartingTxAsHeader() : void from class org.neo4j.kernel.api.KernelTransactionImplementationTest


    @Test
    public void shouldBePossibleToConsumeCompiledExecutionResultsWithVisitor()
    {
        // Given
        createNode();
        createNode();

        // When
        final List<Result.ResultRow> listResult = new ArrayList<>();
        try ( Result result = db.execute( "CYPHER runtime=compiled MATCH (n) RETURN n" ) )
        {
            result.accept( row -> {
                listResult.add( row );
                return true;
            } );
        }

        // Then
        assertThat( listResult, hasSize( 2 ) );
    }

    @Test
    public void shouldBePossibleToConsumeCompiledExecutionResultsWithVisitor()
    {
        // Given
        createNode();
        createNode();

        // When
        final List<Result.ResultRow> listResult = new ArrayList<>();
        try ( Result result = db.execute( "CYPHER runtime=compiled MATCH (n) RETURN n" ) )
        {
            result.accept( new Result.ResultVisitor<RuntimeException>()
            {
                @Override
                public boolean visit( Result.ResultRow row ) throws RuntimeException
                {
                    listResult.add( row );
                    return true;
                }
            } );
        }

        // Then
        assertThat( listResult, hasSize( 2 ) );
    }

Replace Anonymous With Lambda org.neo4j.cypher.internal.javacompat.ExecutionResultTest.shouldBePossibleToConsumeCompiledExecutionResultsWithVisitor.accept.new Result.ResultVisitor<RuntimeException> with row -> {listResult.add(row); in method public shouldBePossibleToConsumeCompiledExecutionResultsWithVisitor() : void from class org.neo4j.cypher.internal.javacompat.ExecutionResultTest


    @Test
    public void shouldBePossibleToCloseNotFullyVisitedCompiledExecutionResult()
    {
        // Given
        createNode();
        createNode();

        // When
        final List<Result.ResultRow> listResult = new ArrayList<>();
        try ( Result result = db.execute( "CYPHER runtime=compiled MATCH (n) RETURN n" ) )
        {
            result.accept( row -> {
                listResult.add( row );
                // return false so that no more result rows would be visited
                return false;
            } );
        }

        // Then
        assertThat( listResult, hasSize( 1 ) );
    }

    @Test
    public void shouldBePossibleToCloseNotFullyVisitedCompiledExecutionResult()
    {
        // Given
        createNode();
        createNode();

        // When
        final List<Result.ResultRow> listResult = new ArrayList<>();
        try ( Result result = db.execute( "CYPHER runtime=compiled MATCH (n) RETURN n" ) )
        {
            result.accept( new Result.ResultVisitor<RuntimeException>()
            {
                @Override
                public boolean visit( Result.ResultRow row ) throws RuntimeException
                {
                    listResult.add( row );
                    // return false so that no more result rows would be visited
                    return false;
                }
            } );
        }

        // Then
        assertThat( listResult, hasSize( 1 ) );
    }

Replace Anonymous With Lambda org.neo4j.cypher.internal.javacompat.ExecutionResultTest.shouldBePossibleToCloseNotFullyVisitedCompiledExecutionResult.accept.new Result.ResultVisitor<RuntimeException> with row -> {listResult.add(row); in method public shouldBePossibleToCloseNotFullyVisitedCompiledExecutionResult() : void from class org.neo4j.cypher.internal.javacompat.ExecutionResultTest


    private Runnable getNodesFromRelationship()
    {
        return () -> {
            relationship.getEndNode();
            relationship.getStartNode();
            relationship.getNodes();
            relationship.getOtherNode( node );
        };
    }

    private Runnable getNodesFromRelationship()
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                relationship.getEndNode();
                relationship.getStartNode();
                relationship.getNodes();
                relationship.getOtherNode( node );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.ReadTransactionLogWritingTest.getNodesFromRelationship.new Runnable with () -> {relationship.getEndNode(); in method private getNodesFromRelationship() : Runnable from class org.neo4j.kernel.impl.transaction.ReadTransactionLogWritingTest


    public GraphDatabaseDependencies kernelExtensions( Iterable<KernelExtensionFactory<?>> kernelExtensions )
    {
        return new GraphDatabaseDependencies( monitors, userLogProvider, settingsClasses,
                addAll( new ArrayList<>(), kernelExtensions ),
                urlAccessRules, queryEngineProviders );
    }

    public GraphDatabaseDependencies kernelExtensions( Iterable<KernelExtensionFactory<?>> kernelExtensions )
    {
        return new GraphDatabaseDependencies( monitors, userLogProvider, settingsClasses,
                addAll( new ArrayList<KernelExtensionFactory<?>>(), kernelExtensions ),
                urlAccessRules, queryEngineProviders );
    }

Replace Generic With Diamond GraphDatabaseDependencies with GraphDatabaseDependencies in method public kernelExtensions(kernelExtensions Iterable<KernelExtensionFactory<?>>) : GraphDatabaseDependencies from class org.neo4j.kernel.GraphDatabaseDependencies


    private static List<Callable<Object>> workers( final long iterations, final int numWorkers )
    {
        List<Callable<Object>> workers = new ArrayList<>();
        for ( int i = 0; i < numWorkers; i++ )
        {
            final Worker worker = new Worker();
            workers.add( () -> {
                for ( int i1 = 0; i1 < iterations; i1++ )
                {
                    worker.operation();
                }
                return null;
            } );
        }
        return workers;
    }

    private static List<Callable<Object>> workers( final long iterations, final int numWorkers )
    {
        List<Callable<Object>> workers = new ArrayList<>();
        for ( int i = 0; i < numWorkers; i++ )
        {
            final Worker worker = new Worker();
            workers.add( new Callable<Object>()
            {
                @Override
                public Object call() throws Exception
                {
                    for ( int i = 0; i < iterations; i++ )
                    {
                        worker.operation();
                    }
                    return null;
                }
            });
        }
        return workers;
    }

Replace Anonymous With Lambda .TxBench.workers.add.new Callable<Object> with () -> {for(int i1=0; i1 < iterations; i1++){worker.operation(); in method private workers(iterations long, numWorkers int) : List<Callable<Object>> from class TxBench


        public static <RESULT> DocPartParser<RESULT> withDetailedExceptions( Class<RESULT> clazz, DocPartParser<RESULT> delegate )
        {
            return ( fileName, title, el ) -> {
                try
                {
                    return delegate.parse( fileName, title, el );
                }
                catch ( RuntimeException e )
                {
                    throw new IllegalArgumentException(
                            format( "%s[%s]: Couldn't parse %s element", fileName, title, clazz.getSimpleName() )
                    );
                }
            };
        }

        public static <RESULT> DocPartParser<RESULT> withDetailedExceptions( Class<RESULT> clazz, DocPartParser<RESULT> delegate )
        {
            return new DocPartParser<RESULT>()
            {
                @Override
                public RESULT parse( String fileName, String title, Element el )
                {
                    try
                    {
                        return delegate.parse( fileName, title, el );
                    }
                    catch ( RuntimeException e )
                    {
                        throw new IllegalArgumentException(
                                format( "%s[%s]: Couldn't parse %s element", fileName, title, clazz.getSimpleName() )
                        );
                    }
                }
            };
        }

Replace Anonymous With Lambda org.neo4j.bolt.v1.docs.DocPartParser.Decoration.withDetailedExceptions.new DocPartParser<RESULT> with (fileName, title, el) -> {tryreturn delegate.parse(fileName,title,el); in method public withDetailedExceptions(clazz Class<RESULT>, delegate DocPartParser<RESULT>) : DocPartParser<RESULT> from class org.neo4j.bolt.v1.docs.DocPartParser.Decoration


    protected void registerRecovery( final DatabaseInfo databaseInfo, LifeSupport life,
                                     final DependencyResolver dependencyResolver )
    {
        life.addLifecycleListener( ( instance, from, to ) -> {
            if ( instance instanceof DatabaseAvailability && to.equals( LifecycleStatus.STARTED ) )
            {
                doAfterRecoveryAndStartup( databaseInfo, dependencyResolver );
            }
        } );
    }

    protected void registerRecovery( final DatabaseInfo databaseInfo, LifeSupport life,
                                     final DependencyResolver dependencyResolver )
    {
        life.addLifecycleListener( new LifecycleListener()
        {
            @Override
            public void notifyStatusChanged( Object instance, LifecycleStatus from, LifecycleStatus to )
            {
                if ( instance instanceof DatabaseAvailability && to.equals( LifecycleStatus.STARTED ) )
                {
                    doAfterRecoveryAndStartup( databaseInfo, dependencyResolver );
                }
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.factory.CommunityEditionModule.registerRecovery.addLifecycleListener.new LifecycleListener with (instance, from, to) -> {if(instance instanceof DatabaseAvailability && to.equals(LifecycleStatus.STARTED)){doAfterRecoveryAndStartup(databaseInfo,dependencyResolver); in method protected registerRecovery(databaseInfo DatabaseInfo, life LifeSupport, dependencyResolver DependencyResolver) : void from class org.neo4j.kernel.impl.factory.CommunityEditionModule


    private void refreshFields()
    {
        scanAllFields( PF_SHARED_READ_LOCK, element -> {
            readAllFields( element );
            return false;
        } );
    }

    private void refreshFields()
    {
        scanAllFields( PF_SHARED_READ_LOCK, new Visitor<PageCursor,IOException>()
        {
            @Override
            public boolean visit( PageCursor element ) throws IOException
            {
                readAllFields( element );
                return false;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.MetaDataStore.refreshFields.scanAllFields.new Visitor<PageCursor,IOException> with element -> {readAllFields(element); in method private refreshFields() : void from class org.neo4j.kernel.impl.store.MetaDataStore


    public void logRecords( final Logger msgLog )
    {
        scanAllFields( PF_SHARED_READ_LOCK, element -> {
            for ( Position position : Position.values() )
            {
                long value;
                do
                {
                    value = getRecordValue( element, position );
                }
                while ( element.shouldRetry() );
                msgLog.log( position.name() + " (" + position.description() + "): " + value );
            }
            return false;
        } );
    }

    public void logRecords( final Logger msgLog )
    {
        scanAllFields( PF_SHARED_READ_LOCK, new Visitor<PageCursor,IOException>()
        {
            @Override
            public boolean visit( PageCursor element ) throws IOException
            {
                for ( Position position : Position.values() )
                {
                    long value;
                    do
                    {
                        value = getRecordValue( element, position );
                    }
                    while ( element.shouldRetry() );
                    msgLog.log( position.name() + " (" + position.description() + "): " + value );
                }
                return false;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.MetaDataStore.logRecords.scanAllFields.new Visitor<PageCursor,IOException> with element -> {for(Position position: Position.values()){long value; in method public logRecords(msgLog Logger) : void from class org.neo4j.kernel.impl.store.MetaDataStore


    @Test
    public void mustRunEvictionCallbackOnEviction() throws Exception
    {
        final AtomicLong callbackFilePageId = new AtomicLong();
        final AtomicReference<Page> callbackPage = new AtomicReference<>();
        PageEvictionCallback callback = ( filePageId, page ) -> {
            callbackFilePageId.set( filePageId );
            callbackPage.set( page );
        };
        File file = file( "file" );
        PageSwapperFactory factory = swapperFactory();
        PageSwapper swapper = createSwapper( factory, file, cachePageSize(), callback, true );
        Page page = createPage();
        swapper.evicted( 42, page );
        assertThat( callbackFilePageId.get(), is( 42L ) );
        assertThat( callbackPage.get(), sameInstance( page ) );
    }

    @Test
    public void mustRunEvictionCallbackOnEviction() throws Exception
    {
        final AtomicLong callbackFilePageId = new AtomicLong();
        final AtomicReference<Page> callbackPage = new AtomicReference<>();
        PageEvictionCallback callback = new PageEvictionCallback()
        {
            @Override
            public void onEvict( long filePageId, Page page )
            {
                callbackFilePageId.set( filePageId );
                callbackPage.set( page );
            }
        };
        File file = file( "file" );
        PageSwapperFactory factory = swapperFactory();
        PageSwapper swapper = createSwapper( factory, file, cachePageSize(), callback, true );
        Page page = createPage();
        swapper.evicted( 42, page );
        assertThat( callbackFilePageId.get(), is( 42L ) );
        assertThat( callbackPage.get(), sameInstance( page ) );
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageSwapperTest.mustRunEvictionCallbackOnEviction.callback.new PageEvictionCallback with (filePageId, page) -> {callbackFilePageId.set(filePageId); in method public mustRunEvictionCallbackOnEviction() : void from class org.neo4j.io.pagecache.PageSwapperTest


    @Test
    public void concurrentPositionedVectoredReadsAndWritesMustNotInterfere() throws Exception
    {
        File file = file( "file" );
        PageSwapperFactory factory = swapperFactory();
        final PageSwapper swapper = createSwapper( factory, file, 4, NO_CALLBACK, true );
        final int pageCount = 100;
        final int iterations = 20000;
        final CountDownLatch startLatch = new CountDownLatch( 1 );
        ByteBufferPage output = createPage( 4 );
        for ( int i = 0; i < pageCount; i++ )
        {
            output.putInt( i+1, 0 );
            swapper.write( i, output );
        }

        Callable<Void> work = () -> {
            ThreadLocalRandom rng = ThreadLocalRandom.current();
            ByteBufferPage[] pages = new ByteBufferPage[10];
            for ( int i = 0; i < pages.length; i++ )
            {
                pages[i] = createPage( 4 );
            }

            startLatch.await();
            for ( int i = 0; i < iterations; i++ )
            {
                long startFilePageId = rng.nextLong( 0, pageCount - pages.length );
                if ( rng.nextBoolean() )
                {
                    // Do read
                    long bytesRead = swapper.read( startFilePageId, pages, 0, pages.length );
                    assertThat( bytesRead, is( pages.length * 4L ) );
                    for ( int j = 0; j < pages.length; j++ )
                    {
                        int expectedValue = (int) (1 + j + startFilePageId);
                        int actualValue = pages[j].getInt( 0 );
                        assertThat( actualValue, is( expectedValue ) );
                    }
                }
                else
                {
                    // Do write
                    for ( int j = 0; j < pages.length; j++ )
                    {
                        int value = (int) (1 + j + startFilePageId);
                        pages[j].putInt( value, 0 );
                    }
                    assertThat( swapper.write( startFilePageId, pages, 0, pages.length ), is( pages.length * 4L ) );
                }
            }
            return null;
        };

        int threads = 8;
        ExecutorService executor = Executors.newFixedThreadPool( threads, r -> {
            Thread thread = Executors.defaultThreadFactory().newThread( r );
            thread.setDaemon( true );
            return thread;
        } );
        List<Future<Void>> futures = new ArrayList<>( threads );
        for ( int i = 0; i < threads; i++ )
        {
            futures.add( executor.submit( work ) );
        }

        startLatch.countDown();
        for ( Future<Void> future : futures )
        {
            future.get();
        }
    }

    @Test
    public void concurrentPositionedVectoredReadsAndWritesMustNotInterfere() throws Exception
    {
        File file = file( "file" );
        PageSwapperFactory factory = swapperFactory();
        final PageSwapper swapper = createSwapper( factory, file, 4, NO_CALLBACK, true );
        final int pageCount = 100;
        final int iterations = 20000;
        final CountDownLatch startLatch = new CountDownLatch( 1 );
        ByteBufferPage output = createPage( 4 );
        for ( int i = 0; i < pageCount; i++ )
        {
            output.putInt( i+1, 0 );
            swapper.write( i, output );
        }

        Callable<Void> work = new Callable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                ThreadLocalRandom rng = ThreadLocalRandom.current();
                ByteBufferPage[] pages = new ByteBufferPage[10];
                for ( int i = 0; i < pages.length; i++ )
                {
                    pages[i] = createPage( 4 );
                }

                startLatch.await();
                for ( int i = 0; i < iterations; i++ )
                {
                    long startFilePageId = rng.nextLong( 0, pageCount - pages.length );
                    if ( rng.nextBoolean() )
                    {
                        // Do read
                        long bytesRead = swapper.read( startFilePageId, pages, 0, pages.length );
                        assertThat( bytesRead, is( pages.length * 4L ) );
                        for ( int j = 0; j < pages.length; j++ )
                        {
                            int expectedValue = (int) (1 + j + startFilePageId);
                            int actualValue = pages[j].getInt( 0 );
                            assertThat( actualValue, is( expectedValue ) );
                        }
                    }
                    else
                    {
                        // Do write
                        for ( int j = 0; j < pages.length; j++ )
                        {
                            int value = (int) (1 + j + startFilePageId);
                            pages[j].putInt( value, 0 );
                        }
                        assertThat( swapper.write( startFilePageId, pages, 0, pages.length ), is( pages.length * 4L ) );
                    }
                }
                return null;
            }
        };

        int threads = 8;
        ExecutorService executor = Executors.newFixedThreadPool( threads, new ThreadFactory()
        {
            @Override
            public Thread newThread( Runnable r )
            {
                Thread thread = Executors.defaultThreadFactory().newThread( r );
                thread.setDaemon( true );
                return thread;
            }
        } );
        List<Future<Void>> futures = new ArrayList<>( threads );
        for ( int i = 0; i < threads; i++ )
        {
            futures.add( executor.submit( work ) );
        }

        startLatch.countDown();
        for ( Future<Void> future : futures )
        {
            future.get();
        }
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageSwapperTest.concurrentPositionedVectoredReadsAndWritesMustNotInterfere.work.new Callable<Void> with () -> {ThreadLocalRandom rng=ThreadLocalRandom.current(); in method public concurrentPositionedVectoredReadsAndWritesMustNotInterfere() : void from class org.neo4j.io.pagecache.PageSwapperTest


    private static MBeanServerConnection connect( JMXServiceURL url, String username,
                                                  String password )
    {
        Map<String, Object> environment = new HashMap<>();
        if ( username != null && password != null )
        {
            environment.put( JMXConnector.CREDENTIALS, new String[]{username, password} );
        }
        else if ( username != password )
        {
            throw new IllegalArgumentException(
                    "User name and password must either both be specified, or both be null." );
        }
        try
        {
            try
            {
                return JMXConnectorFactory.connect( url, environment ).getMBeanServerConnection();
            }
            catch ( SecurityException e )
            {
                environment.put( RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE,
                        new SslRMIClientSocketFactory() );
                return JMXConnectorFactory.connect( url, environment ).getMBeanServerConnection();
            }
        }
        catch ( IOException e )
        {
            throw new IllegalStateException( "Connection failed.", e );
        }
    }

    private static MBeanServerConnection connect( JMXServiceURL url, String username,
                                                  String password )
    {
        Map<String, Object> environment = new HashMap<String, Object>();
        if ( username != null && password != null )
        {
            environment.put( JMXConnector.CREDENTIALS, new String[]{username, password} );
        }
        else if ( username != password )
        {
            throw new IllegalArgumentException(
                    "User name and password must either both be specified, or both be null." );
        }
        try
        {
            try
            {
                return JMXConnectorFactory.connect( url, environment ).getMBeanServerConnection();
            }
            catch ( SecurityException e )
            {
                environment.put( RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE,
                        new SslRMIClientSocketFactory() );
                return JMXConnectorFactory.connect( url, environment ).getMBeanServerConnection();
            }
        }
        catch ( IOException e )
        {
            throw new IllegalStateException( "Connection failed.", e );
        }
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method private connect(url JMXServiceURL, username String, password String) : MBeanServerConnection from class org.neo4j.management.Neo4jManager


    public Map<String, Object> getConfiguration()
    {
        final String[] keys;
        final AttributeList attributes;
        try
        {
            MBeanAttributeInfo[] keyInfo = server.getMBeanInfo( config ).getAttributes();
            keys = new String[keyInfo.length];
            for ( int i = 0; i < keys.length; i++ )
            {
                keys[i] = keyInfo[i].getName();
            }
            attributes = server.getAttributes( config, keys );
        }
        catch ( Exception e )
        {
            throw new IllegalStateException( "Could not access the configuration bean", e );
        }
        Map<String, Object> configuration = new HashMap<>();
        for ( int i = 0; i < keys.length; i++ )
        {
            configuration.put( keys[i], attributes.get( i ) );

        }
        return configuration;
    }

    public Map<String, Object> getConfiguration()
    {
        final String[] keys;
        final AttributeList attributes;
        try
        {
            MBeanAttributeInfo[] keyInfo = server.getMBeanInfo( config ).getAttributes();
            keys = new String[keyInfo.length];
            for ( int i = 0; i < keys.length; i++ )
            {
                keys[i] = keyInfo[i].getName();
            }
            attributes = server.getAttributes( config, keys );
        }
        catch ( Exception e )
        {
            throw new IllegalStateException( "Could not access the configuration bean", e );
        }
        Map<String, Object> configuration = new HashMap<String, Object>();
        for ( int i = 0; i < keys.length; i++ )
        {
            configuration.put( keys[i], attributes.get( i ) );

        }
        return configuration;
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public getConfiguration() : Map<String,Object> from class org.neo4j.management.Neo4jManager


    public static <T> Setting<T> setting( final String name, final Function<String, T> parser,
                                          final String defaultValue,
                                          final Setting<T> inheritedSetting, final BiFunction<T, Function<String,
            String>, T>... valueConverters )
    {
        Function<Function<String, String>, String> valueLookup = named( name );

        Function<Function<String, String>, String> defaultLookup;
        if ( defaultValue != null )
        {
            // This is explicitly an identity comparison. We are comparing against the known instance above,
            // using String.equals() here would mean that we could not have settings that have the string "mandatory"
            // as its default value.
            //noinspection StringEquality
            if ( defaultValue == MANDATORY ) // yes, this really is supposed to be ==
            {
                defaultLookup = mandatory( valueLookup );
            }
            else
            {
                defaultLookup = withDefault( defaultValue, valueLookup );
            }
        }
        else
        {
            defaultLookup = Functions.nullFunction();
        }

        if ( inheritedSetting != null )
        {
            valueLookup = inheritedValue( valueLookup, inheritedSetting );
            defaultLookup = inheritedDefault( defaultLookup, inheritedSetting );
        }

        return new DefaultSetting<>( name, parser, valueLookup, defaultLookup, valueConverters );
    }

    public static <T> Setting<T> setting( final String name, final Function<String, T> parser,
                                          final String defaultValue,
                                          final Setting<T> inheritedSetting, final BiFunction<T, Function<String,
            String>, T>... valueConverters )
    {
        Function<Function<String, String>, String> valueLookup = named( name );

        Function<Function<String, String>, String> defaultLookup;
        if ( defaultValue != null )
        {
            // This is explicitly an identity comparison. We are comparing against the known instance above,
            // using String.equals() here would mean that we could not have settings that have the string "mandatory"
            // as its default value.
            //noinspection StringEquality
            if ( defaultValue == MANDATORY ) // yes, this really is supposed to be ==
            {
                defaultLookup = mandatory( valueLookup );
            }
            else
            {
                defaultLookup = withDefault( defaultValue, valueLookup );
            }
        }
        else
        {
            defaultLookup = Functions.nullFunction();
        }

        if ( inheritedSetting != null )
        {
            valueLookup = inheritedValue( valueLookup, inheritedSetting );
            defaultLookup = inheritedDefault( defaultLookup, inheritedSetting );
        }

        return new DefaultSetting<T>( name, parser, valueLookup, defaultLookup, valueConverters );
    }

Replace Generic With Diamond DefaultSetting<T> with DefaultSetting<> in method public setting(name String, parser Function<String,T>, defaultValue String, inheritedSetting Setting<T>, valueConverters BiFunction<T,Function<String,String>,T>...) : Setting<T> from class org.neo4j.kernel.configuration.Settings


    private static <T> Function<Function<String, String>, String> inheritedValue( final Function<Function<String,
            String>, String> lookup, final Setting<T> inheritedSetting )
    {
        return settings -> {
            String value = lookup.apply( settings );
            if ( value == null )
            {
                value = ((SettingHelper<T>) inheritedSetting).lookup( settings );
            }
            return value;
        };
    }

    private static <T> Function<Function<String, String>, String> inheritedValue( final Function<Function<String,
            String>, String> lookup, final Setting<T> inheritedSetting )
    {
        return new Function<Function<String, String>, String>()
        {
            @Override
            public String apply( Function<String, String> settings )
            {
                String value = lookup.apply( settings );
                if ( value == null )
                {
                    value = ((SettingHelper<T>) inheritedSetting).lookup( settings );
                }
                return value;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.configuration.Settings.inheritedValue.new Function<Function<String,String>,String> with settings -> {String value=lookup.apply(settings); in method private inheritedValue(lookup Function<Function<String,String>,String>, inheritedSetting Setting<T>) : Function<Function<String,String>,String> from class org.neo4j.kernel.configuration.Settings