changeset 4:aae47a713589

editing
author dwinter
date Mon, 02 Jan 2012 12:42:28 +0100
parents dfd72ea936ff
children a59be29f06c8
files .classpath .settings/org.eclipse.wst.common.component libs/org.json.jar libs/org.restlet.ext.jaas.jar libs/org.restlet.ext.json.jar src/de/mpiwg/itgroup/metaDataManagerRestlet/RestServer.java src/de/mpiwg/itgroup/nimanager/edit/Editor.java
diffstat 7 files changed, 435 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/.classpath	Thu Dec 29 15:19:29 2011 +0100
+++ b/.classpath	Mon Jan 02 12:42:28 2012 +0100
@@ -12,6 +12,7 @@
 	<classpathentry kind="lib" path="libs/org.restlet.ext.servlet.jar"/>
 	<classpathentry kind="lib" path="libs/org.json.jar"/>
 	<classpathentry kind="lib" path="libs/org.restlet.ext.json.jar"/>
+	<classpathentry kind="lib" path="libs/org.restlet.ext.jaas.jar"/>
 	<classpathentry combineaccessrules="false" kind="src" path="/MetaDataManager"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
 	<classpathentry combineaccessrules="false" kind="src" path="/NamedIdentityManager">
--- a/.settings/org.eclipse.wst.common.component	Thu Dec 29 15:19:29 2011 +0100
+++ b/.settings/org.eclipse.wst.common.component	Mon Jan 02 12:42:28 2012 +0100
@@ -12,9 +12,6 @@
         <dependent-module archiveName="xercesImpl-2.9.1.jar" deploy-path="/WEB-INF/lib" handle="module:/classpath/lib//Applications/eXist/lib/endorsed/xercesImpl-2.9.1.jar">
             <dependency-type>uses</dependency-type>
         </dependent-module>
-        <dependent-module archiveName="protege-owl.jar" deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/MetaDataManagerRestlet/libs/protege-owl.jar">
-            <dependency-type>uses</dependency-type>
-        </dependent-module>
         <dependent-module archiveName="protege.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/protege/protege">
             <dependency-type>uses</dependency-type>
         </dependent-module>
@@ -135,6 +132,15 @@
         <dependent-module archiveName="TripleStoreManager.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/TripleStoreManager/TripleStoreManager">
             <dependency-type>uses</dependency-type>
         </dependent-module>
+        <dependent-module archiveName="commons-lang-2.3.jar" deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/NamedIdentityManager/libs/commons-lang-2.3.jar">
+            <dependency-type>uses</dependency-type>
+        </dependent-module>
+        <dependent-module archiveName="jena.jar" deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/NamedIdentityManager/libs/jena.jar">
+            <dependency-type>uses</dependency-type>
+        </dependent-module>
+        <dependent-module archiveName="org.restlet.ext.jaas.jar" deploy-path="/WEB-INF/lib" handle="module:/classpath/lib/MetaDataManagerRestlet/libs/org.restlet.ext.jaas.jar">
+            <dependency-type>uses</dependency-type>
+        </dependent-module>
         <property name="java-output-path" value="/MetaDaterManagerRestlet/build/classes"/>
         <property name="context-root" value="MetaDataManagerRestlet"/>
     </wb-module>
Binary file libs/org.json.jar has changed
Binary file libs/org.restlet.ext.jaas.jar has changed
Binary file libs/org.restlet.ext.json.jar has changed
--- a/src/de/mpiwg/itgroup/metaDataManagerRestlet/RestServer.java	Thu Dec 29 15:19:29 2011 +0100
+++ b/src/de/mpiwg/itgroup/metaDataManagerRestlet/RestServer.java	Mon Jan 02 12:42:28 2012 +0100
@@ -1,19 +1,33 @@
 package de.mpiwg.itgroup.metaDataManagerRestlet;
 
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.Configuration;
+
 import org.apache.log4j.BasicConfigurator;
 import org.apache.log4j.Level;
 import org.apache.log4j.Logger;
 import org.restlet.Application;
 import org.restlet.Context;
+import org.restlet.Request;
+import org.restlet.Response;
 import org.restlet.Restlet;
+import org.restlet.data.ChallengeScheme;
+import org.restlet.ext.jaas.JaasVerifier;
 import org.restlet.routing.Router;
 import org.restlet.routing.Template;
 import org.restlet.routing.TemplateRoute;
+import org.restlet.security.ChallengeAuthenticator;
+
+import com.sun.security.auth.login.ConfigFile;
 
 import de.mpiwg.itgroup.metaDataManagerRestlet.pid.PIDcreator;
 import de.mpiwg.itgroup.metaDataManagerRestlet.ui.GeneralInfo;
 import de.mpiwg.itgroup.metaDataManagerRestlet.ui.SearchPersons;
 import de.mpiwg.itgroup.metadataManager.indexMeta.server.IndexMetaProvider;
+import de.mpiwg.itgroup.nimanager.edit.Editor;
 import de.mpiwg.itgroup.nimanager.persons.PersonByNameService;
 import de.mpiwg.itgroup.nimanager.persons.PersonByIDService;
 import de.mpiwg.itgroup.nimanager.persons.PersonListService;
@@ -34,7 +48,74 @@
 		
 	}
 	
+	
+	private ChallengeAuthenticator authenticator;
+	private CallbackHandler callbackHandler;
+
+    /** Erzeuge einen Authenticator
+     * @return
+     */
+    private ChallengeAuthenticator createAuthenticator() {
+        Context context = getContext();
+        boolean optional = true;
+        ChallengeScheme challengeScheme = ChallengeScheme.HTTP_BASIC;
+        String realm = "Annotation Service";
+
+        JaasVerifier verifier = new JaasVerifier("BasicJaasAuthenticationApplication");
+        //JaasVerifier verifier = new JaasVerifier("DummyAuthentication");
+       
+        Configuration jaasConfig;
+        jaasConfig = createConfiguration();
+        
+        
+		verifier.setConfiguration(jaasConfig);
+        verifier.setUserPrincipalClassName("com.sun.security.auth.UserPrincipal");
+        
+        ChallengeAuthenticator auth = new ChallengeAuthenticator(context, optional, challengeScheme, realm, verifier) {
+            @Override
+            protected boolean authenticate(Request request, Response response) {
+                if (request.getChallengeResponse() == null) {
+                    return false;
+                } else {
+                    return super.authenticate(request, response);
+                }
+            }
+        };
+
+        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.jaas.configFilePath");
+		
+		
+		try {
+			confUri = new URI(configFilePath);
+		} catch (URISyntaxException e) {
+			e.printStackTrace();
+			confUri = null;
+		}
+		
+		jaasConfig= new ConfigFile(confUri);
+		return jaasConfig;
+	}
+	
+	
+	
+	
+	
 	public synchronized Restlet createInboundRoot(){
+		this.authenticator = createAuthenticator();
+
 		Router router = new Router(getContext());
 		
 		router.attach("/",GeneralInfo.class);
@@ -45,11 +126,38 @@
 		router.attach("/person/id/{personId}",PersonService.class);
 		router.attach("/person/id/{personId}/{graphId}",PersonService.class);
 		router.attach("/ids",PersonByIDService.class);
+		router.attach("/edit",Editor.class);
 		TemplateRoute route = router.attach("/indexMeta", IndexMetaProvider.class);
 		route.setMatchingMode(Template.MODE_STARTS_WITH);
 		
+		authenticator.setNext(router);
+	    return authenticator;
+
+
 		
-		return router;
 	}
+	
+	 /**
+	  * 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;
+	    }
+
 }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/de/mpiwg/itgroup/nimanager/edit/Editor.java	Mon Jan 02 12:42:28 2012 +0100
@@ -0,0 +1,316 @@
+package de.mpiwg.itgroup.nimanager.edit;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.apache.log4j.lf5.util.StreamUtils;
+import org.openrdf.model.Statement;
+import org.openrdf.repository.RepositoryException;
+import org.openrdf.repository.RepositoryResult;
+import org.restlet.Context;
+import org.restlet.data.ClientInfo;
+import org.restlet.data.Form;
+import org.restlet.data.MediaType;
+import org.restlet.data.Status;
+import org.restlet.engine.component.ChildContext;
+import org.restlet.representation.Representation;
+import org.restlet.representation.StringRepresentation;
+import org.restlet.resource.Get;
+import org.restlet.resource.Post;
+import org.restlet.resource.ServerResource;
+import org.restlet.security.User;
+
+import de.mpiwg.itgroup.metaDataManagerRestlet.RestServer;
+import de.mpiwg.itgroup.triplestoremanager.exceptions.TripleStoreHandlerException;
+import de.mpiwg.itgroup.triplestoremanager.owl.MetaDataHandler;
+import de.mpiwg.itgroup.triplestoremanager.owl.TripleStoreHandler;
+import de.mpiwg.itgroup.triplestoremanager.owl.TripleStoreHandler.LiteralQuadruple;
+import de.mpiwg.itgroup.triplestoremanager.owl.TripleStoreHandler.Quadruple;
+import edu.stanford.smi.protegex.owl.model.impl.DefaultRDFProperty;
+import edu.stanford.smi.protege.model.DefaultCls;
+/**
+ * @author dwinter
+ *
+ * Edit an Entity defined by OWL modell
+ */
+public class Editor extends ServerResource {
+		
+	private  String NAMED_ENTITIES_ONTOLOGIE_URL = "http://ontologies.mpiwg-berlin.mpg.de/authorities/namedIdentities";
+	private  String VIRTUOSO_PW;
+	private  String VIRTUOSO_USER;
+	private  String virtuoso_server_url;
+	private  String TRIPLE_INDEX_PATH;
+	private  Logger rl = Logger.getRootLogger();
+	private  MetaDataHandler mh;
+	private  TripleStoreHandler th;
+	private String editGraph="file:///personEdits.rdf";
+	
+	
+	public Editor (){
+		ChildContext context = (ChildContext)Context.getCurrent();
+		virtuoso_server_url = context.getParameters().getFirstValue("de.mpwig.itgroup.personSearch.virtuoso.url");
+		VIRTUOSO_PW = context.getParameters().getFirstValue("de.mpwig.itgroup.personSearch.virtuoso.pw");
+		VIRTUOSO_USER = context.getParameters().getFirstValue("de.mpwig.itgroup.personSearch.virtuoso.user");
+		rl.setLevel(Level.DEBUG);
+		try {
+			th = TripleStoreHandler.getInstance(virtuoso_server_url, VIRTUOSO_USER, VIRTUOSO_PW);
+
+			//th = new TripleStoreHandler(virtuoso_server_url, VIRTUOSO_USER, VIRTUOSO_PW);
+		} catch (TripleStoreHandlerException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
+		mh = MetaDataHandler.getInstance();
+	}
+	
+	public Editor(String serverUrl,String User, String PW){
+		virtuoso_server_url = serverUrl;
+		VIRTUOSO_PW =  PW;
+		VIRTUOSO_USER = User;
+		
+		try {
+			th = TripleStoreHandler.getInstance(virtuoso_server_url, VIRTUOSO_USER, VIRTUOSO_PW);
+			//th = new TripleStoreHandler(virtuoso_server_url, VIRTUOSO_USER, VIRTUOSO_PW);
+		} catch (TripleStoreHandlerException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
+		mh = MetaDataHandler.getInstance();
+	}
+	/**
+	 * Hole alle Properties eines Instance wie definiert in OWL.
+	 * @param instance
+	 * @return
+	 */
+	private HashMap<String, Object> getProperties(String instance, List<String> NSFilter){
+		RepositoryResult<Statement> stmts;
+		HashMap<String, Object> retMap = new HashMap<String, Object>();
+		try {
+			stmts= th.getStatements(instance, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", null); 
+		} catch (RepositoryException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+			return null;
+		}
+		try {
+			while(stmts.hasNext()){
+				Statement stmt = stmts.next();
+				addPropsOfType(retMap,stmt.getObject().stringValue(),instance, NSFilter);
+			}
+		} catch (RepositoryException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+			return null;
+		}
+		
+		
+		return retMap;
+	}
+	private void addPropsOfType(HashMap<String, Object> retMap,
+			String cls, String instance, List<String> NSfilter) {
+		
+//		Set props = mh.getAssociatedPropsForClass(cls);
+//		Iterator propsIt = props.iterator();
+//		while (propsIt.hasNext()){
+//			Object prop = propsIt.next();
+//			
+//			
+//		}
+		Collection props = mh.getAssociatedPropsForClass(cls);
+	
+		// filter namespaces
+		if (NSfilter!=null){
+			
+		Object[] propsCopy = props.toArray();
+		for (Object prop:propsCopy){
+			if (DefaultRDFProperty.class.isInstance(prop)){
+				DefaultRDFProperty rdfProp = (DefaultRDFProperty)prop;
+				rl.debug(rdfProp.getNamespace());
+				if (!NSfilter.contains(rdfProp.getNamespace())){ // nicht im filter
+						props.remove(prop);
+				}
+		}
+		}
+		}
+	
+		Map<String, Object> newProps;
+		try {
+			newProps = th.getJenaRDFValues(props, instance, mh.getOwlModel(),true);
+		} catch (RepositoryException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+			return;
+		}
+		
+		retMap.putAll(newProps);
+		
+		
+	}
+	
+	@Post
+	public Representation postHTML(Representation entity){
+		User user = handleBasicAuthentification(entity);
+		if (user==null){
+			setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
+			return null;
+		}
+		
+		Form form = new Form(entity);
+		
+		String id = form.getFirstValue("id");
+		if (id==null){
+			setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
+			return new StringRepresentation("Parameter ID missing");
+		}
+		
+		String type = form.getFirstValue("type");
+		if (type==null){
+			setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
+			return new StringRepresentation("Parameter type missing");
+		}
+
+		
+		ArrayList<Quadruple> quads = new ArrayList<Quadruple>();
+		ArrayList<Quadruple> deleteQuads = new ArrayList<Quadruple>();
+		Map<String,String> formMap = form.getValuesMap();
+		for (String key: formMap.keySet()){
+			if (isDataTypeProperty(key,type)){
+				String value=formMap.get(key);
+				
+				//remove white space
+				value=StringUtils.stripEnd(value, null);
+				value=StringUtils.stripStart(value, null);
+				
+				if (value!=null && !value.equals("")){ //not empty
+					deleteQuads.add(new LiteralQuadruple(id, key, null, editGraph));
+					quads.add(new LiteralQuadruple(id, key, formMap.get(key), editGraph));
+				}
+			}
+		}
+		try {
+			th.remove(deleteQuads);
+			th.write(quads);
+		} catch (RepositoryException e) {
+			setStatus(Status.SERVER_ERROR_INTERNAL);
+			e.printStackTrace();
+			return null;
+		} catch (TripleStoreHandlerException e) {
+			setStatus(Status.SERVER_ERROR_INTERNAL);
+			e.printStackTrace();
+			return null;
+		}
+		
+		return new StringRepresentation("written");
+		
+	}
+	
+	/**
+	 * Checks if the 
+	 * @param key
+	 * @param value 
+	 * @return
+	 */
+	private boolean isDataTypeProperty(String key,String type) {
+		
+	
+		Collection props = mh.getAssociatedPropsForClass(type);
+		
+			
+		Object[] propsCopy = props.toArray();
+		for (Object prop:propsCopy){
+			if (DefaultRDFProperty.class.isInstance(prop)){
+				DefaultRDFProperty rdfProp = (DefaultRDFProperty)prop;
+				rl.debug(rdfProp.getNamespace());
+				if (rdfProp.getName().equals(key)){
+					rl.debug(rdfProp);
+					return true;
+				}
+			}
+		}
+		return false;
+	}
+	
+
+	@Get("html")
+	public Representation getHTML(Representation entity){
+		Form form = getRequest().getResourceRef().getQueryAsForm();
+		
+		
+		String id  =form.getValuesMap().get("id");			
+		try {
+			id = URLDecoder.decode(id, "utf-8");
+		} catch (UnsupportedEncodingException e) {
+			e.printStackTrace();
+			e.printStackTrace();
+			setStatus(Status.SERVER_ERROR_INTERNAL, "REPOSITORY ERROR");
+			return new StringRepresentation(
+					"<xml><error>Unsupported encoding</error></xml>",
+					MediaType.TEXT_HTML);
+			
+		}
+		id=StringUtils.stripEnd(id, null);
+		id=StringUtils.stripStart(id, null);
+		
+		ArrayList<String> NSFilter = new ArrayList<String>();
+		NSFilter.add("http://xmlns.com/foaf/0.1/"); // only foaf
+		HashMap<String, Object> props = getProperties(id, NSFilter);
+		
+		
+		ArrayList<String> NSFilterRDF = new ArrayList<String>();
+		NSFilterRDF.add("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); // only foaf
+		HashMap<String, Object> propsRDF = getProperties(id, NSFilterRDF);
+		
+		String RDFtype = ((DefaultCls)(propsRDF.get("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"))).getName();
+	
+		
+		String retString="<html><body><form method=\"post\" class=\"editEntity\">";
+		retString+=String.format("<input type=\"hidden\" name=\"id\" value=\"%s\" len=\"50\">", id);
+		retString+=String.format("<input type=\"hidden\" name=\"type\" value=\"%s\" len=\"50\">", RDFtype);
+		for (String prop: props.keySet()){
+			
+			retString+=String.format("<div class=\"labelEntity\">%s<input type=\"text\" name=\"%s\" value=\"%s\" len=\"50\"></div>", 
+					prop,prop,String.valueOf(props.get(prop)));
+		}
+		
+		retString+="<input type=\"submit\"/>";
+		retString+="</form></body></html>";
+		return new StringRepresentation(retString,MediaType.TEXT_HTML);
+		
+	}
+	
+	
+	private User handleBasicAuthentification(Representation entity) {
+		RestServer restServer = (RestServer) getApplication();
+		if (!restServer.authenticate(getRequest(), getResponse())) {
+			// Not authenticated
+			return null;
+		}
+
+		ClientInfo ci = getRequest().getClientInfo();
+		rl.debug(ci);
+		return getRequest().getClientInfo().getUser();
+
+	}
+	
+	public static void main(String args[]) {
+		Logger.getRootLogger().setLevel(Level.DEBUG);
+		Editor ed = new Editor("jdbc:virtuoso://virtuoso.mpiwg-berlin.mpg.de:1111","dba","wa55er");
+		ArrayList<String> NSFilter = new ArrayList<String>();
+		NSFilter.add("http://xmlns.com/foaf/0.1/"); // only foaf
+		HashMap<String, Object> props = ed.getProperties("http://ontologies.mpiwg-berlin.mpg.de/tempObjects/person/370868",NSFilter);
+		System.out.println(props);
+		
+	}
+}