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