source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorAnnotations.java @ 41:5d4260344db5

Last change on this file since 41:5d4260344db5 was 41:5d4260344db5, checked in by casties, 12 years ago

Merge with 21c5394ea0cbb6738016a3c7d03b5ce7943d6216

File size: 9.5 KB
Line 
1/**
2 * Implements the "annotations" uri of the Annotator API. see
3 * <https://github.com/okfn/annotator/wiki/Storage>
4 */
5package de.mpiwg.itgroup.annotations.restlet;
6
7import java.io.IOException;
8import java.util.ArrayList;
9import java.util.List;
10
11import org.json.JSONArray;
12import org.json.JSONException;
13import org.json.JSONObject;
14import org.restlet.data.Form;
15import org.restlet.data.Parameter;
16import org.restlet.data.Status;
17import org.restlet.ext.json.JsonRepresentation;
18import org.restlet.representation.Representation;
19import org.restlet.resource.Delete;
20import org.restlet.resource.Get;
21import org.restlet.resource.Post;
22import org.restlet.resource.Put;
23
24import de.mpiwg.itgroup.annotations.Annotation;
25import de.mpiwg.itgroup.annotations.Person;
26import de.mpiwg.itgroup.annotations.neo4j.AnnotationStore;
27import de.mpiwg.itgroup.annotations.restlet.utils.JSONObjectComparator;
28
29/**
30 * Implements the "annotations" uri of the Annotator API. see
31 * <https://github.com/okfn/annotator/wiki/Storage>
32 *
33 * @author dwinter, casties
34 *
35 */
36public class AnnotatorAnnotations extends AnnotatorResourceImpl {
37
38    protected String getAllowedMethodsForHeader() {
39        return "OPTIONS,GET,POST,PUT,DELETE";
40    }
41
42    /**
43     * GET with JSON content-type.
44     *
45     * @param entity
46     * @return
47     */
48    @Get("json")
49    public Representation doGetJSON(Representation entity) {
50        logger.debug("AnnotatorAnnotations doGetJSON!");
51        setCorsHeaders();
52        // id from URI /annotations/{id}
53        String jsonId = (String) getRequest().getAttributes().get("id");
54        String id = decodeJsonId(jsonId);
55        logger.debug("annotation-id=" + id);
56
57       
58        // do authentication
59        Person authUser = Person.createPersonWithId(this.checkAuthToken(entity));
60        logger.debug("request authenticated=" + authUser);
61
62        if (id == null) {
63           
64            return getAllAnnotations(authUser);
65        }
66
67     
68        AnnotationStore store = getAnnotationStore();
69        Annotation annot = store.getAnnotationById(id);
70        if (annot != null) {
71            if (! annot.isActionAllowed("read", authUser, store)) {
72                setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Not Authorized!");
73                return null;
74            }
75            JSONObject result = createAnnotatorJson(annot, (authUser == null));
76            logger.debug("sending:");
77            logger.debug(result);
78            return new JsonRepresentation(result);
79        } else {
80            // not found
81            setStatus(Status.CLIENT_ERROR_NOT_FOUND);
82            return null;
83        }
84    }
85
86    private Representation getAllAnnotations(Person authUser) {
87       
88         Form form = getRequest().getResourceRef().getQueryAsForm();
89           String sortBy=null;
90           for (Parameter parameter : form) {
91             if (parameter.getName().equals("sortBy")){
92             sortBy =  parameter.getValue();
93             }
94           }
95       
96        AnnotationStore store = getAnnotationStore();
97        ArrayList<JSONObject> results = new ArrayList<JSONObject>();
98       
99        List<Annotation> annotations = store.getAnnotations(null, null);
100        for (Annotation annotation : annotations) {
101                 //check permission
102                         if (!annotation.isActionAllowed("read", authUser, store)) continue;
103     
104                 JSONObject jo = createAnnotatorJson(annotation,false);
105             results.add(jo);
106           
107            }
108       
109        if (sortBy!=null){
110                JSONObjectComparator.sortAnnotations(results,sortBy);
111        }
112       
113        JSONArray resultsJa = new JSONArray();
114        for (JSONObject result:results){
115                resultsJa.put(result);
116        }
117       
118        // assemble result object
119        JSONObject result = new JSONObject();
120        try {
121            result.put("rows", resultsJa);
122            result.put("total", resultsJa.length());
123        } catch (JSONException e) {
124            setStatus(Status.SERVER_ERROR_INTERNAL, "JSON Error");
125            return null;
126        }
127        logger.debug("sending:");
128        logger.debug(result);
129        return new JsonRepresentation(result);
130    }
131
132       
133       
134       
135
136        /**
137     * POST with JSON content-type. Creates a new Annotation.
138     *
139     * @return
140     */
141    @Post("json")
142    public Representation doPostJson(Representation entity) {
143        logger.debug("AnnotatorAnnotations doPostJSON!");
144        // set headers
145        setCorsHeaders();
146       
147        // do authentication TODO: who's allowed to create?
148        Person authUser = Person.createPersonWithId(this.checkAuthToken(entity));
149        logger.debug("request authenticated=" + authUser);
150        if (authUser == null) {
151            setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Not Authorized!");
152            return null;
153        }
154
155        Annotation annot = null;
156        try {
157            JsonRepresentation jrep = new JsonRepresentation(entity);
158            JSONObject jo = jrep.getJsonObject();
159            if (jo == null) {
160                setStatus(Status.SERVER_ERROR_INTERNAL);
161                return null;
162            }
163            // make sure id is not set for POST
164            jo.remove("id");
165            // get Annotation object from posted JSON
166            annot = createAnnotation(jo, entity);
167        } catch (IOException e1) {
168            setStatus(Status.SERVER_ERROR_INTERNAL);
169            return null;
170        } catch (JSONException e) {
171            setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
172            return null;
173        }
174        if (annot == null) {
175            setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
176            return null;
177        }
178        Annotation storedAnnot;
179        // store Annotation
180        storedAnnot = getAnnotationStore().storeAnnotation(annot);
181        /*
182         * according to https://github.com/okfn/annotator/wiki/Storage we should
183         * return 303: see other. For now we return the annotation.
184         */
185        JSONObject jo = createAnnotatorJson(storedAnnot, (authUser == null));
186        JsonRepresentation retRep = new JsonRepresentation(jo);
187        return retRep;
188    }
189
190    /**
191     * PUT with JSON content-type. Modifies an Annotation.
192     *
193     * @param entity
194     * @return
195     */
196    @Put("json")
197    public Representation doPutJSON(Representation entity) {
198        logger.debug("AnnotatorAnnotations doPutJSON!");
199        setCorsHeaders();
200        // id from URI /annotations/{id}
201        String jsonId = (String) getRequest().getAttributes().get("id");
202        String id = decodeJsonId(jsonId);
203        logger.debug("annotation-id=" + id);
204
205        // do authentication
206        Person authUser = Person.createPersonWithId(this.checkAuthToken(entity));
207        logger.debug("request authenticated=" + authUser);
208
209        Annotation annot = null;
210        AnnotationStore store = getAnnotationStore();
211        try {
212            JsonRepresentation jrep = new JsonRepresentation(entity);
213            JSONObject jo = jrep.getJsonObject();
214            if (jo == null) {
215                setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
216                return null;
217            }
218            // get stored Annotation
219            Annotation storedAnnot = store.getAnnotationById(id);
220            if (storedAnnot == null) {
221                setStatus(Status.CLIENT_ERROR_NOT_FOUND);
222                return null;
223            }
224            if (! storedAnnot.isActionAllowed("update", authUser, store)) {
225                setStatus(Status.CLIENT_ERROR_FORBIDDEN);
226                return null;
227            }
228            // update from posted JSON
229            annot = updateAnnotation(storedAnnot, jo, entity);
230            // store Annotation
231            storedAnnot = store.storeAnnotation(annot);
232            /*
233             * according to https://github.com/okfn/annotator/wiki/Storage we
234             * should return 303: see other. but the client doesn't like it
235             * setStatus(Status.REDIRECTION_SEE_OTHER); // go to same URL as
236             * this one Reference thisUrl = this.getReference();
237             * this.getResponse().setLocationRef(thisUrl);
238             */
239            // return new annotation
240            jo = createAnnotatorJson(storedAnnot, (authUser == null));
241            JsonRepresentation retRep = new JsonRepresentation(jo);
242            return retRep;
243        } catch (JSONException e) {
244            e.printStackTrace();
245            setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
246        } catch (IOException e) {
247            e.printStackTrace();
248            setStatus(Status.SERVER_ERROR_INTERNAL, "Other Error");
249        }
250        return null;
251    }
252
253    /**
254     * DELETE with JSON content-type. Deletes an Annotation.
255     *
256     * @param entity
257     * @return
258     */
259    @Delete("json")
260    public Representation doDeleteJSON(Representation entity) {
261        logger.debug("AnnotatorAnnotations doDeleteJSON!");
262        setCorsHeaders();
263        // id from URI /annotations/{id}
264        String jsonId = (String) getRequest().getAttributes().get("id");
265        String id = decodeJsonId(jsonId);
266        logger.debug("annotation-id=" + id);
267
268        // do authentication
269        Person authUser = Person.createPersonWithId(this.checkAuthToken(entity));
270        logger.debug("request authenticated=" + authUser);
271        AnnotationStore store = getAnnotationStore();
272        Annotation annot = store.getAnnotationById(id);
273        if (annot != null) {
274            if (! annot.isActionAllowed("delete", authUser, store)) {
275                setStatus(Status.CLIENT_ERROR_FORBIDDEN, "Not Authorized!");
276                return null;
277            }
278        }
279       
280        // delete annotation
281        store.deleteAnnotationById(id);
282        setStatus(Status.SUCCESS_NO_CONTENT);
283        return null;
284    }
285
286}
Note: See TracBrowser for help on using the repository browser.