diff src/de/mpiwg/itgroup/annotationManager/RDFHandling/RDFSearcher.java @ 17:b0ef5c860464

updating and deleting annotations works now! more cleanup.
author casties
date Thu, 22 Mar 2012 21:37:16 +0100
parents 667d98fd28bd
children
line wrap: on
line diff
--- a/src/de/mpiwg/itgroup/annotationManager/RDFHandling/RDFSearcher.java	Thu Mar 22 10:54:56 2012 +0100
+++ b/src/de/mpiwg/itgroup/annotationManager/RDFHandling/RDFSearcher.java	Thu Mar 22 21:37:16 2012 +0100
@@ -6,212 +6,184 @@
 import org.apache.log4j.Logger;
 import org.openrdf.query.BindingSet;
 import org.openrdf.query.TupleQueryResult;
-import org.restlet.Context;
-import org.restlet.engine.component.ChildContext;
 
 import de.mpiwg.itgroup.annotationManager.Errors.TripleStoreSearchError;
-import de.mpiwg.itgroup.annotationManager.Errors.TripleStoreStoreError;
-import de.mpiwg.itgroup.annotationManager.RDFHandling.Convert.Annotation;
 import de.mpiwg.itgroup.triplestoremanager.exceptions.TripleStoreHandlerException;
 import de.mpiwg.itgroup.triplestoremanager.owl.TripleStoreHandler;
 
 public class RDFSearcher {
 
-	private String urlBase="http://ontologies.mpiwg-berlin.mpg.de/annotations/"; //TODO should go into config
-
-	private TripleStoreHandler th;
+    private String urlBase = "http://ontologies.mpiwg-berlin.mpg.de/annotations/"; // TODO should go into config
 
-	private String context;
-
-	private Logger logger= Logger.getRootLogger();
+    private String context;
 
-	public RDFSearcher(String context) {
-		this.context=context;
-	}
-
-
+    private Logger logger = Logger.getRootLogger();
 
-        /** Sucht im Triplestore nach Annotationen.
-         * 
-         * @param id id der Annotation
-         * @return
-         * @throws TripleStoreHandlerException
-         * @throws TripleStoreSearchError
-         */
-        public List<Annotation> searchById(String id) throws TripleStoreHandlerException, TripleStoreSearchError {
+    public RDFSearcher(String context) {
+        this.context = context;
+    }
 
-                List<Annotation> retAnnots = new ArrayList<Convert.Annotation>();
-                ChildContext context = (ChildContext)Context.getCurrent();
-                String tripleStoreUser = context.getParameters().getFirstValue("de.mpiwg.itgroup.annotationManager.virtuoso.tripleStoreUser");
-                String tripleStorePW = context.getParameters().getFirstValue("de.mpiwg.itgroup.annotationManager.virtuoso.tripleStoreUserPassword");
-                String connectionURL = context.getParameters().getFirstValue("de.mpiwg.itgroup.annotationManager.virtuoso.tripleStoreConnectionURL");
-                if (tripleStoreUser == null || tripleStorePW == null || connectionURL == null) {
-                    logger.error(String.format("Missing triplestore parameters! (user=%s pw=%s url=%s)", tripleStoreUser, tripleStorePW, connectionURL));
-                    throw new TripleStoreStoreError();
-                }
-                
-                th = new TripleStoreHandler(connectionURL, tripleStoreUser, tripleStorePW);
-                String queryString="";
+    /**
+     * Sucht im Triplestore nach Annotationen.
+     * 
+     * @param id
+     *            id der Annotation
+     * @return
+     * @throws TripleStoreHandlerException
+     * @throws TripleStoreSearchError
+     */
+    public List<Annotation> searchById(String id) throws TripleStoreHandlerException, TripleStoreSearchError {
+        if (id == null) {
+            return null;
+        }
+        List<Annotation> retAnnots = new ArrayList<Annotation>();
+        TripleStoreHandler th = TripleStoreConnection.newTripleStoreHandler();
+        String queryString = "";
+        // query for tuples with id as subject
+        StringBuilder whereString = new StringBuilder(String.format("<%s> ?p <http://www.w3.org/2000/10/annotationType#Comment>.", id));
+        whereString.append(String.format("<%s> <http://ontologies.mpiwg-berlin.mpg.de/annotations/annotatesDocuviewerText> ?uri.", id));
+        whereString.append(String.format("<%s> <http://ontologies.mpiwg-berlin.mpg.de/annotations/textSelection> ?xpointer.", id));
+        whereString.append(String.format("<%s> <http://www.w3.org/2000/10/annotation-ns#body> ?annotText.", id));
+        whereString.append(String.format("<%s> <http://www.w3.org/2000/10/annotation-ns#author> ?author.", id));
+        whereString.append(String.format("<%s> <http://www.w3.org/2000/10/annotation-ns#created> ?created.", id));
+        whereString.append(" OPTIONAL {?annotText <http://ontologies.mpiwg-berlin.mpg.de/annotations/containsText> ?text.}");
 
-                String whereString = "?s ?p <http://www.w3.org/2000/10/annotationType#Comment>.";
-                //whereString +="?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/docuviewerText> ?link.";
-/*                String uri = null;
-                if(uri!=null && !uri.equals("")){
-                        whereString +=String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/annotatesDocuviewerText> <%s>.",uri);}
-                else { */
-                        whereString +=String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/annotatesDocuviewerText> ?uri.");
-//                }       
+        queryString = String.format("select distinct * where {%s}", whereString);
 
-                whereString +=String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/textSelection> ?xpointer.");
-                whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#body> ?annotText.");
+        logger.debug("RDFSearcher:" + queryString);
 
-/*                String user = null;
-                if(user!=null && !user.equals("")){
-                        if (user.startsWith("http")){
-                                whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> <%s>.",user);  
-                        } else {
-                                whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> \"%s\".",user);
-                        }
-                } else { */
-                        whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> ?author.");
-//                }
-
-                whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#created> ?created.");
-
-                whereString +=String.format(" OPTIONAL {?annotText <http://ontologies.mpiwg-berlin.mpg.de/annotations/containsText> ?text.}");
-
-                queryString=String.format("select distinct * where {%s}",whereString);
-
-                
-                logger.debug("RDFSearcher:"+queryString);
-
-                try {
-                        TupleQueryResult results = th.querySPARQL(queryString);
+        try {
+            TupleQueryResult results = th.querySPARQL(queryString);
+            while (results.hasNext()) {
+                BindingSet result = results.next();
+                String annotUri = result.getBinding("uri").getValue().stringValue();
+                String annotUser = result.getBinding("author").getValue().stringValue();
+                String textString = "";
+                if (result.getBinding("text") != null) {
+                    textString = result.getBinding("text").getValue().stringValue();
+                }
+      
+                String xpointer = result.getBinding("xpointer").getValue().stringValue();
+                String created = result
+                        .getBinding("created").getValue().stringValue();
+                Annotation annot = new Annotation(xpointer, annotUser, created, textString, null, annotUri, id);
+                retAnnots.add(annot);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new TripleStoreSearchError();
+        }
+        // TODO Auto-generated method stub
+        return retAnnots;
+    }
 
-                        while (results.hasNext()) {
-                                BindingSet result = results.next();
-                                String annotUri;
-                                if(uri!=null && !uri.equals("")){
-                                        annotUri=uri;
-                                } else {
-                                        annotUri = result.getBinding("uri").getValue().stringValue();
-                                }
-                                
-                                String annotUser;
-                                if(user!=null && !user.equals("")){
-                                        annotUser=user;
-                                } else {
-                                        annotUser = result.getBinding("author").getValue().stringValue();
-                                }
-                                
-                                String textString="";
-                                if (result.getBinding("text")!=null){
-                                        textString= result.getBinding("text").getValue().stringValue();
-                                }
-                                Annotation annot = new Annotation(result.getBinding("xpointer").getValue().stringValue(), 
-                                                annotUser, result.getBinding("created").getValue().stringValue(), 
-                                                textString, null,
-                                                annotUri,result.getBinding("s").getValue().stringValue());
-                                retAnnots.add(annot);
-                        }
-                } catch (Exception e) {
-                        e.printStackTrace();
-                        throw new TripleStoreSearchError();
-                }
-                // TODO Auto-generated method stub
-                return retAnnots;
+    /**
+     * Sucht im Triplestore nach Annotationen
+     * 
+     * @param uri
+     *            Adresse der Annotierten Ressource, in der Regel nicht mit dem xpointer, sonder die URI der kompletten Ressource
+     *            oder NULL oder leer
+     * @param user
+     *            Author der Annotationen, entweder als uri der Person oder ein Username, je nachdem wie die Annotatinen angelegt
+     *            wurden.
+     * @param limit
+     * @param offset
+     * @return
+     * @throws TripleStoreHandlerException
+     * @throws TripleStoreSearchError
+     */
+    public List<Annotation> searchByUriUser(String uri, String user, String limit, String offset)
+            throws TripleStoreHandlerException, TripleStoreSearchError {
+
+        List<Annotation> retAnnots = new ArrayList<Annotation>();
+        TripleStoreHandler th = TripleStoreConnection.newTripleStoreHandler();
+        String queryString = "";
+
+        String whereString = "?s ?p <http://www.w3.org/2000/10/annotationType#Comment>.";
+        // whereString +="?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/docuviewerText> ?link.";
+
+        if (uri != null && !uri.equals("")) {
+            whereString += String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/annotatesDocuviewerText> <%s>.",
+                    uri);
+        } else {
+            whereString += String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/annotatesDocuviewerText> ?uri.");
+        }
+        whereString += String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/textSelection> ?xpointer.");
+        whereString += String.format("?s <http://www.w3.org/2000/10/annotation-ns#body> ?annotText.");
+
+        if (user != null && !user.equals("")) {
+            if (user.startsWith("http")) {
+                whereString += String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> <%s>.", user);
+            } else {
+                whereString += String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> \"%s\".", user);
+            }
+        } else {
+            whereString += String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> ?author.");
         }
 
-        /** Sucht im Triplestore nach Annotationen
-	 * @param uri Adresse der Annotierten Ressource, in der Regel nicht mit dem xpointer, sonder die URI der kompletten Ressource oder NULL oder leer
-	 * @param user Author der Annotationen, entweder als uri der Person oder ein Username, je nachdem wie die Annotatinen angelegt wurden.
-	 * @param limit
-	 * @param offset
-	 * @return
-	 * @throws TripleStoreHandlerException
-	 * @throws TripleStoreSearchError
-	 */
-	public List<Annotation> searchByUriUser(String uri, String user, String limit,
-			String offset) throws TripleStoreHandlerException, TripleStoreSearchError {
+        whereString += String.format("?s <http://www.w3.org/2000/10/annotation-ns#created> ?created.");
+
+        whereString += String
+                .format(" OPTIONAL {?annotText <http://ontologies.mpiwg-berlin.mpg.de/annotations/containsText> ?text.}");
+
+        queryString = String.format("select distinct * where {%s}", whereString);
+
+        logger.debug("RDFSearcher:" + queryString);
 
-		List<Annotation> retAnnots = new ArrayList<Convert.Annotation>();
-		ChildContext context = (ChildContext)Context.getCurrent();
-		String tripleStoreUser = context.getParameters().getFirstValue("de.mpiwg.itgroup.annotationManager.virtuoso.tripleStoreUser");
-		String tripleStorePW = context.getParameters().getFirstValue("de.mpiwg.itgroup.annotationManager.virtuoso.tripleStoreUserPassword");
-                String connectionURL = context.getParameters().getFirstValue("de.mpiwg.itgroup.annotationManager.virtuoso.tripleStoreConnectionURL");
-                if (tripleStoreUser == null || tripleStorePW == null || connectionURL == null) {
-                    logger.error(String.format("Missing triplestore parameters! (user=%s pw=%s url=%s)", tripleStoreUser, tripleStorePW, connectionURL));
-                    throw new TripleStoreStoreError();
+        try {
+            TupleQueryResult results = th.querySPARQL(queryString);
+
+            while (results.hasNext()) {
+                BindingSet result = results.next();
+                String annotUri;
+                if (uri != null && !uri.equals("")) {
+                    annotUri = uri;
+                } else {
+                    annotUri = result.getBinding("uri").getValue().stringValue();
                 }
-		
-		th = new TripleStoreHandler(connectionURL, tripleStoreUser, tripleStorePW);
-		String queryString="";
 
-		String whereString = "?s ?p <http://www.w3.org/2000/10/annotationType#Comment>.";
-		//whereString +="?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/docuviewerText> ?link.";
-
-		if(uri!=null && !uri.equals("")){
-			whereString +=String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/annotatesDocuviewerText> <%s>.",uri);}
-		else {
-			whereString +=String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/annotatesDocuviewerText> ?uri.");
-		}	
-		whereString +=String.format("?s <http://ontologies.mpiwg-berlin.mpg.de/annotations/textSelection> ?xpointer.");
-		whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#body> ?annotText.");
-
-		if(user!=null && !user.equals("")){
-			if (user.startsWith("http")){
-				whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> <%s>.",user);	
-			} else {
-				whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> \"%s\".",user);
-			}
-		} else {
-			whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#author> ?author.");
-		}
+                String annotUser;
+                if (user != null && !user.equals("")) {
+                    annotUser = user;
+                } else {
+                    annotUser = result.getBinding("author").getValue().stringValue();
+                }
 
-		whereString +=String.format("?s <http://www.w3.org/2000/10/annotation-ns#created> ?created.");
-
-		whereString +=String.format(" OPTIONAL {?annotText <http://ontologies.mpiwg-berlin.mpg.de/annotations/containsText> ?text.}");
-
-		queryString=String.format("select distinct * where {%s}",whereString);
-
-		
-		logger.debug("RDFSearcher:"+queryString);
-
-		try {
-			TupleQueryResult results = th.querySPARQL(queryString);
+                String textString = "";
+                if (result.getBinding("text") != null) {
+                    textString = result.getBinding("text").getValue().stringValue();
+                }
+                Annotation annot = new Annotation(result.getBinding("xpointer").getValue().stringValue(), annotUser, result
+                        .getBinding("created").getValue().stringValue(), textString, null, annotUri, result.getBinding("s")
+                        .getValue().stringValue());
+                retAnnots.add(annot);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new TripleStoreSearchError();
+        }
+        // TODO Auto-generated method stub
+        return retAnnots;
+    }
 
-			while (results.hasNext()) {
-				BindingSet result = results.next();
-				String annotUri;
-				if(uri!=null && !uri.equals("")){
-					annotUri=uri;
-				} else {
-					annotUri = result.getBinding("uri").getValue().stringValue();
-				}
-				
-				String annotUser;
-				if(user!=null && !user.equals("")){
-					annotUser=user;
-				} else {
-					annotUser = result.getBinding("author").getValue().stringValue();
-				}
-				
-				String textString="";
-				if (result.getBinding("text")!=null){
-					textString= result.getBinding("text").getValue().stringValue();
-				}
-				Annotation annot = new Annotation(result.getBinding("xpointer").getValue().stringValue(), 
-						annotUser, result.getBinding("created").getValue().stringValue(), 
-						textString, null,
-						annotUri,result.getBinding("s").getValue().stringValue());
-				retAnnots.add(annot);
-			}
-		} catch (Exception e) {
-			e.printStackTrace();
-			throw new TripleStoreSearchError();
-		}
-		// TODO Auto-generated method stub
-		return retAnnots;
-	}
+    public void deleteById(String id) throws TripleStoreHandlerException, TripleStoreSearchError {
+        if (id == null) {
+            return;
+        }
+        TripleStoreHandler th = TripleStoreConnection.newTripleStoreHandler();
+        // delete triples with id as subject
+        /* wish Virtuoso would speak SparQL1.1...
+        String queryString = String.format("WITH <%s> DELETE { <%s> ?p ?o } WHERE { <%s> ?p ?o }", context, id, id);
+        */
+        String queryString = String.format("DELETE FROM <%s> { <%s> ?p ?o } WHERE { <%s> ?p ?o }", context, id, id);
 
+        logger.debug("RDFSearcher:" + queryString);
+
+        try {
+            th.querySPARQL(queryString);
+       } catch (Exception e) {
+            e.printStackTrace();
+            throw new TripleStoreSearchError();
+        }
+    }
 }