source: DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/AnnotationResource.java @ 4539

Last change on this file since 4539 was 4539, checked in by olhsha, 10 years ago

refactoring repetitive code for different sort of resources. Replaced with one code using enum type Resource

File size: 22.4 KB
Line 
1/*
2 * Copyright (C) 2013 DASISH
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17 */
18package eu.dasish.annotation.backend.rest;
19
20import eu.dasish.annotation.backend.BackendConstants;
21import eu.dasish.annotation.backend.Resource;
22import eu.dasish.annotation.backend.dao.DBIntegrityService;
23import eu.dasish.annotation.schema.Annotation;
24import eu.dasish.annotation.schema.AnnotationBody;
25import eu.dasish.annotation.schema.AnnotationInfoList;
26import eu.dasish.annotation.schema.ObjectFactory;
27import eu.dasish.annotation.schema.Permission;
28import eu.dasish.annotation.schema.UserWithPermissionList;
29import eu.dasish.annotation.schema.ReferenceList;
30import eu.dasish.annotation.schema.ResponseBody;
31import java.io.IOException;
32import java.util.UUID;
33import javax.servlet.ServletContext;
34import javax.servlet.http.HttpServletRequest;
35import javax.servlet.http.HttpServletResponse;
36import javax.ws.rs.Consumes;
37import javax.ws.rs.DELETE;
38import javax.ws.rs.GET;
39import javax.ws.rs.POST;
40import javax.ws.rs.PUT;
41import javax.ws.rs.Path;
42import javax.ws.rs.PathParam;
43import javax.ws.rs.Produces;
44import javax.ws.rs.QueryParam;
45import javax.ws.rs.core.Context;
46import javax.ws.rs.core.MediaType;
47import javax.ws.rs.core.UriInfo;
48import javax.ws.rs.ext.Providers;
49import javax.xml.bind.JAXBElement;
50import org.springframework.beans.factory.annotation.Autowired;
51import org.springframework.stereotype.Component;
52import org.slf4j.Logger;
53import org.slf4j.LoggerFactory;
54import org.springframework.transaction.annotation.Transactional;
55
56/**
57 *
58 * @author olhsha
59 */
60@Component
61@Path("/annotations")
62@Transactional(rollbackFor = {Exception.class})
63public class AnnotationResource {
64
65    @Autowired
66    private DBIntegrityService dbIntegrityService;
67    @Context
68    private HttpServletRequest httpServletRequest;
69    @Context
70    private HttpServletResponse httpServletResponse;
71    @Context
72    private UriInfo uriInfo;
73    @Context
74    private Providers providers;
75    @Context
76    private ServletContext context;
77    public static final Logger loggerServer = LoggerFactory.getLogger(HttpServletResponse.class);
78    private final VerboseOutput verboseOutput = new VerboseOutput(httpServletResponse, loggerServer);
79    final private String admin = "admin";
80
81    public void setUriInfo(UriInfo uriInfo) {
82        this.uriInfo = uriInfo;
83    }
84
85    public void setHttpServletResponse(HttpServletResponse httpServletResponse) {
86        this.httpServletResponse = httpServletResponse;
87    }
88
89    public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
90        this.httpServletRequest = httpServletRequest;
91    }
92
93    public void setProviders(Providers providers) {
94        this.providers = providers;
95    }
96
97    public AnnotationResource() {
98    }
99
100    @GET
101    @Produces(MediaType.TEXT_XML)
102    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}")
103    @Transactional(readOnly = true)
104    public JAXBElement<Annotation> getAnnotation(@PathParam("annotationid") String externalIdentifier) throws IOException {
105        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
106        try {
107            final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
108            if (annotationID != null) {
109                String remoteUser = httpServletRequest.getRemoteUser();
110                final Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
111                if (userID != null) {
112                    if (dbIntegrityService.canRead(userID, annotationID)) {
113                        final Annotation annotation = dbIntegrityService.getAnnotation(annotationID);
114                        return new ObjectFactory().createAnnotation(annotation);
115                    } else {
116                        verboseOutput.FORBIDDEN_ANNOTATION_READING(externalIdentifier);
117                    }
118                } else {
119                    verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
120                }
121            } else {
122                verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
123            }
124        } catch (IllegalArgumentException e) {
125            verboseOutput.ILLEGAL_UUID(externalIdentifier);
126        }
127        return new ObjectFactory().createAnnotation(new Annotation());
128    }
129
130    //TODO: unit test
131    @GET
132    @Produces(MediaType.TEXT_XML)
133    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/targets")
134    @Transactional(readOnly = true)
135    public JAXBElement<ReferenceList> getAnnotationTargets(@PathParam("annotationid") String externalIdentifier) throws IOException {
136        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
137        try {
138            final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
139            if (annotationID != null) {
140                String remoteUser = httpServletRequest.getRemoteUser();
141                final Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
142                if (userID != null) {
143                    if (dbIntegrityService.canRead(userID, annotationID)) {
144                        final ReferenceList TargetList = dbIntegrityService.getAnnotationTargets(annotationID);
145                        return new ObjectFactory().createTargetList(TargetList);
146                    } else {
147                        verboseOutput.FORBIDDEN_ANNOTATION_READING(externalIdentifier);
148                    }
149                } else {
150                    verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
151                }
152            } else {
153                verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
154
155            }
156        } catch (IllegalArgumentException e) {
157            verboseOutput.ILLEGAL_UUID(externalIdentifier);
158        }
159        return new ObjectFactory().createTargetList(new ReferenceList());
160    }
161// TODO Unit test
162
163    @GET
164    @Produces(MediaType.TEXT_XML)
165    @Path("")
166    @Transactional(readOnly = true)
167    public JAXBElement<AnnotationInfoList> getFilteredAnnotations(@QueryParam("link") String link,
168            @QueryParam("text") String text,
169            @QueryParam("access") String access,
170            @QueryParam("namespace") String namespace,
171            @QueryParam("owner") String ownerExternalId,
172            @QueryParam("after") String after,
173            @QueryParam("before") String before) throws IOException {
174
175        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
176        String remoteUser = httpServletRequest.getRemoteUser();
177        Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
178        if (userID != null) {
179            try {
180                UUID ownerExternalUUID = (ownerExternalId != null) ? UUID.fromString(ownerExternalId) : null;
181
182                final AnnotationInfoList annotationInfoList = dbIntegrityService.getFilteredAnnotationInfos(ownerExternalUUID, link, text, userID, access, namespace, after, before);
183                return new ObjectFactory().createAnnotationInfoList(annotationInfoList);
184            } catch (IllegalArgumentException e) {
185                verboseOutput.ILLEGAL_UUID(ownerExternalId);
186            }
187        } else {
188            verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
189
190        }
191        return new ObjectFactory().createAnnotationInfoList(new AnnotationInfoList());
192    }
193
194    // TODO Unit test   
195    @GET
196    @Produces(MediaType.TEXT_XML)
197    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/permissions")
198    @Transactional(readOnly = true)
199    public JAXBElement<UserWithPermissionList> getAnnotationPermissions(@PathParam("annotationid") String externalIdentifier) throws IOException {
200        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
201        try {
202            final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
203            String remoteUser = httpServletRequest.getRemoteUser();
204            Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
205            if (userID != null) {
206                if (annotationID != null) {
207                    if (dbIntegrityService.canRead(userID, annotationID)) {
208                        final UserWithPermissionList permissionList = dbIntegrityService.getPermissions(annotationID, Resource.ANNOTATION);
209                        return new ObjectFactory().createPermissionList(permissionList);
210                    } else {
211                        verboseOutput.FORBIDDEN_ANNOTATION_READING(externalIdentifier);
212                    }
213                } else {
214                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
215                }
216            } else {
217                verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
218
219            }
220        } catch (IllegalArgumentException e) {
221            verboseOutput.ILLEGAL_UUID(externalIdentifier);
222        }
223        return new ObjectFactory().createUserWithPermissionList(new UserWithPermissionList());
224    }
225///////////////////////////////////////////////////////
226// TODO: how to return the status code?
227
228    @DELETE
229    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}")
230    public String deleteAnnotation(@PathParam("annotationid") String externalIdentifier) throws IOException {
231        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
232        try {
233            final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
234            String remoteUser = httpServletRequest.getRemoteUser();
235            Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
236            if (userID != null) {
237                if (annotationID != null) {
238                    if (userID.equals(dbIntegrityService.getAnnotationOwner(annotationID)) || dbIntegrityService.getTypeOfUserAccount(userID).equals(admin)) {
239                        int[] resultDelete = dbIntegrityService.deleteAnnotation(annotationID);
240                        String result = Integer.toString(resultDelete[0]);
241                        return result + " annotation(s) deleted.";
242                    } else {
243                        verboseOutput.FORBIDDEN_ANNOTATION_WRITING(externalIdentifier);
244
245                    }
246                } else {
247                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
248                }
249
250            } else {
251                verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
252
253            }
254        } catch (IllegalArgumentException e) {
255            verboseOutput.ILLEGAL_UUID(externalIdentifier);
256        }
257
258        return "Due to the failure no annotation is deleted.";
259    }
260
261    // TODO: how to return the status code?
262///////////////////////////////////////////////////////
263    @POST
264    @Consumes(MediaType.APPLICATION_XML)
265    @Produces(MediaType.APPLICATION_XML)
266    @Path("")
267    public JAXBElement<ResponseBody> createAnnotation(Annotation annotation) throws IOException {
268        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
269        String remoteUser = httpServletRequest.getRemoteUser();
270        Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
271        if (userID != null) {
272            Number annotationID = dbIntegrityService.addUsersAnnotation(userID, annotation);
273            return new ObjectFactory().createResponseBody(dbIntegrityService.makeAnnotationResponseEnvelope(annotationID));
274        } else {
275            verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
276
277        }
278        return new ObjectFactory().createResponseBody(new ResponseBody());
279    }
280///////////////////////////////////////////////////////
281// TODO: unit test
282
283    @PUT
284    @Consumes(MediaType.APPLICATION_XML)
285    @Produces(MediaType.APPLICATION_XML)
286    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}")
287    public JAXBElement<ResponseBody> updateAnnotation(@PathParam("annotationid") String externalIdentifier, Annotation annotation) throws IOException {
288        String path = uriInfo.getBaseUri().toString();
289        dbIntegrityService.setServiceURI(path);
290        String annotationURI = annotation.getURI();
291
292        if (!(path + "annotations/" + externalIdentifier).equals(annotationURI)) {
293            verboseOutput.IDENTIFIER_MISMATCH(externalIdentifier);
294            return new ObjectFactory().createResponseBody(new ResponseBody());
295        }
296
297
298        try {
299            final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
300            if (annotationID != null) {
301                String remoteUser = httpServletRequest.getRemoteUser();
302                Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
303                if (userID != null) {
304                    if (userID.equals(dbIntegrityService.getAnnotationOwner(annotationID)) || dbIntegrityService.getTypeOfUserAccount(userID).equals(admin)) {
305                        int updatedRows = dbIntegrityService.updateAnnotation(annotation);
306                        return new ObjectFactory().createResponseBody(dbIntegrityService.makeAnnotationResponseEnvelope(annotationID));
307                    } else {
308                        verboseOutput.FORBIDDEN_PERMISSION_CHANGING(externalIdentifier);
309                        loggerServer.debug(" Permission changing is the part of the full update of the annotation.");
310                    }
311                } else {
312                    verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
313                }
314            } else {
315                verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
316            }
317        } catch (IllegalArgumentException e) {
318            verboseOutput.ILLEGAL_UUID(externalIdentifier);
319        }
320        return new ObjectFactory().createResponseBody(new ResponseBody());
321    }
322
323    @PUT
324    @Consumes(MediaType.APPLICATION_XML)
325    @Produces(MediaType.APPLICATION_XML)
326    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/body")
327    public JAXBElement<ResponseBody> updateAnnotationBody(@PathParam("annotationid") String externalIdentifier, AnnotationBody annotationBody) throws IOException {
328        String path = uriInfo.getBaseUri().toString();
329        dbIntegrityService.setServiceURI(path);
330        try {
331            final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.ANNOTATION);
332            String remoteUser = httpServletRequest.getRemoteUser();
333            Number userID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
334            if (userID != null) {
335                if (annotationID != null) {
336                    if (dbIntegrityService.canWrite(userID, annotationID)) {
337                        int updatedRows = dbIntegrityService.updateAnnotationBody(annotationID, annotationBody);
338                        return new ObjectFactory().createResponseBody(dbIntegrityService.makeAnnotationResponseEnvelope(annotationID));
339                    } else {
340                        verboseOutput.FORBIDDEN_ANNOTATION_WRITING(externalIdentifier);
341                    }
342                } else {
343                    verboseOutput.ANNOTATION_NOT_FOUND(externalIdentifier);
344                }
345            } else {
346                verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
347
348            }
349        } catch (IllegalArgumentException e) {
350            verboseOutput.ILLEGAL_UUID(externalIdentifier);
351        }
352        return new ObjectFactory().createResponseBody(new ResponseBody());
353    }
354
355    @PUT
356    @Consumes(MediaType.APPLICATION_XML)
357    @Produces(MediaType.APPLICATION_XML)
358    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/permissions/{userid: " + BackendConstants.regExpIdentifier + "}")
359    public String updatePermission(@PathParam("annotationid") String annotationExternalId,
360            @PathParam("userid") String userExternalId, Permission permission) throws IOException {
361        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
362        String remoteUser = httpServletRequest.getRemoteUser();
363        Number remoteUserID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
364        if (remoteUserID != null) {
365            try {
366                final Number userID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(userExternalId), Resource.PRINCIPAL);
367                if (userID != null) {
368                    try {
369                        final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(annotationExternalId), Resource.ANNOTATION);
370                        if (annotationID != null) {
371                            if (remoteUserID.equals(dbIntegrityService.getAnnotationOwner(annotationID)) || dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
372                                int result = (dbIntegrityService.getPermission(annotationID, userID) != null)
373                                        ? dbIntegrityService.updateAnnotationPrincipalPermission(annotationID, userID, permission)
374                                        : dbIntegrityService.addAnnotationPrincipalPermission(annotationID, userID, permission);
375                                return result + " rows are updated/added";
376
377                            } else {
378                                verboseOutput.FORBIDDEN_PERMISSION_CHANGING(annotationExternalId);
379                            }
380                        } else {
381                            verboseOutput.ANNOTATION_NOT_FOUND(annotationExternalId);
382                        }
383                    } catch (IllegalArgumentException e) {
384                        verboseOutput.ILLEGAL_UUID(annotationExternalId);
385                    }
386                } else {
387                    verboseOutput.PRINCIPAL_NOT_FOUND(userExternalId);
388                }
389            } catch (IllegalArgumentException e) {
390                verboseOutput.ILLEGAL_UUID(userExternalId);
391            }
392
393        } else {
394            verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
395
396        }
397        return "Due to the failure no permissionis updated.";
398    }
399
400    @PUT
401    @Consumes(MediaType.APPLICATION_XML)
402    @Produces(MediaType.APPLICATION_XML)
403    @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/permissions/")
404    public JAXBElement<ResponseBody> updatePermissions(@PathParam("annotationid") String annotationExternalId, UserWithPermissionList permissions) throws IOException {
405        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
406        try {
407            final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(annotationExternalId), Resource.ANNOTATION);
408            String remoteUser = httpServletRequest.getRemoteUser();
409            Number remoteUserID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
410            if (remoteUserID != null) {
411                if (annotationID != null) {
412                    if (remoteUserID.equals(dbIntegrityService.getAnnotationOwner(annotationID)) || dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
413                        int updatedRows = dbIntegrityService.updatePermissions(annotationID, permissions);
414                        return new ObjectFactory().createResponseBody(dbIntegrityService.makePermissionResponseEnvelope(annotationID, Resource.ANNOTATION));
415                    } else {
416                        verboseOutput.FORBIDDEN_PERMISSION_CHANGING(annotationExternalId);
417                    }
418                } else {
419                    verboseOutput.ANNOTATION_NOT_FOUND(annotationExternalId);
420                }
421            } else {
422                verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
423
424            }
425            return new ObjectFactory().createResponseBody(new ResponseBody());
426
427        } catch (IllegalArgumentException e) {
428            verboseOutput.ILLEGAL_UUID(annotationExternalId);
429            return new ObjectFactory().createResponseBody(new ResponseBody());
430
431        }
432    }
433
434    @DELETE
435    @Produces(MediaType.TEXT_PLAIN)
436    @Path("{annotationId: " + BackendConstants.regExpIdentifier + "}/user/{userId}/delete")
437    public String deleteUsersPermission(@PathParam("annotationId") String annotationId, @PathParam("userId") String userId) throws IOException {
438        dbIntegrityService.setServiceURI(uriInfo.getBaseUri().toString());
439        int deletedRows = 0;
440        try {
441            final Number annotationID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(annotationId), Resource.ANNOTATION);
442            String remoteUser = httpServletRequest.getRemoteUser();
443            Number remoteUserID = dbIntegrityService.getUserInternalIDFromRemoteID(remoteUser);
444            if (remoteUserID != null) {
445                if (annotationID != null) {
446                    if (remoteUserID.equals(dbIntegrityService.getAnnotationOwner(annotationID)) || dbIntegrityService.getTypeOfUserAccount(remoteUserID).equals(admin)) {
447                        Number userID = dbIntegrityService.getResourceInternalIdentifier(UUID.fromString(userId), Resource.PRINCIPAL);
448                        if (userID != null) {
449                            deletedRows = dbIntegrityService.updateAnnotationPrincipalPermission(annotationID, userID, null);
450
451                        } else {
452                            verboseOutput.PRINCIPAL_NOT_FOUND(userId);
453                        }
454                    } else {
455                        verboseOutput.FORBIDDEN_PERMISSION_CHANGING(annotationId);
456
457                    }
458                } else {
459                    verboseOutput.ANNOTATION_NOT_FOUND(annotationId);
460                }
461            } else {
462                verboseOutput.REMOTE_PRINCIPAL_NOT_FOUND(remoteUser);
463
464            }
465        } catch (IllegalArgumentException e) {
466            verboseOutput.ILLEGAL_UUID(annotationId);
467        }
468        return (deletedRows + " is deleted.");
469    }
470
471}
Note: See TracBrowser for help on using the repository browser.