source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/RestServer.java @ 6:6dfbe2400f64

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

delete annotation should work now.

File size: 10.5 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
169        // router.attach("",redirector); router.attach("/annotator",
170        // ExtendedAnnotationInput.class);
171
172        router.attach("/", AnnotatorInfo.class);
173        // authenticator.setNext(router);
174        // return authenticator;
175
176        return router;
177    }
178
179    /**
180     * Hole den vollen Benutzernamen aus dem LDAP
181     *
182     * @param creator
183     * @return
184     */
185    public String getFullNameFromLdap(String creator) {
186        String retString = creator; // falls nichts gefunden wird einfach den
187                                    // creator zurueckgeben
188        if (ldapServerUrl == null) {
189                return retString;
190        }
191        Hashtable<String, String> env = new Hashtable<String, String>();
192        String sp = "com.sun.jndi.ldap.LdapCtxFactory";
193        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, sp);
194
195        env.put(javax.naming.Context.PROVIDER_URL, ldapServerUrl);
196
197        DirContext dctx;
198        try {
199            dctx = new InitialDirContext(env);
200        } catch (NamingException e1) {
201            // TODO Auto-generated catch block
202            e1.printStackTrace();
203            return retString;
204        }
205
206        String base = "ou=people";
207
208        SearchControls sc = new SearchControls();
209        String[] attributeFilter = { "cn", "mail" };
210        sc.setReturningAttributes(attributeFilter);
211        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
212
213        String filter = "(uid=" + creator + ")";
214
215        try {
216            NamingEnumeration<SearchResult> results = dctx.search(base, filter, sc);
217            while (results.hasMore()) {
218                SearchResult sr = (SearchResult) results.next();
219                javax.naming.directory.Attributes attrs = sr.getAttributes();
220
221                Attribute attr = attrs.get("cn");
222                retString = (String) attr.get();
223            }
224        } catch (NamingException e) {
225            // TODO Auto-generated catch block
226            e.printStackTrace();
227        }
228
229        try {
230            dctx.close();
231        } catch (NamingException e) {
232            // TODO Auto-generated catch block
233            e.printStackTrace();
234        }
235        return retString;
236    }
237
238    /**
239     * returns resource from path (in webapp) as InputStream.
240     *
241     * @param sc
242     * @param path
243     * @return
244     */
245    protected InputStream getResourceAsStream(ServletContext sc, String path) {
246        InputStream ps = sc.getResourceAsStream(path);
247        if (ps == null) {
248            // try as file
249            File pf = new File(sc.getRealPath(path));
250            if (pf != null) {
251                logger.debug("trying file for: " + pf);
252                try {
253                    ps = new FileInputStream(pf);
254                } catch (FileNotFoundException e) {
255                    logger.error(e);
256                }
257            }
258        }
259        return ps;
260    }
261
262    /**
263     * get a real file name for a web app file pathname.
264     *
265     * If filename starts with "/" its treated as absolute else the path is
266     * appended to the base directory of the web-app.
267     *
268     * @param filename
269     * @param sc
270     * @return
271     */
272    public static String getResourcePath(ServletContext sc, String filename) {
273        File f = new File(filename);
274        // is the filename absolute?
275        if (!f.isAbsolute()) {
276            // relative path -> use getRealPath to resolve in webapp
277            filename = sc.getRealPath(filename);
278        }
279        return filename;
280    }
281
282    /* (non-Javadoc)
283     * @see org.restlet.Application#stop()
284     */
285    @Override
286    public synchronized void stop() throws Exception {
287        /*
288         * trying to clean up databases, nur sure if this is the right way...
289         */
290        if (srv != null) {
291            logger.debug("Stopping DB admin server...");
292            srv.stop();
293            srv = null;
294        }
295        if (graphDb != null) {
296            logger.debug("Stopping DB...");
297            graphDb.shutdown();
298            graphDb = null;
299        }
300        super.stop();
301    }
302
303    private static void registerShutdownHook(final GraphDatabaseService graphDb) {
304        // Registers a shutdown hook for the Neo4j instance so that it
305        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
306        // running example before it's completed)
307        Runtime.getRuntime().addShutdownHook(new Thread() {
308            @Override
309            public void run() {
310                graphDb.shutdown();
311            }
312        });
313    }
314   
315   
316}
Note: See TracBrowser for help on using the repository browser.