How to retrieve a (graph connecion) static server variable from GWT RequestFactory

124 views Asked by At

I know this concern a bit more GWT...

I am developing my first CWT app. And I am using RequestFactory. I take the example from "GWT In Action Second Edition". Inside the ContactService class where are the methods to access the database I wish to connect Neo4J Graph. In the constructor I added this

private static GraphDatabaseService graphDB;
public ContactService () {
String DB_PATH = "/home/myName/Developer/Workspace/MyGWTApp/DATA";
graphDB = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);  

}

I can CRUD with passing the static variable graphDB to the method, fetch(graphDB, id), persist(graphDB, c), and so on. All is working well. The first time the constructor give me a link the the graph. My problem is whenIi develop another service class by example FriendService I need my connection to graphDB again. I cannot recreate the same thing with the constructor


private static GraphDatabaseService graphDB;
public FriendService () {
    String DB_PATH = "/home/myName/Developer/Workspace/MyGWTApp/DATA";
    graphDB = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);  
 }

That is normal with Neo4J. I must retrieve only the value of my static variable graphDB. But how to do that?

I tried to create a servlet like that

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;


public class Neo4jServletContextListener implements ServletContextListener{

    public static GraphDatabaseService getGraphDB(ServletContext context) {
        return (GraphDatabaseService) context.getAttribute("neo4j");
    }
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        getGraphDB(arg0.getServletContext()).shutdown();
        //System.out.println("ServletContextListener destroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {

        String DB_PATH = "/home/myName/Developer/Workspace/MyGWTApp/DATA";
        GraphDatabaseService graphDB =
            new   GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);  
        ServletContext context = arg0.getServletContext();
        context.setAttribute ("neo4j", graphDB);

        //System.out.println("ServletContextListener started"); 
    }
}

But it is impossible to make this

graphDB = (GraphDatabaseService) getServletContext().getAttribute("neo4j");

I found somewhere in Stack Overflow this line which is running well

graphDB = (GraphDatabaseService) RequestFactoryServlet.getThreadLocalServletContext().getAttribute("neo4j");
1

There are 1 answers

0
Andrea Boscolo On

Correct. If you need to retrieve the ServletContext inside a running service during a request, use the static method RequestFactoryServlet.getThreadLocalServletContext().