source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/RestServer.java @ 15:58357a4b86de

Last change on this file since 15:58357a4b86de was 15:58357a4b86de, checked in by casties, 12 years ago

ASSIGNED - # 249: Annotations shared in groups
https://it-dev.mpiwg-berlin.mpg.de/tracs/mpdl-project-software/ticket/249

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