source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorResourceImpl.java @ 40:03e0f7574224

Last change on this file since 40:03e0f7574224 was 40:03e0f7574224, checked in by casties, 12 years ago

saving and loading resource targets should work now (no searching yet)

File size: 21.5 KB
Line 
1/**
2 * Base class for Annotator resource classes.
3 */
4package de.mpiwg.itgroup.annotations.restlet;
5
6import java.io.UnsupportedEncodingException;
7import java.security.InvalidKeyException;
8import java.security.SignatureException;
9import java.text.SimpleDateFormat;
10import java.util.ArrayList;
11import java.util.Calendar;
12import java.util.HashSet;
13import java.util.List;
14import java.util.Set;
15import java.util.regex.Matcher;
16import java.util.regex.Pattern;
17
18import net.oauth.jsontoken.Checker;
19import net.oauth.jsontoken.JsonToken;
20import net.oauth.jsontoken.JsonTokenParser;
21import net.oauth.jsontoken.SystemClock;
22import net.oauth.jsontoken.crypto.HmacSHA256Verifier;
23import net.oauth.jsontoken.crypto.Verifier;
24
25import org.apache.commons.codec.binary.Base64;
26import org.apache.log4j.Logger;
27import org.json.JSONArray;
28import org.json.JSONException;
29import org.json.JSONObject;
30import org.restlet.data.Form;
31import org.restlet.data.Status;
32import org.restlet.representation.Representation;
33import org.restlet.resource.Options;
34import org.restlet.resource.ServerResource;
35
36import de.mpiwg.itgroup.annotations.Actor;
37import de.mpiwg.itgroup.annotations.Annotation;
38import de.mpiwg.itgroup.annotations.Annotation.FragmentTypes;
39import de.mpiwg.itgroup.annotations.Group;
40import de.mpiwg.itgroup.annotations.NS;
41import de.mpiwg.itgroup.annotations.Person;
42import de.mpiwg.itgroup.annotations.neo4j.AnnotationStore;
43
44/**
45 * Base class for Annotator resource classes.
46 *
47 * @author dwinter, casties
48 *
49 */
50public abstract class AnnotatorResourceImpl extends ServerResource {
51
52    protected static Logger logger = Logger.getLogger(AnnotatorResourceImpl.class);
53
54    private AnnotationStore store;
55
56    protected String getAllowedMethodsForHeader() {
57        return "OPTIONS,GET,POST";
58    }
59
60    protected AnnotationStore getAnnotationStore() {
61        if (store == null) {
62            store = ((BaseRestlet) getApplication()).getAnnotationStore();
63        }
64        return store;
65    }
66
67    public String encodeJsonId(String id) {
68        if (id == null) return null;
69        try {
70            return Base64.encodeBase64URLSafeString(id.getBytes("UTF-8"));
71        } catch (UnsupportedEncodingException e) {
72            return null;
73        }
74    }
75
76    public String decodeJsonId(String id) {
77        if (id == null) return null;
78        try {
79            return new String(Base64.decodeBase64(id), "UTF-8");
80        } catch (UnsupportedEncodingException e) {
81            return null;
82        }
83    }
84
85    /**
86     * Handle options request to allow CORS for AJAX.
87     *
88     * @param entity
89     */
90    @Options
91    public void doOptions(Representation entity) {
92        logger.debug("AnnotatorResourceImpl doOptions!");
93        setCorsHeaders();
94    }
95
96    /**
97     * set headers to allow CORS for AJAX.
98     */
99    protected void setCorsHeaders() {
100        Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");
101        if (responseHeaders == null) {
102            responseHeaders = new Form();
103            getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
104        }
105        responseHeaders.add("Access-Control-Allow-Methods", getAllowedMethodsForHeader());
106        // echo back Origin and Request-Headers
107        Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers");
108        String origin = requestHeaders.getFirstValue("Origin", true);
109        if (origin == null) {
110            responseHeaders.add("Access-Control-Allow-Origin", "*");
111        } else {
112            responseHeaders.add("Access-Control-Allow-Origin", origin);
113        }
114        String allowHeaders = requestHeaders.getFirstValue("Access-Control-Request-Headers", true);
115        if (allowHeaders != null) {
116            responseHeaders.add("Access-Control-Allow-Headers", allowHeaders);
117        }
118        responseHeaders.add("Access-Control-Allow-Credentials", "true");
119        responseHeaders.add("Access-Control-Max-Age", "60");
120    }
121
122    /**
123     * returns if authentication information from headers is valid.
124     *
125     * @param entity
126     * @return
127     */
128    public boolean isAuthenticated(Representation entity) {
129        return (checkAuthToken(entity) != null);
130    }
131
132    /**
133     * checks Annotator Auth plugin authentication information from headers.
134     * returns userId if successful.
135     *
136     * @param entity
137     * @return
138     */
139    public String checkAuthToken(Representation entity) {
140        Form requestHeaders = (Form) getRequest().getAttributes().get("org.restlet.http.headers");
141        String authToken = requestHeaders.getFirstValue("x-annotator-auth-token", true);
142        if (authToken == null) return null;
143        // decode token first to get consumer key
144        JsonToken token = new JsonTokenParser(null, null).deserialize(authToken);
145        String userId = token.getParamAsPrimitive("userId").getAsString();
146        String consumerKey = token.getParamAsPrimitive("consumerKey").getAsString();
147        // get stored consumer secret for key
148        BaseRestlet restServer = (BaseRestlet) getApplication();
149        String consumerSecret = restServer.getConsumerSecret(consumerKey);
150        logger.debug("requested consumer key=" + consumerKey + " secret=" + consumerSecret);
151        if (consumerSecret == null) {
152            return null;
153        }
154        // logger.debug(String.format("token=%s tokenString=%s signatureAlgorithm=%s",token,token.getTokenString(),token.getSignatureAlgorithm()));
155        try {
156            List<Verifier> verifiers = new ArrayList<Verifier>();
157            // we only do HS256 yet
158            verifiers.add(new HmacSHA256Verifier(consumerSecret.getBytes("UTF-8")));
159            // verify token signature(should really be static...)
160            new JsonTokenParser(new SystemClock(), null, (Checker[]) null).verify(token, verifiers);
161        } catch (SignatureException e) {
162            // TODO Auto-generated catch block
163            e.printStackTrace();
164        } catch (InvalidKeyException e) {
165            // TODO Auto-generated catch block
166            e.printStackTrace();
167        } catch (UnsupportedEncodingException e) {
168            // TODO Auto-generated catch block
169            e.printStackTrace();
170        }
171        // must be ok then
172        logger.debug("auth OK! user=" + userId);
173        return userId;
174    }
175
176    /**
177     * creates Annotator-JSON from an Annotation object.
178     *
179     * @param annot
180     * @param forAnonymous TODO
181     * @return
182     */
183    public JSONObject createAnnotatorJson(Annotation annot, boolean forAnonymous) {
184        // return user as a JSON object (otherwise just as string)
185        boolean makeUserObject = true;
186        JSONObject jo = new JSONObject();
187        try {
188            jo.put("text", annot.getBodyText());
189            jo.put("uri", annot.getTargetBaseUri());
190            if (annot.getResourceUri() != null) {
191                jo.put("resource", annot.getResourceUri());
192            }
193
194            /*
195             * user
196             */
197            if (makeUserObject) {
198                // create user object
199                JSONObject userObject = new JSONObject();
200                Actor creator = annot.getCreator();
201                // save creator as uri
202                userObject.put("uri", creator.getUri());
203                // make short user id
204                String userId = creator.getIdString();
205                // set as id
206                userObject.put("id", userId);
207                // get full name
208                String userName = creator.getName();
209                if (userName == null) {
210                    BaseRestlet restServer = (BaseRestlet) getApplication();
211                    userName = restServer.getFullNameFromLdap(userId);
212                }
213                userObject.put("name", userName);
214                // save user object
215                jo.put("user", userObject);
216            } else {
217                // save user as string
218                jo.put("user", annot.getCreatorUri());
219            }
220
221            /*
222             * ranges
223             */
224            if (annot.getTargetFragment() != null) {
225                // we only look at the first xpointer
226                List<String> fragments = new ArrayList<String>();
227                fragments.add(annot.getTargetFragment());
228                FragmentTypes xt = annot.getFragmentType();
229                if (xt == FragmentTypes.XPOINTER) {
230                    jo.put("ranges", transformToRanges(fragments));
231                } else if (xt == FragmentTypes.AREA) {
232                    jo.put("areas", transformToAreas(fragments));
233                }
234            }
235           
236            /*
237             * permissions
238             */
239            JSONObject perms = new JSONObject();
240            jo.put("permissions", perms);
241            // admin
242            JSONArray adminPerms = new JSONArray();
243            perms.put("admin", adminPerms);
244            Actor adminPerm = annot.getAdminPermission();
245            if (adminPerm != null) {
246                adminPerms.put(adminPerm.getIdString());
247            } else if (forAnonymous) {
248                // set something because its not allowed for anonymous
249                adminPerms.put("not-you");
250            }
251            // delete
252            JSONArray deletePerms = new JSONArray();
253            perms.put("delete", deletePerms);
254            Actor deletePerm = annot.getDeletePermission();
255            if (deletePerm != null) {
256                deletePerms.put(deletePerm.getIdString());
257            } else if (forAnonymous) {
258                // set something because its not allowed for anonymous
259                deletePerms.put("not-you");
260            }
261            // update
262            JSONArray updatePerms = new JSONArray();
263            perms.put("update", updatePerms);
264            Actor updatePerm = annot.getUpdatePermission();
265            if (updatePerm != null) {
266                updatePerms.put(updatePerm.getIdString());
267            } else if (forAnonymous) {
268                // set something because its not allowed for anonymous
269                updatePerms.put("not-you");
270            }
271            // read
272            JSONArray readPerms = new JSONArray();
273            perms.put("read", readPerms);
274            Actor readPerm = annot.getReadPermission();
275            if (readPerm != null) {
276                readPerms.put(readPerm.getIdString());
277            }
278           
279            /*
280             * tags
281             */
282            Set<String> tagset = annot.getTags(); 
283            if (tagset != null) {
284                JSONArray tags = new JSONArray();
285                jo.put("tags", tags);
286                for (String tag : tagset) {
287                    tags.put(tag);
288                }
289            }
290           
291            /*
292             * id
293             */
294            // encode Annotation URL (=id) in base64
295            String annotUrl = annot.getUri();
296            String annotId = encodeJsonId(annotUrl);
297            jo.put("id", annotId);
298            return jo;
299        } catch (JSONException e) {
300            // TODO Auto-generated catch block
301            e.printStackTrace();
302        }
303        return null;
304    }
305
306    private JSONArray transformToRanges(List<String> xpointers) {
307
308        JSONArray ja = new JSONArray();
309
310        Pattern rg = Pattern
311                .compile("xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)/range-to\\(end-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)\\)");
312        Pattern rg1 = Pattern.compile("xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)");
313
314        try {
315            for (String xpointer : xpointers) {
316                // String decoded = URLDecoder.decode(xpointer, "utf-8");
317                String decoded = xpointer;
318                Matcher m = rg.matcher(decoded);
319
320                if (m.find()) {
321                    {
322                        JSONObject jo = new JSONObject();
323                        jo.put("start", m.group(1));
324                        jo.put("startOffset", m.group(2));
325                        jo.put("end", m.group(3));
326                        jo.put("endOffset", m.group(4));
327                        ja.put(jo);
328                    }
329                }
330                m = rg1.matcher(xpointer);
331                if (m.find()) {
332                    JSONObject jo = new JSONObject();
333                    jo.put("start", m.group(1));
334                    jo.put("startOffset", m.group(2));
335
336                    ja.put(jo);
337                }
338            }
339        } catch (JSONException e) {
340            // TODO Auto-generated catch block
341            e.printStackTrace();
342        }
343        return ja;
344    }
345
346    private JSONArray transformToAreas(List<String> xpointers) {
347
348        JSONArray ja = new JSONArray();
349
350        Pattern rg = Pattern.compile("xywh=(\\w*:)([\\d\\.]+),([\\d\\.]+),([\\d\\.]+),([\\d\\.]+)");
351
352        try {
353            for (String xpointer : xpointers) {
354                // String decoded = URLDecoder.decode(xpointer, "utf-8");
355                String decoded = xpointer;
356                Matcher m = rg.matcher(decoded);
357
358                if (m.find()) {
359                    {
360                        JSONObject jo = new JSONObject();
361                        @SuppressWarnings("unused")
362                        String unit = m.group(1);
363                        jo.put("x", m.group(2));
364                        jo.put("y", m.group(3));
365                        jo.put("width", m.group(4));
366                        jo.put("height", m.group(5));
367                        ja.put(jo);
368                    }
369                }
370            }
371        } catch (JSONException e) {
372            // TODO Auto-generated catch block
373            e.printStackTrace();
374        }
375        return ja;
376    }
377
378    protected String parseArea(JSONObject area) throws JSONException {
379        String x = area.getString("x");
380        String y = area.getString("y");
381        String width = "0";
382        String height = "0";
383        if (area.has("width")) {
384            width = area.getString("width");
385            height = area.getString("height");
386        }
387        String fragment = String.format("xywh=fraction:%s,%s,%s,%s", x, y, width, height);
388        return fragment;
389    }
390
391    protected String parseRange(JSONObject range) throws JSONException {
392        String start = range.getString("start");
393        String end = range.getString("end");
394        String startOffset = range.getString("startOffset");
395        String endOffset = range.getString("endOffset");
396
397        String fragment = String.format(
398                "xpointer(start-point(string-range(\"%s\",%s,1))/range-to(end-point(string-range(\"%s\",%s,1))))", start,
399                startOffset, end, endOffset);
400        return fragment;
401    }
402
403    /**
404     * Creates an Annotation object with data from JSON.
405     *
406     * uses the specification from the annotator project: {@link https
407     * ://github.com/okfn/annotator/wiki/Annotation-format}
408     *
409     * The username will be transformed to an URI if not given already as URI,
410     * if not it will set to the MPIWG namespace defined in
411     * de.mpiwg.itgroup.annotationManager.Constants.NS
412     *
413     * @param jo
414     * @return
415     * @throws JSONException
416     * @throws UnsupportedEncodingException
417     */
418    public Annotation createAnnotation(JSONObject jo, Representation entity) throws JSONException, UnsupportedEncodingException {
419        return updateAnnotation(new Annotation(), jo, entity);
420    }
421
422    /**
423     * Updates an Annotation object with data from JSON.
424     *
425     * uses the specification from the annotator project: {@link https
426     * ://github.com/okfn/annotator/wiki/Annotation-format}
427     *
428     * The username will be transformed to an URI if not given already as URI,
429     * if not it will set to the MPIWG namespace defined in
430     * de.mpiwg.itgroup.annotationManager.Constants.NS
431     *
432     * @param annot
433     * @param jo
434     * @return
435     * @throws JSONException
436     * @throws UnsupportedEncodingException
437     */
438    public Annotation updateAnnotation(Annotation annot, JSONObject jo, Representation entity) throws JSONException,
439            UnsupportedEncodingException {
440        /*
441         * target uri
442         */
443        if (jo.has("uri")) {
444            annot.setTargetBaseUri(jo.getString("uri"));
445        }
446        /*
447         * resource uri
448         */
449        if (jo.has("resource")) {
450            annot.setResourceUri(jo.getString("resource"));
451        }
452        /*
453         * annotation text
454         */
455        if (jo.has("text")) {
456            annot.setBodyText(jo.getString("text"));
457        }
458        /*
459         * check authentication
460         */
461        String authUser = checkAuthToken(entity);
462        if (authUser == null) {
463            /*
464             * // try http auth User httpUser = getHttpAuthUser(entity); if
465             * (httpUser == null) {
466             */
467            setStatus(Status.CLIENT_ERROR_FORBIDDEN);
468            return null;
469            /*
470             * } authUser = httpUser.getIdentifier();
471             */
472        }
473        /*
474         * get or create creator object
475         */
476        Actor creator = annot.getCreator();
477        if (creator == null) {
478            creator = new Person();
479            annot.setCreator(creator);
480        }
481        // username not required, if no username given authuser will be used
482        String username = null;
483        String userUri = creator.getUri();
484        if (jo.has("user")) {
485            if (jo.get("user") instanceof String) {
486                // user is just a String
487                username = jo.getString("user");
488                creator.setId(username);
489                // TODO: what if username and authUser are different?
490            } else {
491                // user is an object
492                JSONObject user = jo.getJSONObject("user");
493                if (user.has("id")) {
494                    String id = user.getString("id");
495                    creator.setId(id);
496                    username = id;
497                }
498                if (user.has("uri")) {
499                    userUri = user.getString("uri");
500                }
501            }
502        }
503        if (username == null) {
504            username = authUser;
505        }
506        // try to get full name
507        if (creator.getName() == null && username != null) {
508            BaseRestlet restServer = (BaseRestlet) getApplication();
509            String fullName = restServer.getFullNameFromLdap(username);
510            creator.setName(fullName);
511        }
512        // userUri should be a URI, if not it will set to the MPIWG namespace
513        if (userUri == null) {
514            if (username.startsWith("http")) {
515                userUri = username;
516            } else {
517                userUri = NS.MPIWG_PERSONS_URL + username;
518            }
519        }
520        // TODO: should we overwrite the creator?
521        if (creator.getUri() == null) {
522            creator.setUri(userUri);
523        }
524        /*
525         * creation date
526         */
527        if (annot.getCreated() == null) {
528            // set creation date
529            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
530            String ct = format.format(Calendar.getInstance().getTime());
531            annot.setCreated(ct);
532        }
533
534        /*
535         * create xpointer from the first range/area
536         */
537        if (jo.has("ranges")) {
538            JSONObject ranges = jo.getJSONArray("ranges").getJSONObject(0);
539            annot.setFragmentType(FragmentTypes.XPOINTER);
540            String fragment = parseRange(ranges);
541            annot.setTargetFragment(fragment);
542        }
543        if (jo.has("areas")) {
544            JSONObject area = jo.getJSONArray("areas").getJSONObject(0);
545            annot.setFragmentType(FragmentTypes.AREA);
546            String fragment = parseArea(area);
547            annot.setTargetFragment(fragment);
548        }
549
550        /*
551         * permissions
552         */
553        if (jo.has("permissions")) {
554            JSONObject permissions = jo.getJSONObject("permissions");
555            if (permissions.has("admin")) {
556                JSONArray perms = permissions.getJSONArray("admin");
557                Actor actor = getActorFromPermissions(perms);
558                annot.setAdminPermission(actor);
559            }
560            if (permissions.has("delete")) {
561                JSONArray perms = permissions.getJSONArray("delete");
562                Actor actor = getActorFromPermissions(perms);
563                annot.setDeletePermission(actor);
564            }
565            if (permissions.has("update")) {
566                JSONArray perms = permissions.getJSONArray("update");
567                Actor actor = getActorFromPermissions(perms);
568                annot.setUpdatePermission(actor);
569            }
570            if (permissions.has("read")) {
571                JSONArray perms = permissions.getJSONArray("read");
572                Actor actor = getActorFromPermissions(perms);
573                annot.setReadPermission(actor);
574            }
575        }
576
577        /*
578         * tags
579         */
580        if (jo.has("tags")) {
581            HashSet<String> tagset = new HashSet<String>();
582            JSONArray tags = jo.getJSONArray("tags");
583            for (int i = 0; i < tags.length(); ++i) {
584                tagset.add(tags.getString(i));
585            }
586            annot.setTags(tagset);
587        }
588
589       
590        return annot;
591    }
592
593    @SuppressWarnings("unused") // i in for loop
594    protected Actor getActorFromPermissions(JSONArray perms) throws JSONException {
595        Actor actor = null;
596        for (int i = 0; i < perms.length(); ++i) {
597            String perm = perms.getString(i);
598            if (perm.toLowerCase().startsWith("group:")) {
599                String groupId = perm.substring(6);
600                actor = new Group(groupId);
601            } else {
602                actor = new Person(perm);
603            }
604            // we just take the first one
605            break;
606        }
607        return actor;
608    }
609
610}
Note: See TracBrowser for help on using the repository browser.