source: AnnotationManagerN4J/src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorAnnotations.java @ 37:34b9d044d0bf

Last change on this file since 37:34b9d044d0bf was 37:34b9d044d0bf, checked in by dwinter, 12 years ago

authorisation added
js / css aufgeraeumt

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