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.ItemPermissionSet;
25 import eu.ehri.project.acl.PermissionType;
26 import eu.ehri.project.exceptions.DeserializationError;
27
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.WebApplicationException;
30 import javax.ws.rs.core.MediaType;
31 import javax.ws.rs.core.MultivaluedMap;
32 import javax.ws.rs.core.Response;
33 import javax.ws.rs.ext.MessageBodyReader;
34 import javax.ws.rs.ext.Provider;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.lang.annotation.Annotation;
38 import java.lang.reflect.Type;
39 import java.util.HashSet;
40 import java.util.Set;
41
42
43 @Provider
44 @Consumes(MediaType.APPLICATION_JSON)
45 public class ItemPermissionSetProvider implements MessageBodyReader<ItemPermissionSet>, JsonMessageBodyHandler {
46
47 private static final TypeReference<HashSet<PermissionType>> typeRef = new TypeReference<HashSet<PermissionType>>() {
48 };
49
50 @Override
51 public boolean isReadable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
52 return aClass == ItemPermissionSet.class;
53 }
54
55 @Override
56 public ItemPermissionSet readFrom(Class<ItemPermissionSet> bundleClass, Type type, Annotation[] annotations,
57 MediaType mediaType, MultivaluedMap<String, String> headers, InputStream stream)
58 throws IOException, WebApplicationException {
59 try {
60 return parseMatrix(stream);
61 } catch (DeserializationError deserializationError) {
62 throw new WebApplicationException(deserializationError, Response.Status.BAD_REQUEST);
63 }
64 }
65
66 private ItemPermissionSet parseMatrix(InputStream json) throws DeserializationError {
67 try {
68 Set<PermissionType> set = mapper.readValue(json, typeRef);
69 return ItemPermissionSet.from(set);
70 } catch (JsonMappingException e) {
71 throw new DeserializationError(e.getMessage());
72 } catch (IOException e) {
73 throw new DeserializationError(e.getMessage());
74 }
75 }
76 }