source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/RestServer.java @ 5:bbf0cc5bee29

Last change on this file since 5:bbf0cc5bee29 was 5:bbf0cc5bee29, checked in by casties, 12 years ago

version 0.2 really works now

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