1 package com.atlassian.plugins.rest.common.json;
2
3 import org.codehaus.jackson.JsonEncoding;
4 import org.codehaus.jackson.map.Module;
5 import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
6 import org.codehaus.jackson.map.SerializationConfig;
7
8 import javax.ws.rs.core.MediaType;
9 import javax.xml.bind.JAXBException;
10 import java.io.ByteArrayOutputStream;
11 import java.io.IOException;
12 import java.util.Collections;
13
14 import static com.google.common.collect.ImmutableList.copyOf;
15
16 public class DefaultJaxbJsonMarshaller implements JaxbJsonMarshaller {
17
18 private final boolean prettyPrint;
19 private final JacksonJsonProvider jsonProvider;
20
21
22
23
24 @Deprecated
25 public DefaultJaxbJsonMarshaller() {
26 this(null, false);
27 }
28
29
30
31
32 @Deprecated
33 public DefaultJaxbJsonMarshaller(boolean prettyPrint) {
34 this(null, prettyPrint);
35 }
36
37 private DefaultJaxbJsonMarshaller(Iterable<? extends Module> modules, boolean prettyPrint) {
38 this.prettyPrint = prettyPrint;
39
40
41
42 Iterable<? extends Module> moduleList = modules != null ? copyOf(modules) : Collections.<Module>emptyList();
43 this.jsonProvider = new JacksonJsonProviderFactory().create(moduleList);
44 }
45
46 public String marshal(Object jaxbBean) {
47 try {
48 final ByteArrayOutputStream os = new ByteArrayOutputStream();
49 if (prettyPrint) {
50 jsonProvider.enable(SerializationConfig.Feature.INDENT_OUTPUT, true);
51 }
52 jsonProvider.writeTo(jaxbBean, jaxbBean.getClass(), null, null, MediaType.APPLICATION_JSON_TYPE, null, os);
53
54
55 return new String(os.toByteArray(), JsonEncoding.UTF8.getJavaName());
56 } catch (IOException e) {
57 throw new JsonMarshallingException(e);
58 }
59 }
60
61 @Deprecated
62 public String marshal(final Object jaxbBean, final Class... jaxbClasses) throws JAXBException {
63 return marshal(jaxbBean);
64 }
65
66 public static Builder builder() {
67 return new Builder();
68 }
69
70 public static class Builder {
71 private boolean prettyPrint;
72 private Iterable<? extends Module> modules;
73
74 private Builder() {
75 }
76
77 public Builder prettyPrint(boolean prettyPrint) {
78 this.prettyPrint = prettyPrint;
79 return this;
80 }
81
82 public Builder modules(Iterable<? extends Module> modules) {
83 this.modules = modules;
84 return this;
85 }
86
87 public JaxbJsonMarshaller build() {
88 return new DefaultJaxbJsonMarshaller(modules, prettyPrint);
89 }
90 }
91 }