source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/RestServer.java @ 4:3599b29c393f

Last change on this file since 4:3599b29c393f was 4:3599b29c393f, checked in by casties, 12 years ago

store seems to work now :-)

File size: 9.4 KB
Line 
1package de.mpiwg.itgroup.annotations.restlet;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileNotFoundException;
6import java.io.IOException;
7import java.io.InputStream;
8import java.util.Hashtable;
9import java.util.Properties;
10
11import javax.naming.NamingEnumeration;
12import javax.naming.NamingException;
13import javax.naming.directory.Attribute;
14import javax.naming.directory.DirContext;
15import javax.naming.directory.InitialDirContext;
16import javax.naming.directory.SearchControls;
17import javax.naming.directory.SearchResult;
18import javax.servlet.ServletContext;
19
20import org.apache.log4j.BasicConfigurator;
21import org.apache.log4j.Logger;
22import org.neo4j.graphdb.GraphDatabaseService;
23import org.neo4j.graphdb.factory.GraphDatabaseFactory;
24import org.neo4j.kernel.AbstractGraphDatabase;
25import org.neo4j.server.WrappingNeoServerBootstrapper;
26import org.restlet.Application;
27import org.restlet.Context;
28import org.restlet.Restlet;
29import org.restlet.routing.Router;
30
31import de.mpiwg.itgroup.annotations.neo4j.AnnotationStore;
32
33public class RestServer extends Application {
34
35    public static Logger logger = Logger.getLogger(RestServer.class);
36
37    /**
38     * Properties holding consumer keys and secrets
39     */
40    private Properties consumerKeys;
41    public String CONSUMER_KEYS_PATH = "WEB-INF/consumerkeys.property";
42
43    private GraphDatabaseService graphDb;
44    public static final String GRAPHDB_KEY = "annotationmanager.graphdb";
45    public String DB_PATH = "WEB-INF/neo4j-annotation-db";
46
47    private WrappingNeoServerBootstrapper srv;
48    public static final String GRAPHDBSRV_KEY = "annotationmanager.graphdb.srv";
49   
50    private AnnotationStore store;
51    public static final String ANNSTORE_KEY = "annotationmanager.store";
52
53    /**
54     * constructor
55     *
56     * @param parentContext
57     */
58    public RestServer(Context parentContext) {
59        super(parentContext);
60        // TODO: is this the right place to run the log4j configurator?
61        BasicConfigurator.configure();
62
63        ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes()
64                .get("org.restlet.ext.servlet.ServletContext");
65        if (sc != null) {
66            // look for database service in context
67            graphDb = (GraphDatabaseService) sc.getAttribute(GRAPHDB_KEY);
68            if (graphDb == null) {
69                /*
70                 * open database
71                 */
72                String dbFn = getResourcePath(sc, DB_PATH);
73                if (dbFn != null) {
74                    logger.debug("opening DB " + dbFn);
75                    graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbFn);
76                    registerShutdownHook(graphDb);
77                    // store in context
78                    sc.setAttribute(GRAPHDB_KEY, graphDb);
79                    // AnnotationStore
80                    store = new AnnotationStore(graphDb);
81                    sc.setAttribute(ANNSTORE_KEY, store);
82                    // admin server
83                    srv = new WrappingNeoServerBootstrapper((AbstractGraphDatabase) graphDb);
84                    logger.debug("Starting DB admin server...");
85                    // store in context
86                    sc.setAttribute(GRAPHDBSRV_KEY, srv);
87                    srv.start();
88                } else {
89                    logger.error("Unable to get resource " + DB_PATH);
90                }
91            }
92            /*
93             * read consumerKeys from webapp
94             */
95            consumerKeys = new Properties();
96            InputStream ps = getResourceAsStream(sc, CONSUMER_KEYS_PATH);
97            if (ps != null) {
98                logger.debug("loading consumer keys from " + CONSUMER_KEYS_PATH);
99                try {
100                    consumerKeys.load(ps);
101                } catch (IOException e) {
102                    // TODO Auto-generated catch block
103                    e.printStackTrace();
104                }
105                logger.debug("consumer keys: " + consumerKeys);
106            } else {
107                logger.error("Unable to get resource " + CONSUMER_KEYS_PATH);
108            }
109        } else {
110            logger.error("Unable to get ServletContext!");
111        }
112
113    }
114
115    /**
116     * returns consumer secret for consumer key. returns null if consumer key
117     * doesn't exist.
118     *
119     * @param consumerKey
120     * @return
121     */
122    public String getConsumerSecret(String consumerKey) {
123        return consumerKeys.getProperty(consumerKey);
124    }
125
126    /*
127     * (non-Javadoc)
128     *
129     * @see org.restlet.Application#createInboundRoot()
130     */
131    @Override
132    public Restlet createInboundRoot() {
133        // this.authenticator = createAuthenticator();
134
135        Router router = new Router(getContext());
136
137        router.attach("/annotator/annotations", AnnotatorAnnotations.class);
138        router.attach("/annotator/annotations/{id}", AnnotatorAnnotations.class);
139        router.attach("/annotator/search", AnnotatorSearch.class);
140
141        // router.attach("",redirector); router.attach("/annotator",
142        // ExtendedAnnotationInput.class);
143
144        router.attach("/", AnnotatorInfo.class);
145        // authenticator.setNext(router);
146        // return authenticator;
147
148        return router;
149    }
150
151    /**
152     * Hole den vollen Benutzernamen aus dem LDAP
153     *
154     * @param creator
155     * @return
156     */
157    public String getUserNameFromLdap(String creator) {
158        String retString = creator; // falls nichts gefunden wird einfach den
159                                    // creator zurueckgeben
160        Hashtable<String, String> env = new Hashtable<String, String>();
161        String sp = "com.sun.jndi.ldap.LdapCtxFactory";
162        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, sp);
163
164        // TODO: should go into config file
165        String ldapUrl = "ldap://ldapreplik.mpiwg-berlin.mpg.de/dc=mpiwg-berlin,dc=mpg,dc=de"; 
166        env.put(javax.naming.Context.PROVIDER_URL, ldapUrl);
167
168        DirContext dctx;
169        try {
170            dctx = new InitialDirContext(env);
171        } catch (NamingException e1) {
172            // TODO Auto-generated catch block
173            e1.printStackTrace();
174            return retString;
175        }
176
177        String base = "ou=People";
178
179        SearchControls sc = new SearchControls();
180        String[] attributeFilter = { "cn", "mail" };
181        sc.setReturningAttributes(attributeFilter);
182        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
183
184        String filter = "(uid=" + creator + ")";
185
186        try {
187            NamingEnumeration<SearchResult> results = dctx.search(base, filter, sc);
188            while (results.hasMore()) {
189                SearchResult sr = (SearchResult) results.next();
190                javax.naming.directory.Attributes attrs = sr.getAttributes();
191
192                Attribute attr = attrs.get("cn");
193                retString = (String) attr.get();
194            }
195        } catch (NamingException e) {
196            // TODO Auto-generated catch block
197            e.printStackTrace();
198        }
199
200        try {
201            dctx.close();
202        } catch (NamingException e) {
203            // TODO Auto-generated catch block
204            e.printStackTrace();
205        }
206        return retString;
207    }
208
209    /**
210     * returns resource from path (in webapp) as InputStream.
211     *
212     * @param sc
213     * @param path
214     * @return
215     */
216    protected InputStream getResourceAsStream(ServletContext sc, String path) {
217        InputStream ps = sc.getResourceAsStream(path);
218        if (ps == null) {
219            // try as file
220            File pf = new File(sc.getRealPath(path));
221            if (pf != null) {
222                logger.debug("trying file for: " + pf);
223                try {
224                    ps = new FileInputStream(pf);
225                } catch (FileNotFoundException e) {
226                    logger.error(e);
227                }
228            }
229        }
230        return ps;
231    }
232
233    /**
234     * get a real file name for a web app file pathname.
235     *
236     * If filename starts with "/" its treated as absolute else the path is
237     * appended to the base directory of the web-app.
238     *
239     * @param filename
240     * @param sc
241     * @return
242     */
243    public static String getResourcePath(ServletContext sc, String filename) {
244        File f = new File(filename);
245        // is the filename absolute?
246        if (!f.isAbsolute()) {
247            // relative path -> use getRealPath to resolve in webapp
248            filename = sc.getRealPath(filename);
249        }
250        return filename;
251    }
252
253    /* (non-Javadoc)
254     * @see org.restlet.Application#stop()
255     */
256    @Override
257    public synchronized void stop() throws Exception {
258        /*
259         * trying to clean up databases, nur sure if this is the right way...
260         */
261        if (srv != null) {
262            logger.debug("Stopping DB admin server...");
263            srv.stop();
264            srv = null;
265        }
266        if (graphDb != null) {
267            logger.debug("Stopping DB...");
268            graphDb.shutdown();
269            graphDb = null;
270        }
271        super.stop();
272    }
273
274    private static void registerShutdownHook(final GraphDatabaseService graphDb) {
275        // Registers a shutdown hook for the Neo4j instance so that it
276        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
277        // running example before it's completed)
278        Runtime.getRuntime().addShutdownHook(new Thread() {
279            @Override
280            public void run() {
281                graphDb.shutdown();
282            }
283        });
284    }
285   
286   
287}
Note: See TracBrowser for help on using the repository browser.