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 javax.json.Json; |
22 | |
import javax.json.JsonReader; |
23 | |
import javax.json.JsonReaderFactory; |
24 | |
import javax.json.JsonStructure; |
25 | |
import javax.ws.rs.Consumes; |
26 | |
import javax.ws.rs.WebApplicationException; |
27 | |
import javax.ws.rs.core.MediaType; |
28 | |
import javax.ws.rs.core.MultivaluedMap; |
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.lang.annotation.Annotation; |
34 | |
import java.lang.reflect.Type; |
35 | |
import java.util.Collections; |
36 | |
|
37 | |
import static javax.ws.rs.core.MediaType.WILDCARD; |
38 | |
|
39 | 2 | @Provider |
40 | |
@Consumes(WILDCARD) |
41 | |
public class JsrMessageBodyReader implements MessageBodyReader<JsonStructure> { |
42 | |
private final JsonReaderFactory factory; |
43 | |
private final boolean closeStream; |
44 | |
|
45 | |
public JsrMessageBodyReader() { |
46 | 3 | this(Json.createReaderFactory(Collections.<String, Object>emptyMap()), false); |
47 | 3 | } |
48 | |
|
49 | 3 | public JsrMessageBodyReader(final JsonReaderFactory factory, final boolean closeStream) { |
50 | 3 | this.factory = factory; |
51 | 3 | this.closeStream = closeStream; |
52 | 3 | } |
53 | |
|
54 | |
@Override |
55 | |
public boolean isReadable(final Class<?> aClass, final Type type, |
56 | |
final Annotation[] annotations, final MediaType mediaType) { |
57 | 2 | return JsonStructure.class.isAssignableFrom(aClass); |
58 | |
} |
59 | |
|
60 | |
@Override |
61 | |
public JsonStructure readFrom(final Class<JsonStructure> jsonStructureClass, final Type type, |
62 | |
final Annotation[] annotations, final MediaType mediaType, |
63 | |
final MultivaluedMap<String, String> stringStringMultivaluedMap, |
64 | |
final InputStream inputStream) throws IOException, WebApplicationException { |
65 | 2 | JsonReader reader = null; |
66 | |
try { |
67 | 2 | reader = factory.createReader(inputStream); |
68 | 2 | return reader.read(); |
69 | |
} finally { |
70 | 2 | if (closeStream && reader != null) { |
71 | 0 | reader.close(); |
72 | |
} |
73 | |
} |
74 | |
} |
75 | |
} |