source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/BaseRestlet.java @ 19:f0f55ab768c9

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

more work on HTML UI.

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