1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package eu.ehri.extension.providers;
21
22 import com.fasterxml.jackson.core.type.TypeReference;
23 import com.fasterxml.jackson.databind.JsonMappingException;
24 import eu.ehri.project.acl.ContentTypes;
25 import eu.ehri.project.acl.GlobalPermissionSet;
26 import eu.ehri.project.acl.PermissionType;
27 import eu.ehri.project.exceptions.DeserializationError;
28
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.WebApplicationException;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.MultivaluedMap;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.ext.MessageBodyReader;
35 import javax.ws.rs.ext.Provider;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.lang.annotation.Annotation;
39 import java.lang.reflect.Type;
40 import java.util.Collection;
41 import java.util.HashMap;
42 import java.util.List;
43
44
45 @Provider
46 @Consumes(MediaType.APPLICATION_JSON)
47 public class GlobalPermissionSetProvider implements MessageBodyReader<GlobalPermissionSet>, JsonMessageBodyHandler {
48
49 @Override
50 public boolean isReadable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
51 return aClass == GlobalPermissionSet.class;
52 }
53
54 @Override
55 public GlobalPermissionSet readFrom(Class<GlobalPermissionSet> bundleClass, Type type, Annotation[] annotations,
56 MediaType mediaType, MultivaluedMap<String,
57 String> headers, InputStream stream) throws IOException, WebApplicationException {
58
59 try {
60 return parseMatrix(stream);
61 } catch (DeserializationError deserializationError) {
62 throw new WebApplicationException(deserializationError, Response.Status.BAD_REQUEST);
63 }
64 }
65
66 private GlobalPermissionSet parseMatrix(InputStream json) throws DeserializationError {
67 try {
68 TypeReference<HashMap<ContentTypes, List<PermissionType>>> typeRef = new TypeReference<HashMap<ContentTypes,
69 List<PermissionType>>>() {
70 };
71 HashMap<ContentTypes, Collection<PermissionType>> globals = mapper.readValue(json, typeRef);
72 return GlobalPermissionSet.from(globals);
73 } catch (JsonMappingException e) {
74 throw new DeserializationError(e.getMessage());
75 } catch (IOException e) {
76 throw new DeserializationError(e.getMessage());
77 }
78 }
79 }