diff src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorResourceImpl.java @ 4:3599b29c393f

store seems to work now :-)
author casties
date Mon, 02 Jul 2012 22:39:46 +0200
parents 47b53ae385d1
children bbf0cc5bee29
line wrap: on
line diff
--- a/src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorResourceImpl.java	Fri Jun 29 20:38:27 2012 +0200
+++ b/src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorResourceImpl.java	Mon Jul 02 22:39:46 2012 +0200
@@ -13,6 +13,8 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import javax.servlet.ServletContext;
+
 import net.oauth.jsontoken.Checker;
 import net.oauth.jsontoken.JsonToken;
 import net.oauth.jsontoken.JsonTokenParser;
@@ -25,16 +27,16 @@
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
-import org.restlet.data.ClientInfo;
 import org.restlet.data.Form;
 import org.restlet.data.Status;
 import org.restlet.representation.Representation;
 import org.restlet.resource.Options;
 import org.restlet.resource.ServerResource;
-import org.restlet.security.User;
 
-import de.mpiwg.itgroup.annotationManager.Constants.NS;
-import de.mpiwg.itgroup.annotationManager.RDFHandling.Annotation;
+import de.mpiwg.itgroup.annotations.Annotation;
+import de.mpiwg.itgroup.annotations.Annotation.FragmentTypes;
+import de.mpiwg.itgroup.annotations.neo4j.AnnotationStore;
+import de.mpiwg.itgroup.annotations.old.NS;
 
 /**
  * Base class for Annotator resource classes.
@@ -44,12 +46,24 @@
  */
 public abstract class AnnotatorResourceImpl extends ServerResource {
 
-    protected Logger logger = Logger.getRootLogger();
+    protected static Logger logger = Logger.getLogger(AnnotatorResourceImpl.class);
+
+    private AnnotationStore store;
 
     protected String getAllowedMethodsForHeader() {
         return "OPTIONS,GET,POST";
     }
 
+    protected AnnotationStore getAnnotationStore() {
+        if (store == null) {
+            ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes()
+                    .get("org.restlet.ext.servlet.ServletContext");
+            logger.debug("Getting AnnotationStore from Context");
+            store = (AnnotationStore) sc.getAttribute(RestServer.ANNSTORE_KEY);
+        }
+        return store;
+    }
+
     public String encodeJsonId(String id) {
         try {
             return Base64.encodeBase64URLSafeString(id.getBytes("UTF-8"));
@@ -114,7 +128,8 @@
     }
 
     /**
-     * checks Annotator Auth plugin authentication information from headers. returns userId if successful.
+     * checks Annotator Auth plugin authentication information from headers.
+     * returns userId if successful.
      * 
      * @param entity
      * @return
@@ -165,52 +180,46 @@
         boolean makeUserObject = true;
         JSONObject jo = new JSONObject();
         try {
-            jo.put("text", annot.text);
-            jo.put("uri", annot.url);
+            jo.put("text", annot.getBodyText());
+            jo.put("uri", annot.getTargetBaseUri());
 
             if (makeUserObject) {
                 // create user object
                 JSONObject userObject = new JSONObject();
                 // save creator as uri
-                userObject.put("uri", annot.creator);
+                userObject.put("uri", annot.getCreatorUri());
                 // make short user id
-                String userID = annot.creator;
-                if (userID.startsWith(NS.MPIWG_PERSONS_URL)) {
-                    userID = userID.replace(NS.MPIWG_PERSONS_URL, ""); // entferne
+                String userId = annot.getCreatorUri();
+                if (userId != null && userId.startsWith(NS.MPIWG_PERSONS_URL)) {
+                    userId = userId.replace(NS.MPIWG_PERSONS_URL, ""); // entferne
                                                                        // NAMESPACE
                 }
                 // save as id
-                userObject.put("id", userID);
+                userObject.put("id", userId);
                 // get full name
                 RestServer restServer = (RestServer) getApplication();
-                String userName = restServer.getUserNameFromLdap(userID);
+                String userName = restServer.getUserNameFromLdap(userId);
                 userObject.put("name", userName);
                 // save user object
                 jo.put("user", userObject);
             } else {
                 // save user as string
-                jo.put("user", annot.creator);
+                jo.put("user", annot.getCreatorUri());
             }
 
-            List<String> xpointers = new ArrayList<String>();
-            if (annot.xpointers == null || annot.xpointers.size() == 0)
-                xpointers.add(annot.xpointer);
-            else {
-                for (String xpointerString : annot.xpointers) {
-                    xpointers.add(xpointerString);
-                }
-            }
-            if (!xpointers.isEmpty()) {
+            if (annot.getTargetFragment() != null) {
                 // we only look at the first xpointer
-                String xt = getXpointerType(xpointers.get(0));
-                if (xt == "range") {
-                    jo.put("ranges", transformToRanges(xpointers));
-                } else if (xt == "area") {
-                    jo.put("areas", transformToAreas(xpointers));
+                List<String> fragments = new ArrayList<String>();
+                fragments.add(annot.getTargetFragment());
+                FragmentTypes xt = annot.getFragmentType();
+                if (xt == FragmentTypes.XPOINTER) {
+                    jo.put("ranges", transformToRanges(fragments));
+                } else if (xt == FragmentTypes.AREA) {
+                    jo.put("areas", transformToAreas(fragments));
                 }
             }
             // encode Annotation URL (=id) in base64
-            String annotUrl = annot.getAnnotationUri();
+            String annotUrl = annot.getUri();
             String annotId = encodeJsonId(annotUrl);
             jo.put("id", annotId);
             return jo;
@@ -221,22 +230,13 @@
         return null;
     }
 
-    private String getXpointerType(String xpointer) {
-        if (xpointer.contains("#xpointer")) {
-            return "range";
-        } else if (xpointer.contains("#xywh")) {
-            return "area";
-        }
-        return null;
-    }
-
     private JSONArray transformToRanges(List<String> xpointers) {
 
         JSONArray ja = new JSONArray();
 
         Pattern rg = Pattern
-                .compile("#xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)/range-to\\(end-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)\\)");
-        Pattern rg1 = Pattern.compile("#xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)");
+                .compile("xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)/range-to\\(end-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)\\)");
+        Pattern rg1 = Pattern.compile("xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)");
 
         try {
             for (String xpointer : xpointers) {
@@ -277,7 +277,7 @@
 
         JSONArray ja = new JSONArray();
 
-        Pattern rg = Pattern.compile("#xywh=(\\w*:)([\\d\\.]+),([\\d\\.]+),([\\d\\.]+),([\\d\\.]+)");
+        Pattern rg = Pattern.compile("xywh=(\\w*:)([\\d\\.]+),([\\d\\.]+),([\\d\\.]+),([\\d\\.]+)");
 
         try {
             for (String xpointer : xpointers) {
@@ -307,47 +307,76 @@
         return ja;
     }
 
+    protected String parseArea(JSONObject area) throws JSONException, UnsupportedEncodingException {
+        String x = area.getString("x");
+        String y = area.getString("y");
+        String width = "0";
+        String height = "0";
+        if (area.has("width")) {
+            width = area.getString("width");
+            height = area.getString("height");
+        }
+        String fragment = URLEncoder.encode(String.format("xywh=fraction:%s,%s,%s,%s", x, y, width, height), "utf-8");
+        return fragment;
+    }
+
+    protected String parseRange(JSONObject range) throws JSONException, UnsupportedEncodingException {
+        String start = range.getString("start");
+        String end = range.getString("end");
+        String startOffset = range.getString("startOffset");
+        String endOffset = range.getString("endOffset");
+
+        String fragment = URLEncoder.encode(String.format(
+                "xpointer(start-point(string-range(\"%s\",%s,1))/range-to(end-point(string-range(\"%s\",%s,1))))", start,
+                startOffset, end, endOffset), "utf-8");
+        return fragment;
+    }
+
     /**
      * creates an Annotation object with data from JSON.
      * 
-     * uses the specification from the annotator project: {@link https ://github.com/okfn/annotator/wiki/Annotation-format}
+     * uses the specification from the annotator project: {@link https
+     * ://github.com/okfn/annotator/wiki/Annotation-format}
      * 
-     * The username will be transformed to an URI if not given already as URI, if not it will set to the MPIWG namespace defined in
+     * The username will be transformed to an URI if not given already as URI,
+     * if not it will set to the MPIWG namespace defined in
      * de.mpiwg.itgroup.annotationManager.Constants.NS
      * 
      * @param jo
      * @return
      * @throws JSONException
+     * @throws UnsupportedEncodingException
      */
-    public Annotation createAnnotation(JSONObject jo, Representation entity) throws JSONException {
+    public Annotation createAnnotation(JSONObject jo, Representation entity) throws JSONException, UnsupportedEncodingException {
         return updateAnnotation(new Annotation(), jo, entity);
     }
 
-    public Annotation updateAnnotation(Annotation annot, JSONObject jo, Representation entity) throws JSONException {
+    public Annotation updateAnnotation(Annotation annot, JSONObject jo, Representation entity) throws JSONException,
+            UnsupportedEncodingException {
         // annotated uri
-        String url = annot.url;
         if (jo.has("uri")) {
-            url = jo.getString("uri");
+            annot.setTargetBaseUri(jo.getString("uri"));
         }
         // annotation text
-        String text = annot.text;
         if (jo.has("text")) {
-            text = jo.getString("text");
+            annot.setBodyText(jo.getString("text"));
         }
         // check authentication
         String authUser = checkAuthToken(entity);
         if (authUser == null) {
-            // try http auth
-            User httpUser = getHttpAuthUser(entity);
-            if (httpUser == null) {
-                setStatus(Status.CLIENT_ERROR_FORBIDDEN);
-                return null;
-            }
-            authUser = httpUser.getIdentifier();
+            /*
+             * // try http auth User httpUser = getHttpAuthUser(entity); if
+             * (httpUser == null) {
+             */
+            setStatus(Status.CLIENT_ERROR_FORBIDDEN);
+            return null;
+            /*
+             * } authUser = httpUser.getIdentifier();
+             */
         }
         // username not required, if no username given authuser will be used
         String username = null;
-        String userUri = annot.creator;
+        String userUri = annot.getCreatorUri();
         if (jo.has("user")) {
             if (jo.get("user") instanceof String) {
                 // user is just a String
@@ -380,64 +409,19 @@
         // TODO: should we overwrite the creator?
 
         // create xpointer from the first range/area
-        String xpointer = annot.xpointer;
         if (jo.has("ranges")) {
             JSONObject ranges = jo.getJSONArray("ranges").getJSONObject(0);
-            String start = ranges.getString("start");
-            String end = ranges.getString("end");
-            String startOffset = ranges.getString("startOffset");
-            String endOffset = ranges.getString("endOffset");
-
-            try {
-                xpointer = url
-                        + "#"
-                        + URLEncoder.encode(String.format(
-                                "xpointer(start-point(string-range(\"%s\",%s,1))/range-to(end-point(string-range(\"%s\",%s,1))))",
-                                start, startOffset, end, endOffset), "utf-8");
-            } catch (UnsupportedEncodingException e) {
-                e.printStackTrace();
-                setStatus(Status.SERVER_ERROR_INTERNAL);
-                return null;
-            }
+            annot.setFragmentType(FragmentTypes.XPOINTER);
+            String fragment = parseRange(ranges);
+            annot.setTargetFragment(fragment);
         }
         if (jo.has("areas")) {
             JSONObject area = jo.getJSONArray("areas").getJSONObject(0);
-            String x = area.getString("x");
-            String y = area.getString("y");
-            String width = "0";
-            String height = "0";
-            if (area.has("width")) {
-                width = area.getString("width");
-                height = area.getString("height");
-            }
-            try {
-                xpointer = url + "#" + URLEncoder.encode(String.format("xywh=fraction:%s,%s,%s,%s", x, y, width, height), "utf-8");
-            } catch (UnsupportedEncodingException e) {
-                e.printStackTrace();
-                setStatus(Status.SERVER_ERROR_INTERNAL);
-                return null;
-            }
+            annot.setFragmentType(FragmentTypes.AREA);
+            String fragment = parseArea(area);
+            annot.setTargetFragment(fragment);
         }
-        return new Annotation(xpointer, userUri, annot.time, text, annot.type);
-    }
-
-    /**
-     * returns the logged in User.
-     * 
-     * @param entity
-     * @return
-     */
-    protected User getHttpAuthUser(Representation entity) {
-        RestServer restServer = (RestServer) getApplication();
-        if (!restServer.authenticate(getRequest(), getResponse())) {
-            // Not authenticated
-            return null;
-        }
-
-        ClientInfo ci = getRequest().getClientInfo();
-        logger.debug(ci);
-        return getRequest().getClientInfo().getUser();
-
+        return annot;
     }
 
 }