Hot questions for Using Neo4j in jersey

Question:

I am in great need of some advice regarding an issue I'm running into with a Neo4j unmanaged extension that I'm building in Java. I have created a very simple code sample that highlights my issue. The basic premise is that I'd like to set the

org.neo4j.server.webserver.limit.executiontime

for the neo4j server to a reasonable amount of time for user queries (lets say 2 minutes) which are coming in through Cypher, other endpoints, etc. But I also have some batch jobs that I need to run through this unmanaged extension, and therefore I attempted to break them up into several <2 minute transactions. The issue I am seeing is that even though each of my transactions is <2 minutes, once my process has been running for 2 minutes I get a GuardTimeoutException.

Here is the sample. In this sample note that I have limited the time to 2000 milliseconds, so it doesn't take me all day to debug. (getting awful close though!)

Endpoint

/**
 * Sample endpoint.
@GET
@Path("test")
@Produces(MediaType.APPLICATION_JSON)
public Response test(@Context GraphDatabaseService service) {
    TestFile.test(service);
    return Response.ok().build();
}

Logic

public static void test(final GraphDatabaseService service) {
    for (int i = 0; i < 100000; i++) {
        try (Transaction tx = service.beginTx();) {
            final Node n = service.createNode();
            n.addLabel(testLabel);
            tx.success();
            tx.close();
        }
        System.out.println("Added node");
    }
}

I can see that each transaction takes only a fraction of a second, since I load in about 200 nodes successfully before timeout. At exactly 2 seconds from hitting the endpoint though, I get the following:

org.neo4j.kernel.guard.GuardTimeoutException: timeout occured (overtime=1)
at org.neo4j.kernel.guard.Guard$Timeout.check(Guard.java:132)
at org.neo4j.kernel.guard.Guard.check(Guard.java:43)
at org.neo4j.kernel.InternalAbstractGraphDatabase$5.createNode(InternalAbstractGraphDatabase.java:794)
at org.neo4j.kernel.impl.api.state.OldTxStateBridgeImpl.nodeCreate(OldTxStateBridgeImpl.java:120)
at org.neo4j.kernel.impl.api.state.TxStateImpl.nodeDoCreate(TxStateImpl.java:366)
at org.neo4j.kernel.impl.api.StateHandlingStatementOperations.nodeCreate(StateHandlingStatementOperations.java:99)
at org.neo4j.kernel.impl.api.ConstraintEnforcingEntityOperations.nodeCreate(ConstraintEnforcingEntityOperations.java:390)
at org.neo4j.kernel.impl.api.LockingStatementOperations.nodeCreate(LockingStatementOperations.java:207)
at org.neo4j.kernel.impl.api.OperationsFacade.nodeCreate(OperationsFacade.java:506)
at org.neo4j.kernel.InternalAbstractGraphDatabase.createNode(InternalAbstractGraphDatabase.java:1120)
at **TestFile.test(TestFile.java:15)
at **test(Jobs.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at org.neo4j.server.rest.transactional.TransactionalRequestDispatcher.dispatch(TransactionalRequestDispatcher.java:139)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:698)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1506)
at org.neo4j.server.guard.GuardingRequestFilter.doFilter(GuardingRequestFilter.java:68)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1477)
at org.neo4j.server.guard.GuardingRequestFilter.doFilter(GuardingRequestFilter.java:68)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1477)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:211)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1096)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:432)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:175)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1030)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:445)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:268)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:601)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:532)
at java.lang.Thread.run(Thread.java:744)

As you can see I have tried tx.success(), tx.close(), anything I can think of to make all the transactions die when they are completed. Any advice greatly appreciated!!

update -------------

Michael - I have followed the steps that you suggested - I have a new java class that extends SPIPluginLifecycle and have also added the new config file in /src/main/resources/META-INF/services. I can see that this file ends up in the jar that goes in /plugins within META-INF/services. However, I don't see this initialization class getting called at all. Heres the class and logs I do see on startup.

public class GraphInitializer implements SPIPluginLifecycle {
private WebServer webServer;

@Override
public Collection<Injectable<?>> start(final GraphDatabaseService graphDatabaseService, final Configuration config) {
    throw new IllegalAccessError();
}

@Override
public void stop() {

}

@Override
public Collection<Injectable<?>> start(final NeoServer neoServer) {
    System.out.println("K starting!");
    webServer = getWebServer(neoServer);
    final Database database = neoServer.getDatabase();
    final GraphDatabaseAPI graphDatabaseAPI = database.getGraph();
    final Guard guard = graphDatabaseAPI.getDependencyResolver().resolveDependency(Guard.class);
    final Filter filter = new GuardingRequestFilter(guard, 3000);
    webServer.addFilter(filter, "/*" );
    return null;
}

private WebServer getWebServer(final NeoServer neoServer) {
    if (neoServer instanceof AbstractNeoServer) {
        return ((AbstractNeoServer) neoServer).getWebServer();
    }
    throw new IllegalArgumentException("expected AbstractNeoServer");
}

Logs:

2014-10-06 16:14:23.009+0000 INFO  [API] Mounted discovery module at [/]
2014-10-06 16:14:23.014+0000 INFO  [API] Mounted REST API at [/db/data/]
2014-10-06 16:14:23.017+0000 INFO  [API] Mounted management API at [/db/manage/]
2014-10-06 16:14:23.017+0000 INFO  [API] Mounted third-party JAX-RS package [***] at [/kristen]
2014-10-06 16:14:23.017+0000 INFO  [API] Mounted webadmin at [/webadmin]
2014-10-06 16:14:23.017+0000 INFO  [API] Mounted Neo4j Browser at [/browser]
2014-10-06 16:14:23.070+0000 INFO  [API] Mounting static content at [/webadmin] from [webadmin-html]
2014-10-06 16:14:23.124+0000 INFO  [API] Mounting static content at [/browser] from [browser]
12:14:23.126 [main] WARN  o.e.j.server.handler.ContextHandler - o.e.j.s.ServletContextHandler@1cb1c025{/,null,null} contextPath ends with /
12:14:23.127 [main] WARN  o.e.j.server.handler.ContextHandler - Empty contextPath
12:14:23.131 [main] INFO  org.eclipse.jetty.server.Server - jetty-9.0.5.v20130815
12:14:23.155 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.h.MovedContextHandler@5de15910{/,null,AVAILABLE}
12:14:23.245 [main] INFO  o.e.j.w.StandardDescriptorProcessor - NO JSP Support for /webadmin, did not find org.apache.jasper.servlet.JspServlet
12:14:23.255 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.w.WebAppContext@4b45c74e{/webadmin,jar:file:/usr/local/Cellar/neo4j/2.1.3/libexec/system/lib/neo4j-server-2.1.3-static-web.jar!/webadmin-html,AVAILABLE}
12:14:23.668 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@2917eb65{/kristen,null,AVAILABLE}
12:14:23.817 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@54589209{/db/manage,null,AVAILABLE}
12:14:24.003 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@68a1f8e7{/db/data,null,AVAILABLE}
12:14:24.021 [main] INFO  o.e.j.w.StandardDescriptorProcessor - NO JSP Support for /browser, did not find org.apache.jasper.servlet.JspServlet
12:14:24.022 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.w.WebAppContext@438e0daa{/browser,jar:file:/usr/local/Cellar/neo4j/2.1.3/libexec/system/lib/neo4j-browser-2.1.3.jar!/browser,AVAILABLE}
12:14:24.103 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@1cb1c025{/,null,AVAILABLE}
12:14:24.115 [main] INFO  o.e.jetty.server.ServerConnector - Started ServerConnector@75b61dd7{HTTP/1.1}{localhost:7474}
12:14:24.503 [main] INFO  o.e.jetty.server.ServerConnector - Started ServerConnector@6464d61f{SSL-HTTP/1.1}{localhost:7473}
2014-10-06 16:14:24.503+0000 INFO  [API] Server started on: http://localhost:7474/
2014-10-06 16:14:24.504+0000 INFO  [API] Remote interface ready and available at [http://localhost:7474/]

I expected a new line entry or something - also my changes to add a timeout don't actually work so I'm sure these changes haven't taken affect. Is there anything additional I have to add to the neo4j-server.properties, neo4j.properties, etc? I have already successfully added the line that sets up the unmanaged extension.

thank you!


Answer:

Small transaction make it go slower as each has to be flushed to disk. Usually it makes sense to add up to 50k nodes in one tx, which should take less than a second.

For your guard filter, it's just a servlet filter, so you can also just check the Neo4j source code where it is installed and on init of your extension install it yourself but excempt the endpoints you want to batch to.

In: org.neo4j.server.AbstractNeoServer line 488

    Filter filter = new GuardingRequestFilter( guard,
            getConfiguration().getInt( Configurator.WEBSERVER_LIMIT_EXECUTION_TIME_PROPERTY_KEY ) );
    webServer.addFilter( filter, "/*" );

You can use the extension initializer to add your custom filter like shown here:

https://github.com/neo4j-contrib/authentication-extension/blob/2.1/src/main/java/org/neo4j/server/extension/auth/AuthenticationExtensionInitializer.java#L81

you have to add a file like this which contains your initializer class name:

https://github.com/neo4j-contrib/authentication-extension/blob/2.1/src/main/resources/META-INF/services/org.neo4j.server.plugins.PluginLifecycle

Question:

I use neo4j 2.2.4

I try this program ,and this is my test code

package neo4j.rest.client;
import javax.ws.rs.core.MediaType;
import org.json.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class MyRestClient {
public static void main(String[] args) {
    MyRestClient jersey = new MyRestClient();
    jersey.createNode();
    jersey.sendCypher();        
}
public void createNode(){   
    //Create a REST Client
    Client client = Client.create();
    //Define a resource (REST Endpoint) which needs to be Invoked 
    //for creating a Node
    WebResource resource = client.resource("http://localhost:7474").path("/db/data/node");
    //Define properties for the node.
    JSONObject node = new JSONObject();
    node.append("Name", "John");        
    System.out.println(node.toString());        
    //Invoke the rest endpoint as JSON request
    ClientResponse res = resource.accept(MediaType.APPLICATION_JSON)
    .entity(node.toString())
    .post(ClientResponse.class);
    //Print the URI of the new Node
    System.out.println("URI of New Node = " + res.getLocation());       
}
public void sendCypher() {
    //Create a REST Client
    Client client = Client.create();
    //Define a resource (REST Endpoint) which needs to be Invoked 
    //for executing Cypher Query
    WebResource resource = client.resource("http://localhost:7474").path("/db/data/cypher");
    //Define JSON Object and Cypher Query
    JSONObject cypher = new JSONObject();
    cypher.accumulate("query", "match n return n limit 10");
    //Invoke the rest endpoint as JSON request
    ClientResponse res = resource.accept(MediaType.APPLICATION_JSON).entity(cypher.toString())
    .post(ClientResponse.class);
    //Print the response received from the Server
    System.out.println(res.getEntity(String.class));
}
}

And this is my error information,

{"Name":["John"]} Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149) at com.sun.jersey.api.client.Client.handle(Client.java:648) at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670) at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74) at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:553) at neo4j.rest.client.MyRestClient.createNode(MyRestClient.java:30) at neo4j.rest.client.MyRestClient.main(MyRestClient.java:14) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at sun.net.NetworkClient.doConnect(NetworkClient.java:180) at sun.net.www.http.HttpClient.openServer(HttpClient.java:388) at sun.net.www.http.HttpClient.openServer(HttpClient.java:483) at sun.net.www.http.HttpClient.(HttpClient.java:213) at sun.net.www.http.HttpClient.New(HttpClient.java:300) at sun.net.www.http.HttpClient.New(HttpClient.java:316) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087) at com.sun.jersey.client.urlconnection.URLConnectionClientHandler$1$1.getOutputStream(URLConnectionClientHandler.java:225) at com.sun.jersey.api.client.CommittingOutputStream.commitWrite(CommittingOutputStream.java:117) at com.sun.jersey.api.client.CommittingOutputStream.write(CommittingOutputStream.java:89) at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221) at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291) at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295) at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141) at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229) at java.io.BufferedWriter.flush(BufferedWriter.java:254) at com.sun.jersey.core.util.ReaderWriter.writeToAsString(ReaderWriter.java:191) at com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider.writeToAsString(AbstractMessageReaderWriterProvider.java:128) at com.sun.jersey.core.impl.provider.entity.StringProvider.writeTo(StringProvider.java:88) at com.sun.jersey.core.impl.provider.entity.StringProvider.writeTo(StringProvider.java:58) at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:300) at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:204) at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147) ... 6 more

Thank you.


Answer:

  • Check if your Neo4j server is up and running. Just open http://localhost:7474 in your browser.

  • Your code would work if you use default settings of Neo4j. Because authorization is enabled by default. You have two options:

    1. Add authorization headers into your request

      client.addFilter(new HTTPBasicAuthFilter("neo4j","your_password"));

    2. Disable authorization

neo4j-server.properties

# Disable authorization
dbms.security.auth_enabled=false

Question:

I am trying to insert data to a neo4j graph database. I am trying to create a Person type node whose name is 'Thamali' by using a jersey client. I have given the java code that I use below. I try to execute the cypher query CREATE (thamali:Person {name:"Thamali"}) By using the below java code.

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

import javax.ws.rs.core.MediaType;

public class NeoAPIClass {
    private final String baseUri = "http://localhost:7474/db/data/cypher";
    private final String user = "neo4j";
    private final String password = "12345";

    public static void main(String args[]){
            NeoAPIClass n=new NeoAPIClass();
            n.runQuery();
    }

    void runQuery(){
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter(user, password));
        WebResource cypherResource = client.resource(baseUri);

        String s="{\"query\":\"CREATE (thamali:Person{name:\"Thamali\"})\"}";
        ClientResponse cypherResponse = cypherResource.accept(MediaType.APPLICATION_JSON)
                .type(MediaType.APPLICATION_JSON_TYPE).entity(s).post(ClientResponse.class);

        System.out.println("Output from Server .... "+ cypherResponse.getStatus());

    }

}

I get the following exception with http status code 500.

    ERROR The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container Unexpected character ('T' (code 84)): was expecting comma to separate OBJECT entries [line: 1, column: 41]
    org.neo4j.server.rest.repr.BadInputException: Unexpected character ('T' (code 84)): was expecting comma to separate OBJECT entries [line: 1, column: 41]
        at org.neo4j.server.rest.repr.formats.JsonFormat.readMap(JsonFormat.java:94)
        at org.neo4j.server.rest.web.CypherService.cypher(CypherService.java:89)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
        at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)

Caused by: org.neo4j.server.rest.domain.JsonParseException: Unexpected character ('T' (code 84)): was expecting comma to separate OBJECT entries [line: 1, column: 41]
    at org.neo4j.server.rest.domain.JsonHelper.readJson(JsonHelper.java:73)
    at org.neo4j.server.rest.domain.JsonHelper.jsonToMap(JsonHelper.java:54)
    at org.neo4j.server.rest.repr.formats.JsonFormat.readMap(JsonFormat.java:90)
    ... 43 more

Can anyone please help me to solve this.


Answer:

The problem in the correct formation of the JSON-string. Two ways to solve:

1) Two additional slash to the internal quotation:

String s="{\"query\":\"CREATE (thamali:Person{name:\\\"Thamali\\\"})\"}";

2) Use JSON library. For example by Douglas Crockford:

JSONObject obj = new JSONObject();
obj.put("query", "CREATE (thamali: Person{name:\"Thamali\"})");
String s = obj.toString();

Question:

I'm going through the neo4j server-extension example that is posted in github---and when running mvn package I get the "java.net.BindException:Address already in use" for port 7474 on the MovieServiceIntegrationTest.

I've looked at the port through the commands 'lsof -i:7474' and 'netstat -n' and I do not see anything interfering.

I've also tried on linux (initially on os X) and I get the same problem.

What is the best next step to investigate the error?

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running example.extension.movies.MovieServiceIntegrationTest
server.baseUri() = http://localhost:7474/
05:46:21.067 [main] WARN  o.e.j.server.handler.ContextHandler - o.e.j.s.ServletContextHandler@29314cc9{/,null,null} contextPath ends with /
05:46:21.070 [main] WARN  o.e.j.server.handler.ContextHandler - Empty contextPath
05:46:21.078 [main] INFO  org.eclipse.jetty.server.Server - jetty-9.0.5.v20130815
05:46:21.133 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.h.MovedContextHandler@7b208b45{/,null,AVAILABLE}
Mar 23, 2015 5:46:21 AM com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
  example.extension.movies
Mar 23, 2015 5:46:21 AM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class example.extension.movies.MovieResource
Mar 23, 2015 5:46:21 AM com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
Mar 23, 2015 5:46:21 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'
05:46:21.588 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@ba354ca{/movie,null,AVAILABLE}
Mar 23, 2015 5:46:21 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'
05:46:21.757 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@7b4acdc2{/db/manage,null,AVAILABLE}
Mar 23, 2015 5:46:21 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'
05:46:21.957 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@736048ed{/db/data,null,AVAILABLE}
05:46:22.061 [main] INFO  o.e.j.w.StandardDescriptorProcessor - NO JSP Support for /browser, did not find org.apache.jasper.servlet.JspServlet
05:46:22.078 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.w.WebAppContext@64693226{/browser,jar:file:/Users/brianchase/.m2/repository/org/neo4j/app/neo4j-browser/2.1.4/neo4j-browser-2.1.4.jar!/browser,AVAILABLE}
Mar 23, 2015 5:46:22 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'
05:46:22.191 [main] INFO  o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@29314cc9{/,null,AVAILABLE}
05:46:22.251 [main] WARN  o.e.j.u.component.AbstractLifeCycle - FAILED ServerConnector@3f985a86{HTTP/1.1}{localhost:7474}: java.net.BindException: Address already in use
java.net.BindException: Address already in use

Port investigation (7474 neo4j server in listen):

Computer:~ user$ lsof -i:7474
COMMAND PID       USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
java    421 user  137u  IPv6 0x4c075845f5b86ccd      0t0  TCP localhost:7474 (LISTEN)

Netstat:

Active Internet connections
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)    
tcp4       0      0  192.168.44.208.49303   65.115.96.238.80       SYN_SENT   
tcp4       0      0  192.168.44.208.49301   209.197.20.103.80      ESTABLISHED
tcp4       0      0  192.168.44.208.49300   4.31.28.74.80          ESTABLISHED
tcp4     164      0  192.168.44.208.49276   52.0.233.188.80        CLOSE_WAIT 
tcp4       0      0  192.168.44.208.49208   108.160.170.34.80      ESTABLISHED
tcp4      37      0  192.168.44.208.49186   108.160.165.211.443    CLOSE_WAIT 
tcp4      37      0  192.168.44.208.49185   108.160.165.211.443    CLOSE_WAIT 
tcp4      37      0  192.168.44.208.49184   108.160.165.211.443    CLOSE_WAIT 
tcp4      37      0  192.168.44.208.49183   108.160.165.211.443    CLOSE_WAIT 
tcp4       0      0  192.168.44.208.49178   17.172.233.120.5223    ESTABLISHED
tcp4       0      0  192.168.44.208.49177   17.110.227.101.5223    ESTABLISHED
tcp4      37      0  192.168.44.208.49170   108.160.166.141.443    CLOSE_WAIT 
udp4       0      0  *.58920                *.*                               
udp4       0      0  *.17500                *.*                               
udp4       0      0  *.53249                *.*                               
udp4       0      0  192.168.44.208.123     *.*                               
udp6       0      0  fe80::2ef0:eeff:.123   *.*                               
udp6       0      0  fe80::8402:97ff:.123   *.*                               
udp6       0      0  fe80::1%lo0.123        *.*                               
udp4       0      0  127.0.0.1.123          *.*                               
udp6       0      0  ::1.123                *.*                               
udp6       0      0  *.123                  *.*                               
udp4       0      0  *.123                  *.*                               
udp6       0      0  *.5353                 *.*                               
udp4       0      0  *.5353                 *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.58003                *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp6       0      0  *.5353                 *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp6       0      0  *.5353                 *.*                               
udp4       0      0  *.5353                 *.*                               
udp46      0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp46      0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.*                    *.*                               
udp4       0      0  *.137                  *.*                               
udp4       0      0  *.138                  *.* 

Answer:

It looks like you have a neo4j instance running when running the maven tests. Make sure you shut this down before running maven.

Before running mvn, use jps to list all running java processes. The neo4j process is mentioned as Bootstrapper in jps' listing. Make sure that there is no such process.

Question:

I want to use the Jersey client to connect via REST with a Neo4j database. In the Neo4j manual they have examples of this in Tutorials->Languages->How to use the REST API from Java. I want to create a new node and then use Cypher to add relationships to it. In the Neo4j example (https://github.com/neo4j/neo4j/blob/2.2.9/community/server-examples/src/main/java/org/neo4j/examples/server/CreateSimpleGraph.java) they use 'createNode', but the documentation suggests that that is only available using an embedded Neo4j server.

Does calling createNode() work in a RESTful context?


Answer:

In the example that you reference, the createNode function as defined here is simply making an HTTP POST request to http://localhost:7474/db/data/node which will create a new node:

private static URI createNode()
{
    final String nodeEntryPointUri = SERVER_ROOT_URI + "node";
    // http://localhost:7474/db/data/node

    WebResource resource = Client.create()
            .resource( nodeEntryPointUri );
    // POST {} to the node entry point URI
    ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
            .type( MediaType.APPLICATION_JSON )
            .entity( "{}" )
            .post( ClientResponse.class );

    final URI location = response.getLocation();
    System.out.println( String.format(
            "POST to [%s], status code [%d], location header [%s]",
            nodeEntryPointUri, response.getStatus(), location.toString() ) );
    response.close();

    return location;
}

This function is defined in the sample code and is completely different than the createNode function that is part of the embedded Java API.

If you are interested in working with the new Neo4j 3.0 version (currently RC) there is a new Java driver that supports Cypher here.

Question:

When upgrading Neo4J from 3.3.4 to 3.4.0 the dependency "com.sun.jersey.multipart.FormDataParam" no longer exists. We are using it like this:

@POST
@Path("/path/to/api")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response restorePost(@Context HttpServletRequest httpRequest,
                            @FormDataParam("file") InputStream file) {

    return service.processRequest(httpRequest, file);
}

Is it another way of doing this in 3.4.0?


Answer:

After asking this question to the Neo4J support I got this answer:

Unlike in Neo4j 3.3.5 which includes:

$NEO4J_HOME/lib/jersey-server-1.19.jar $NEO4J_HOME/lib/jersey-core-1.19.jar $NEO4J_HOME/lib/jersey-multipart-1.19.jar $NEO4J_HOME/lib/jersey-servlet-1.19.jar

3.4.0 no longer includes:

$NEO4J_HOME/lib/jersey-multipart-1.19.jar

since it is no longer used by the core Neo4j database. However you should be able to simply add a new dependency similar to what is described at https://mvnrepository.com/artifact/com.sun.jersey.contribs/jersey-multipart/1.9.1 then this should address your issue.

So in my scenario this was solved by adding this dependency to our pom.xml:

<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-multipart</artifactId>
    <version>1.19.3</version>
</dependency>

Note that the version differs from what is linked in the response from Neo4J. Not sure if the answer is wrong, or if it is because I am testing this on a release candidate. But in my version 3.4.0 RC Neo4J server, the jersey version included is 1.19.3 and not 1.19.1 (check in the "lib" folder of your Neo4J server).

Apart from this you need to make sure that the proper jar's are deployed to your Neo4J plugins folder. In our case we do this with a configuration in maven, but you could also add the dependencies manually. Note that jersey-multipart 1.19.3 is dependent on mimepull 1.9.3, so you need to add both.