source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/RestServer.java @ 3:47b53ae385d1

Last change on this file since 3:47b53ae385d1 was 3:47b53ae385d1, checked in by casties, 12 years ago

merging old code

File size: 7.9 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;
30import org.restlet.security.ChallengeAuthenticator;
31
32import scala.sys.process.ProcessBuilderImpl.Dummy;
33
34public class RestServer extends Application {
35
36    public static Logger logger = Logger.getRootLogger();
37
38    private ChallengeAuthenticator authenticator;
39
40    /**
41     * Properties holding consumer keys and secrets
42     */
43    private Properties consumerKeys;
44    public String CONSUMER_KEYS_PATH = "WEB-INF/consumerkeys.property";
45
46    private GraphDatabaseService graphDb;
47    public static final String GRAPHDB_KEY = "annotationmanager.graphdb";
48    public String DB_PATH = "WEB-INF/neo4j-annotation-db";
49
50    /**
51     * constructor
52     *
53     * @param parentContext
54     */
55    public RestServer(Context parentContext) {
56        super(parentContext);
57        // TODO: is this the right place to run the log4j configurator?
58        BasicConfigurator.configure();
59
60        ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes()
61                .get("org.restlet.ext.servlet.ServletContext");
62        if (sc != null) {
63            // look for database service in context
64            graphDb = (GraphDatabaseService) sc.getAttribute(GRAPHDB_KEY);
65            if (graphDb == null) {
66                /*
67                 * open database
68                 */
69                String dbFn = getResourcePath(sc, DB_PATH);
70                if (dbFn != null) {
71                    logger.debug("opening DB " + dbFn);
72                    graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbFn);
73                    // store in context
74                    sc.setAttribute(GRAPHDB_KEY, graphDb);
75                    WrappingNeoServerBootstrapper srv = new WrappingNeoServerBootstrapper((AbstractGraphDatabase) graphDb);
76                    logger.debug("Starting DB admin server...");
77                    srv.start();
78                } else {
79                    logger.error("Unable to get resource " + DB_PATH);
80                }
81            }
82            /*
83             * read consumerKeys from webapp
84             */
85            consumerKeys = new Properties();
86            InputStream ps = getResourceAsStream(sc, CONSUMER_KEYS_PATH);
87            if (ps != null) {
88                logger.debug("loading consumer keys from " + CONSUMER_KEYS_PATH);
89                try {
90                    consumerKeys.load(ps);
91                } catch (IOException e) {
92                    // TODO Auto-generated catch block
93                    e.printStackTrace();
94                }
95                logger.debug("consumer keys: " + consumerKeys);
96            } else {
97                logger.error("Unable to get resource " + CONSUMER_KEYS_PATH);
98            }
99        } else {
100            logger.error("Unable to get ServletContext!");
101        }
102
103    }
104
105    /**
106     * returns consumer secret for consumer key. returns null if consumer key
107     * doesn't exist.
108     *
109     * @param consumerKey
110     * @return
111     */
112    public String getConsumerSecret(String consumerKey) {
113        return consumerKeys.getProperty(consumerKey);
114    }
115
116    /*
117     * (non-Javadoc)
118     *
119     * @see org.restlet.Application#createInboundRoot()
120     */
121    @Override
122    public Restlet createInboundRoot() {
123        // this.authenticator = createAuthenticator();
124
125        Router router = new Router(getContext());
126
127        router.attach("/annotator/annotations", AnnotatorAnnotations.class);
128        router.attach("/annotator/annotations/{id}", AnnotatorAnnotations.class);
129        // router.attach("/annotator/search", AnnotatorSearch.class);
130
131        // router.attach("",redirector); router.attach("/annotator",
132        // ExtendedAnnotationInput.class);
133
134        router.attach("/", AnnotatorInfo.class);
135        // authenticator.setNext(router);
136        // return authenticator;
137
138        return router;
139    }
140
141    /**
142     * Hole den vollen Benutzernamen aus dem LDAP
143     *
144     * @param creator
145     * @return
146     */
147    public String getUserNameFromLdap(String creator) {
148        String retString = creator; // falls nichts gefunden wird einfach den
149                                    // creator zurueckgeben
150        Hashtable<String, String> env = new Hashtable<String, String>();
151        String sp = "com.sun.jndi.ldap.LdapCtxFactory";
152        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, sp);
153
154        // TODO: should go into config file
155        String ldapUrl = "ldap://ldapreplik.mpiwg-berlin.mpg.de/dc=mpiwg-berlin,dc=mpg,dc=de"; 
156        env.put(javax.naming.Context.PROVIDER_URL, ldapUrl);
157
158        DirContext dctx;
159        try {
160            dctx = new InitialDirContext(env);
161        } catch (NamingException e1) {
162            // TODO Auto-generated catch block
163            e1.printStackTrace();
164            return retString;
165        }
166
167        String base = "ou=People";
168
169        SearchControls sc = new SearchControls();
170        String[] attributeFilter = { "cn", "mail" };
171        sc.setReturningAttributes(attributeFilter);
172        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
173
174        String filter = "(uid=" + creator + ")";
175
176        try {
177            NamingEnumeration<SearchResult> results = dctx.search(base, filter, sc);
178            while (results.hasMore()) {
179                SearchResult sr = (SearchResult) results.next();
180                javax.naming.directory.Attributes attrs = sr.getAttributes();
181
182                Attribute attr = attrs.get("cn");
183                retString = (String) attr.get();
184            }
185        } catch (NamingException e) {
186            // TODO Auto-generated catch block
187            e.printStackTrace();
188        }
189
190        try {
191            dctx.close();
192        } catch (NamingException e) {
193            // TODO Auto-generated catch block
194            e.printStackTrace();
195        }
196        return retString;
197    }
198
199    /**
200     * returns resource from path (in webapp) as InputStream.
201     *
202     * @param sc
203     * @param path
204     * @return
205     */
206    protected InputStream getResourceAsStream(ServletContext sc, String path) {
207        InputStream ps = sc.getResourceAsStream(path);
208        if (ps == null) {
209            // try as file
210            File pf = new File(sc.getRealPath(path));
211            if (pf != null) {
212                logger.debug("trying file for: " + pf);
213                try {
214                    ps = new FileInputStream(pf);
215                } catch (FileNotFoundException e) {
216                    logger.error(e);
217                }
218            }
219        }
220        return ps;
221    }
222
223    /**
224     * get a real file name for a web app file pathname.
225     *
226     * If filename starts with "/" its treated as absolute else the path is
227     * appended to the base directory of the web-app.
228     *
229     * @param filename
230     * @param sc
231     * @return
232     */
233    public static String getResourcePath(ServletContext sc, String filename) {
234        File f = new File(filename);
235        // is the filename absolute?
236        if (!f.isAbsolute()) {
237            // relative path -> use getRealPath to resolve in webapp
238            filename = sc.getRealPath(filename);
239        }
240        return filename;
241    }
242
243}
Note: See TracBrowser for help on using the repository browser.