Mercurial > hg > AnnotationManager
changeset 9:e9fd2e1e0979
consumer key and secret store (property file).
author | casties |
---|---|
date | Mon, 19 Mar 2012 21:26:20 +0100 |
parents | 11baadcdd2c8 |
children | 0bdfe01e30b5 |
files | .classpath .settings/org.eclipse.wst.common.project.facet.core.xml WebContent/WEB-INF/consumerkeys.property.template src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorSearch.java src/de/mpiwg/itgroup/annotationManager/restlet/RestServer.java |
diffstat | 5 files changed, 339 insertions(+), 231 deletions(-) [+] |
line wrap: on
line diff
--- a/.classpath Mon Mar 19 14:50:28 2012 +0100 +++ b/.classpath Mon Mar 19 21:26:20 2012 +0100 @@ -37,6 +37,15 @@ <classpathentry kind="lib" path="libs/httpcomponents-core-4.0-beta3/lib/httpcore-nio-4.0-beta3.jar"/> <classpathentry combineaccessrules="false" kind="src" path="/TripleStoreManager"/> <classpathentry kind="lib" path="libs/org.restlet.jar"/> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.launching.macosx.MacOSXType/JDK 1.6"/> + <classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v7.0"> + <attributes> + <attribute name="owner.project.facets" value="jst.web"/> + </attributes> + </classpathentry> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.launching.macosx.MacOSXType/Java SE 6 (MacOS X Default)"> + <attributes> + <attribute name="owner.project.facets" value="java"/> + </attributes> + </classpathentry> <classpathentry kind="output" path="build/classes"/> </classpath>
--- a/.settings/org.eclipse.wst.common.project.facet.core.xml Mon Mar 19 14:50:28 2012 +0100 +++ b/.settings/org.eclipse.wst.common.project.facet.core.xml Mon Mar 19 21:26:20 2012 +0100 @@ -1,5 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <faceted-project> + <runtime name="Apache Tomcat v7.0"/> <fixed facet="jst.web"/> <fixed facet="wst.jsdt.web"/> <fixed facet="java"/>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/WebContent/WEB-INF/consumerkeys.property.template Mon Mar 19 21:26:20 2012 +0100 @@ -0,0 +1,2 @@ +# consumer keys and secrets for annotation server clients +# format: consumerKey = consumerSecret
--- a/src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorSearch.java Mon Mar 19 14:50:28 2012 +0100 +++ b/src/de/mpiwg/itgroup/annotationManager/restlet/AnnotatorSearch.java Mon Mar 19 21:26:20 2012 +0100 @@ -26,152 +26,170 @@ import de.mpiwg.itgroup.triplestoremanager.exceptions.TripleStoreHandlerException; /** - * Implements the "search" uri of the Annotator API. - * see <https://github.com/okfn/annotator/wiki/Storage> + * Implements the "search" uri of the Annotator API. see + * <https://github.com/okfn/annotator/wiki/Storage> * * @author casties - * + * */ public class AnnotatorSearch extends AnnotatorResourceImpl { - + private Logger logger = Logger.getRootLogger(); protected String getAllowedMethodsForHeader() { return "OPTIONS,GET"; } - + /** - * JSON content type result. + * result for JSON content-type. optional search parameters: uri user limit + * offset * * @param entity * @return */ @Get("json") - public Representation doGetJSON(Representation entity){ - + public Representation doGetJSON(Representation entity) { + doOptions(entity); + + // check authToken + Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers"); + String ck = requestHeaders.getFirstValue("x-annotator-consumer-key", true); + if (ck != null) { + RestServer restServer = (RestServer) getApplication(); + String cs = restServer.getConsumerSecret(ck); + logger.debug("requested consumer key=" + ck + " secret=" + cs); + } + Form form = getRequest().getResourceRef().getQueryAsForm(); String uri = form.getFirstValue("uri"); String user = form.getFirstValue("user"); - String limit=form.getFirstValue("limit"); - String offset=form.getFirstValue("offset"); + String limit = form.getFirstValue("limit"); + String offset = form.getFirstValue("offset"); - RDFSearcher searcher = new RDFSearcher("file:///annotations"); //TODO should ge into config file + RDFSearcher searcher = new RDFSearcher("file:///annotations"); // TODO + // should + // ge + // into + // config + // file JSONArray ja; try { - - List<Convert.Annotation> annots=searcher.search(uri,user,limit,offset); + + List<Convert.Annotation> annots = searcher.search(uri, user, limit, offset); ja = new JSONArray(); - for (Convert.Annotation annot:annots){ + for (Convert.Annotation annot : annots) { JSONObject jo = annot2AnnotatorJSON(annot); - if (jo!=null){ + if (jo != null) { ja.put(annot2AnnotatorJSON(annot)); } else { - setStatus(Status.SERVER_ERROR_INTERNAL,"JSON Error"); + setStatus(Status.SERVER_ERROR_INTERNAL, "JSON Error"); return null; } } } catch (TripleStoreHandlerException e) { - // TODO Auto-generated catch block e.printStackTrace(); - setStatus(Status.SERVER_ERROR_INTERNAL,"TripleStoreHandler Error"); + setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreHandler Error"); return null; } catch (TripleStoreSearchError e) { - // TODO Auto-generated catch block e.printStackTrace(); - setStatus(Status.SERVER_ERROR_INTERNAL,"TripleStoreSearch Error"); + setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreSearch Error"); return null; - } + } JSONObject result = new JSONObject(); try { - result.put("rows",ja); - result.put("total",ja.length()); + result.put("rows", ja); + result.put("total", ja.length()); } catch (JSONException e) { - // TODO Auto-generated catch block e.printStackTrace(); - setStatus(Status.SERVER_ERROR_INTERNAL,"JSON Error"); + setStatus(Status.SERVER_ERROR_INTERNAL, "JSON Error"); return null; } - + logger.debug("sending:"); logger.debug(result); return new JsonRepresentation(result); } /** - * HTML content type result. + * result for HTML content-type. * * @param entity * @return */ @Get("html") - public Representation doGetHTML(Representation entity){ - + public Representation doGetHTML(Representation entity) { + doOptions(entity); Form form = getRequest().getResourceRef().getQueryAsForm(); String uri = form.getFirstValue("uri"); String user = form.getFirstValue("user"); - String limit=form.getFirstValue("limit"); - String offset=form.getFirstValue("offset"); + String limit = form.getFirstValue("limit"); + String offset = form.getFirstValue("offset"); try { - if (uri!=null){ - uri = URLDecoder.decode(uri, "utf-8"); + if (uri != null) { + uri = URLDecoder.decode(uri, "utf-8"); } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE); return null; } - - RDFSearcher searcher = new RDFSearcher("file:///annotations"); //TODO should ge into config file - String retString="<html><body><table>"; - String lineFormat="<tr><td><a href=\"%s\">%s</a></td>" + - "<td><a href=\"%s\">%s</a></td><td>%s</td><td>%s</td><td><a href=\"%s\">%s</a></td><td><a href=\"%s\">%s</a></td></div>"; + RDFSearcher searcher = new RDFSearcher("file:///annotations"); // TODO + // should + // ge + // into + // config + // file + + String retString = "<html><body><table>"; + String lineFormat = "<tr><td><a href=\"%s\">%s</a></td>" + + "<td><a href=\"%s\">%s</a></td><td>%s</td><td>%s</td><td><a href=\"%s\">%s</a></td><td><a href=\"%s\">%s</a></td></div>"; try { - - List<Convert.Annotation> annots=searcher.search(uri,user,limit,offset); + + List<Convert.Annotation> annots = searcher.search(uri, user, limit, offset); - for (Convert.Annotation annot:annots){ - - + for (Convert.Annotation annot : annots) { + RestServer restServer = (RestServer) getApplication(); - String userName=restServer.getUserNameFromLdap(annot.creator); + String userName = restServer.getUserNameFromLdap(annot.creator); List<String> xpointer = new ArrayList<String>(); - if (annot.xpointers==null || annot.xpointers.size()==0) - retString+=String.format(lineFormat, userName,userName,annot.url,annot.url,annot.time,annot.text,annot.xpointer,annot.xpointer,annot.annotationUri,annot.annotationUri); + if (annot.xpointers == null || annot.xpointers.size() == 0) + retString += String.format(lineFormat, userName, userName, annot.url, annot.url, annot.time, annot.text, + annot.xpointer, annot.xpointer, annot.annotationUri, annot.annotationUri); else { - for(String xpointerString:annot.xpointers){ - retString+=String.format(lineFormat, userName,userName,annot.url,annot.url,annot.time,annot.text,xpointerString,xpointerString,annot.annotationUri,annot.annotationUri); + for (String xpointerString : annot.xpointers) { + retString += String.format(lineFormat, userName, userName, annot.url, annot.url, annot.time, annot.text, + xpointerString, xpointerString, annot.annotationUri, annot.annotationUri); } } - + } } catch (TripleStoreHandlerException e) { // TODO Auto-generated catch block e.printStackTrace(); - setStatus(Status.SERVER_ERROR_INTERNAL,"TripleStoreHandler Error"); + setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreHandler Error"); return null; } catch (TripleStoreSearchError e) { // TODO Auto-generated catch block e.printStackTrace(); - setStatus(Status.SERVER_ERROR_INTERNAL,"TripleStoreSearch Error"); + setStatus(Status.SERVER_ERROR_INTERNAL, "TripleStoreSearch Error"); return null; - } + } - retString+="</table></body></html>"; - + retString += "</table></body></html>"; + logger.debug("sending:"); logger.debug(retString); - return new StringRepresentation(retString,MediaType.TEXT_HTML); + return new StringRepresentation(retString, MediaType.TEXT_HTML); } - }
--- a/src/de/mpiwg/itgroup/annotationManager/restlet/RestServer.java Mon Mar 19 14:50:28 2012 +0100 +++ b/src/de/mpiwg/itgroup/annotationManager/restlet/RestServer.java Mon Mar 19 21:26:20 2012 +0100 @@ -1,8 +1,14 @@ package de.mpiwg.itgroup.annotationManager.restlet; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Hashtable; +import java.util.Properties; import javax.naming.NamingEnumeration; import javax.naming.NamingException; @@ -12,10 +18,10 @@ import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; +import javax.servlet.ServletContext; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; @@ -34,16 +40,78 @@ import com.sun.security.auth.login.ConfigFile; - - - public class RestServer extends Application { - - private ChallengeAuthenticator authenticator; - private CallbackHandler callbackHandler; + private ChallengeAuthenticator authenticator; + + /** + * Properties holding consumer keys and secrets + */ + private Properties consumerKeys; + public final String CONSUMER_KEYS_PATH = "WEB-INF/consumerkeys.property"; + + /** + * constructor + * + * @param parentContext + */ + public RestServer(Context parentContext) { + super(parentContext); - /** Erzeuge einen Authenticator + Logger rl = Logger.getRootLogger(); + BasicConfigurator.configure(); + rl.setLevel(Level.DEBUG); + // read consumerKeys from webapp + consumerKeys = new Properties(); + ServletContext sc = (ServletContext) getContext().getServerDispatcher() + .getContext().getAttributes() + .get("org.restlet.ext.servlet.ServletContext"); + if (sc != null) { + InputStream ps = sc.getResourceAsStream(CONSUMER_KEYS_PATH); + if (ps == null) { + // try as file + File pf = new File(sc.getRealPath(CONSUMER_KEYS_PATH)); + if (pf != null) { + rl.debug("trying file for consumer keys: "+pf); + try { + ps = new FileInputStream(pf); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + if (ps != null) { + rl.debug("loading consumer keys from "+CONSUMER_KEYS_PATH); + try { + consumerKeys.load(ps); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + rl.debug("consumer keys: "+consumerKeys); + } else { + rl.error("Unable to get resource "+CONSUMER_KEYS_PATH); + } + } else { + rl.error("Unable to get ServletContext!"); + } + + } + + /** + * returns consumer secret for consumer key. + * returns null if consumer key doesn't exist. + * @param consumerKey + * @return + */ + public String getConsumerSecret(String consumerKey) { + return consumerKeys.getProperty(consumerKey); + } + + /** + * Erzeuge einen Authenticator + * * @return */ private ChallengeAuthenticator createAuthenticator() { @@ -52,17 +120,18 @@ ChallengeScheme challengeScheme = ChallengeScheme.HTTP_BASIC; String realm = "Annotation Service"; - JaasVerifier verifier = new JaasVerifier("BasicJaasAuthenticationApplication"); - //JaasVerifier verifier = new JaasVerifier("DummyAuthentication"); - + JaasVerifier verifier = new JaasVerifier( + "BasicJaasAuthenticationApplication"); + // JaasVerifier verifier = new JaasVerifier("DummyAuthentication"); + Configuration jaasConfig; jaasConfig = createConfiguration(); - - - verifier.setConfiguration(jaasConfig); + + verifier.setConfiguration(jaasConfig); verifier.setUserPrincipalClassName("com.sun.security.auth.UserPrincipal"); - - ChallengeAuthenticator auth = new ChallengeAuthenticator(context, optional, challengeScheme, realm, verifier) { + + ChallengeAuthenticator auth = new ChallengeAuthenticator(context, + optional, challengeScheme, realm, verifier) { @Override protected boolean authenticate(Request request, Response response) { if (request.getChallengeResponse() == null) { @@ -76,174 +145,183 @@ return auth; } - /** - * Konfiguration f�r den Authentificator in Jaas. Pfad zum JAAS-Konfigurationsfile liegt im Context-Parameter - * "de.mpiwg.itgroup.annotationManager.jaas.configFilePath". - * @return - */ - protected Configuration createConfiguration() { - Configuration jaasConfig; - URI confUri; - - Context context = getContext(); - String configFilePath = context.getParameters().getFirstValue("de.mpiwg.itgroup.annotationManager.jaas.configFilePath"); - - - try { - confUri = new URI(configFilePath); - } catch (URISyntaxException e) { - e.printStackTrace(); - confUri = null; - } - - jaasConfig= new ConfigFile(confUri); - return jaasConfig; - } + /** + * Konfiguration fuer den Authentificator in Jaas. Pfad zum + * JAAS-Konfigurationsfile liegt im Context-Parameter + * "de.mpiwg.itgroup.annotationManager.jaas.configFilePath". + * + * @return + */ + protected Configuration createConfiguration() { + Configuration jaasConfig; + URI confUri; + + Context context = getContext(); + String configFilePath = context.getParameters().getFirstValue( + "de.mpiwg.itgroup.annotationManager.jaas.configFilePath"); - public RestServer(Context parentContext){ - super(parentContext); - - Logger rl = Logger.getRootLogger(); - BasicConfigurator.configure(); - rl.setLevel(Level.DEBUG); - - - } - - public synchronized Restlet createInboundRoot(){ - this.authenticator = createAuthenticator(); + try { + confUri = new URI(configFilePath); + } catch (URISyntaxException e) { + e.printStackTrace(); + confUri = null; + } + + jaasConfig = new ConfigFile(confUri); + return jaasConfig; + } + + /* + * (non-Javadoc) + * + * @see org.restlet.Application#createInboundRoot() + */ + public synchronized Restlet createInboundRoot() { + this.authenticator = createAuthenticator(); + + // String target = "{rh}/{rf}/XX"; + // Redirector redirector = new + // Redirector(getContext().createChildContext(), target, + // Redirector.MODE_CLIENT_SEE_OTHER); - - //String target = "{rh}/{rf}/XX"; - //Redirector redirector = new Redirector(getContext().createChildContext(), target, - // Redirector.MODE_CLIENT_SEE_OTHER); - - Router router = new Router(getContext()); - - - router.attach("/annotations",AddAndReadAnnotations.class); - router.attach("/search",AnnotatorSearch.class); // annotator api askes for different uris for search and adding - //router.attach("/search",SearchAnnotations.class); // annotator api askes for different uris for search and adding - router.attach("/dummy",Dummy.class); - - //router.attach("",redirector); - router.attach("/annotator",ExtendedAnnotationInput.class); - router.attach("/",AnnotatorInfo.class); - authenticator.setNext(router); - return authenticator; + Router router = new Router(getContext()); + + router.attach("/annotations", AddAndReadAnnotations.class); + router.attach("/search", AnnotatorSearch.class); // annotator api askes + // for different uris + // for search and + // adding + // router.attach("/search",SearchAnnotations.class); // annotator api + // askes for different uris for search and adding + router.attach("/dummy", Dummy.class); + + // router.attach("",redirector); + router.attach("/annotator", ExtendedAnnotationInput.class); + router.attach("/", AnnotatorInfo.class); + authenticator.setNext(router); + return authenticator; + } - - - } - - /** - * Authentifiziere den Benutzer aus dem Request (BasicAuthenfication) - * @param request - * @param response - * @return - */ - public boolean authenticate(Request request, Response response) { - if (!request.getClientInfo().isAuthenticated()) { - authenticator.challenge(response, false); - return false; - } - - if(request.getClientInfo().getUser()==null) //FIXME sometimes ist authenticated true, but no user - { - authenticator.challenge(response, false); - return false; - } - - - return true; - } + /** + * Authentifiziere den Benutzer aus dem Request (BasicAuthenfication) + * + * @param request + * @param response + * @return + */ + public boolean authenticate(Request request, Response response) { + if (!request.getClientInfo().isAuthenticated()) { + authenticator.challenge(response, false); + return false; + } + + if (request.getClientInfo().getUser() == null) // FIXME sometimes ist + // authenticated true, + // but no user + { + authenticator.challenge(response, false); + return false; + } + return true; + } - /** - * Authentifiziere den Benutzer - * - * @param username - * @param password - * @param request - * @return - */ - public boolean authenticate(String username, String password,Request request) { - LoginContext lc; - - try { - Configuration conf = createConfiguration(); - - lc = new LoginContext("BasicJaasAuthenticationApplication", null, new MyCallBackHandler(username,password),conf); - //lc = new LoginContext("DummyAuthentication", null, new MyCallBackHandler(username,password),conf); - lc.login(); - } catch (LoginException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return false; - } - - Subject subject = lc.getSubject(); - ClientInfo clientInfo = new ClientInfo(); - User user = new User(username); - clientInfo.setAuthenticated(true); - clientInfo.setUser(user); - - request.setClientInfo(clientInfo); - return true; - } + /** + * Authentifiziere den Benutzer + * + * @param username + * @param password + * @param request + * @return + */ + public boolean authenticate(String username, String password, + Request request) { + LoginContext lc; + + try { + Configuration conf = createConfiguration(); - /** - * Hole den vollen Benutzernamen aus dem LDAP - * @param creator - * @return - */ - public String getUserNameFromLdap(String creator) { - String retString=creator; // falls nichts gefunden wird einfach den creator zurueckgeben - Hashtable<String,String> env = new Hashtable<String,String>(); - String sp = "com.sun.jndi.ldap.LdapCtxFactory"; - env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, sp); + lc = new LoginContext("BasicJaasAuthenticationApplication", null, + new MyCallBackHandler(username, password), conf); + // lc = new LoginContext("DummyAuthentication", null, new + // MyCallBackHandler(username,password),conf); + lc.login(); + } catch (LoginException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return false; + } + + Subject subject = lc.getSubject(); + ClientInfo clientInfo = new ClientInfo(); + User user = new User(username); + clientInfo.setAuthenticated(true); + clientInfo.setUser(user); + + request.setClientInfo(clientInfo); + return true; + } + + /** + * Hole den vollen Benutzernamen aus dem LDAP + * + * @param creator + * @return + */ + public String getUserNameFromLdap(String creator) { + String retString = creator; // falls nichts gefunden wird einfach den + // creator zurueckgeben + Hashtable<String, String> env = new Hashtable<String, String>(); + String sp = "com.sun.jndi.ldap.LdapCtxFactory"; + env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, sp); - String ldapUrl = "ldap://ldapreplik.mpiwg-berlin.mpg.de/dc=mpiwg-berlin,dc=mpg,dc=de";//TODO should go into config file - env.put(javax.naming.Context.PROVIDER_URL, ldapUrl); + String ldapUrl = "ldap://ldapreplik.mpiwg-berlin.mpg.de/dc=mpiwg-berlin,dc=mpg,dc=de";// TODO + // should + // go + // into + // config + // file + env.put(javax.naming.Context.PROVIDER_URL, ldapUrl); - DirContext dctx; - try { - dctx = new InitialDirContext(env); - } catch (NamingException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - return retString; - } + DirContext dctx; + try { + dctx = new InitialDirContext(env); + } catch (NamingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + return retString; + } - String base = "ou=People"; + String base = "ou=People"; - SearchControls sc = new SearchControls(); - String[] attributeFilter = { "cn", "mail" }; - sc.setReturningAttributes(attributeFilter); - sc.setSearchScope(SearchControls.SUBTREE_SCOPE); - - String filter = "(uid="+creator+")"; + SearchControls sc = new SearchControls(); + String[] attributeFilter = { "cn", "mail" }; + sc.setReturningAttributes(attributeFilter); + sc.setSearchScope(SearchControls.SUBTREE_SCOPE); - try { - NamingEnumeration<SearchResult> results = dctx.search(base, filter, sc); - while (results.hasMore()) { - SearchResult sr = (SearchResult) results.next(); - javax.naming.directory.Attributes attrs = sr.getAttributes(); + String filter = "(uid=" + creator + ")"; + + try { + NamingEnumeration<SearchResult> results = dctx.search(base, filter, + sc); + while (results.hasMore()) { + SearchResult sr = (SearchResult) results.next(); + javax.naming.directory.Attributes attrs = sr.getAttributes(); - Attribute attr = attrs.get("cn"); - retString=(String) attr.get(); - } - } catch (NamingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - dctx.close(); - } catch (NamingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return retString; - } + Attribute attr = attrs.get("cn"); + retString = (String) attr.get(); + } + } catch (NamingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + dctx.close(); + } catch (NamingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return retString; + } }