1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
package org.apache.johnzon.jaxrs; |
20 | |
|
21 | |
import org.apache.johnzon.mapper.Mapper; |
22 | |
import org.apache.johnzon.mapper.MapperBuilder; |
23 | |
|
24 | |
import javax.json.JsonStructure; |
25 | |
import javax.ws.rs.Consumes; |
26 | |
import javax.ws.rs.core.MediaType; |
27 | |
import javax.ws.rs.core.MultivaluedMap; |
28 | |
import javax.ws.rs.core.Response; |
29 | |
import javax.ws.rs.ext.MessageBodyReader; |
30 | |
import javax.ws.rs.ext.Provider; |
31 | |
import java.io.IOException; |
32 | |
import java.io.InputStream; |
33 | |
import java.io.Reader; |
34 | |
import java.lang.annotation.Annotation; |
35 | |
import java.lang.reflect.ParameterizedType; |
36 | |
import java.lang.reflect.Type; |
37 | |
import java.util.Collection; |
38 | |
|
39 | |
import static javax.ws.rs.core.MediaType.WILDCARD; |
40 | |
import static org.apache.johnzon.jaxrs.Jsons.isJson; |
41 | |
|
42 | |
@Provider |
43 | |
@Consumes(WILDCARD) |
44 | |
public class JohnzonMessageBodyReader<T> extends IgnorableTypes implements MessageBodyReader<T> { |
45 | |
private final Mapper mapper; |
46 | |
|
47 | |
public JohnzonMessageBodyReader() { |
48 | 0 | this(new MapperBuilder().setDoCloseOnStreams(false).build(), null); |
49 | 0 | } |
50 | |
|
51 | |
public JohnzonMessageBodyReader(final Mapper mapper, final Collection<String> ignoredTypes) { |
52 | 10 | super(ignoredTypes); |
53 | 10 | this.mapper = mapper; |
54 | 10 | } |
55 | |
|
56 | |
@Override |
57 | |
public boolean isReadable(final Class<?> rawType, final Type genericType, |
58 | |
final Annotation[] annotations, final MediaType mediaType) { |
59 | 10 | return isJson(mediaType) |
60 | |
&& !isIgnored(rawType) |
61 | |
&& InputStream.class != rawType && Reader.class != rawType && Response.class != rawType |
62 | |
&& String.class != rawType |
63 | |
&& !JsonStructure.class.isAssignableFrom(rawType); |
64 | |
} |
65 | |
|
66 | |
@Override |
67 | |
public T readFrom(final Class<T> rawType, final Type genericType, |
68 | |
final Annotation[] annotations, final MediaType mediaType, |
69 | |
final MultivaluedMap<String, String> httpHeaders, |
70 | |
final InputStream entityStream) throws IOException { |
71 | 8 | if (rawType.isArray()) { |
72 | 2 | return (T) mapper.readArray(entityStream, rawType.getComponentType()); |
73 | 6 | } else if (Collection.class.isAssignableFrom(rawType) && ParameterizedType.class.isInstance(genericType)) { |
74 | 2 | return (T) mapper.readCollection(entityStream, ParameterizedType.class.cast(genericType)); |
75 | |
} |
76 | 4 | return mapper.readObject(entityStream, genericType); |
77 | |
} |
78 | |
} |