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.JsonStructure; |
23 | |
import javax.json.JsonWriter; |
24 | |
import javax.json.JsonWriterFactory; |
25 | |
import javax.ws.rs.Produces; |
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.MessageBodyWriter; |
30 | |
import javax.ws.rs.ext.Provider; |
31 | |
import java.io.Flushable; |
32 | |
import java.io.IOException; |
33 | |
import java.io.OutputStream; |
34 | |
import java.lang.annotation.Annotation; |
35 | |
import java.lang.reflect.Type; |
36 | |
import java.util.Collections; |
37 | |
|
38 | |
import static javax.ws.rs.core.MediaType.WILDCARD; |
39 | |
|
40 | 2 | @Provider |
41 | |
@Produces(WILDCARD) |
42 | |
public class JsrMessageBodyWriter implements MessageBodyWriter<JsonStructure> { |
43 | |
private final JsonWriterFactory factory; |
44 | |
private final boolean close; |
45 | |
|
46 | |
public JsrMessageBodyWriter() { |
47 | 3 | this(Json.createWriterFactory(Collections.<String, Object>emptyMap()), false); |
48 | 3 | } |
49 | |
|
50 | 3 | public JsrMessageBodyWriter(final JsonWriterFactory factory, final boolean closeStreams) { |
51 | 3 | this.factory = factory; |
52 | 3 | this.close = closeStreams; |
53 | 3 | } |
54 | |
|
55 | |
@Override |
56 | |
public boolean isWriteable(final Class<?> aClass, final Type type, |
57 | |
final Annotation[] annotations, final MediaType mediaType) { |
58 | 2 | return JsonStructure.class.isAssignableFrom(aClass); |
59 | |
} |
60 | |
|
61 | |
@Override |
62 | |
public long getSize(final JsonStructure jsonStructure, final Class<?> aClass, |
63 | |
final Type type, final Annotation[] annotations, |
64 | |
final MediaType mediaType) { |
65 | 0 | return -1; |
66 | |
} |
67 | |
|
68 | |
@Override |
69 | |
public void writeTo(final JsonStructure jsonStructure, |
70 | |
final Class<?> aClass, final Type type, |
71 | |
final Annotation[] annotations, final MediaType mediaType, |
72 | |
final MultivaluedMap<String, Object> stringObjectMultivaluedMap, |
73 | |
final OutputStream outputStream) throws IOException, WebApplicationException { |
74 | 2 | JsonWriter writer = null; |
75 | |
try { |
76 | 2 | writer = factory.createWriter(outputStream); |
77 | 2 | writer.write(jsonStructure); |
78 | |
} finally { |
79 | 2 | if (writer != null) { |
80 | 2 | if (close) { |
81 | 0 | writer.close(); |
82 | 2 | } else if (Flushable.class.isInstance(writer)) { |
83 | 0 | Flushable.class.cast(writer).flush(); |
84 | |
} |
85 | |
} |
86 | |
} |
87 | 2 | } |
88 | |
} |