View Javadoc
1   package ejava.util.jaxb;
2   
3   import java.io.ByteArrayInputStream;
4   import java.io.InputStream;
5   import java.io.StringWriter;
6   
7   import javax.xml.bind.JAXBContext;
8   import javax.xml.bind.JAXBException;
9   import javax.xml.bind.Marshaller;
10  import javax.xml.bind.Unmarshaller;
11  
12  public class JAXBUtil {
13      public static <T> String marshal(T object) {
14          try {
15              return marshalThrows(object);
16          } catch (JAXBException ex) {
17              return null;
18          }
19      }
20      
21      public static <T> String marshalThrows(T object) throws JAXBException {
22          if (object==null) {
23              return null;
24          }
25  
26          JAXBContext jbx = JAXBContext.newInstance(object.getClass());
27          Marshaller marshaller = jbx.createMarshaller();
28          marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
29          StringWriter writer = new StringWriter();
30          marshaller.marshal(object, writer);
31          return writer.toString();        
32      }
33      
34      public static <T> T unmarshal(String string, Class<T> type) {
35          try {
36              return unmarshalThrows(string, type);
37          } catch (JAXBException ex) {
38              return null;
39          }
40      }
41      
42      public static <T> T unmarshal(InputStream is, Class<T> type) {
43          try {
44              return unmarshalThrows(is, type);
45          } catch (JAXBException ex) {
46              return null;
47          }        
48      }
49      
50      public static <T> T unmarshalThrows(String string, Class<T> type) throws JAXBException {
51          if (string==null || string.isEmpty()) {
52              return null;
53          }
54          return unmarshalThrows(new ByteArrayInputStream(string.getBytes()), type);
55      }
56  
57      public static <T> T unmarshalThrows(InputStream is, Class<T> type) throws JAXBException {
58          if (is==null) {
59              return null;
60          }
61  
62          JAXBContext jbx = JAXBContext.newInstance(type);
63          Unmarshaller unmarshaller = jbx.createUnmarshaller();
64          @SuppressWarnings("unchecked")
65          T object = (T) unmarshaller.unmarshal(is);
66          return object;
67      }
68  
69  }