1 package ejava.examples.ejbwar.jaxrs;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.InputStream;
5 import java.io.StringWriter;
6
7 import javax.ws.rs.ProcessingException;
8 import javax.ws.rs.ext.ContextResolver;
9 import javax.xml.bind.JAXBContext;
10 import javax.xml.bind.JAXBException;
11 import javax.xml.bind.Marshaller;
12 import javax.xml.bind.Unmarshaller;
13
14 public class JAXBUtils implements ContextResolver<JAXBContext> {
15 private static JAXBUtils instance;
16
17 @Override
18 public JAXBContext getContext(Class<?> type) {
19 try {
20 JAXBContext jbx=JAXBContext.newInstance(type);
21 return jbx;
22 } catch (JAXBException ex) {
23 throw new IllegalStateException("error resolving JAXBContext for type: " + type, ex);
24 }
25 }
26
27 private static JAXBUtils getInstance() {
28 if (instance==null) {
29 instance=new JAXBUtils();
30 }
31 return instance;
32 }
33
34 public static <T> String marshal(T object) {
35 if (object==null) {
36 return "";
37 }
38
39 try {
40 JAXBContext jbx = getInstance().getContext(object.getClass());
41 Marshaller marshaller = jbx.createMarshaller();
42 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
43 StringWriter writer = new StringWriter();
44 marshaller.marshal(object, writer);
45 return writer.toString();
46 } catch (JAXBException ex) {
47 throw new ProcessingException(ex);
48 }
49 }
50
51 public static <T> T unmarshal(String string, Class<T> type) {
52 if (string==null || string.isEmpty()) {
53 return null;
54 }
55 return unmarshall(new ByteArrayInputStream(string.getBytes()), type);
56 }
57
58 public static <T> T unmarshall(InputStream is, Class<T> type) {
59 if (is==null) {
60 return null;
61 }
62
63 try {
64 JAXBContext jbx = getInstance().getContext(type);
65 Unmarshaller unmarshaller = jbx.createUnmarshaller();
66 @SuppressWarnings("unchecked")
67 T object = (T) unmarshaller.unmarshal(is);
68 return object;
69 } catch (JAXBException ex) {
70 throw new ProcessingException(ex);
71 }
72 }
73 }