View Javadoc
1   package cn.home1.oss.lib.common;
2   
3   import static com.google.common.collect.Maps.newLinkedHashMap;
4   import static java.lang.Boolean.FALSE;
5   import static java.lang.Boolean.TRUE;
6   
7   import lombok.NoArgsConstructor;
8   import lombok.SneakyThrows;
9   
10  import org.joda.time.DateTime;
11  import org.springframework.oxm.jaxb.Jaxb2Marshaller;
12  
13  import java.io.StringReader;
14  import java.util.Map;
15  
16  import javax.xml.bind.JAXBElement;
17  import javax.xml.bind.Marshaller;
18  import javax.xml.bind.annotation.adapters.XmlAdapter;
19  import javax.xml.transform.stream.StreamSource;
20  
21  
22  public final class JaxbUtils {
23  
24    private JaxbUtils() {
25    }
26  
27    /**
28     * jaxb2 marshaller.
29     *
30     * @return jaxb2 marshaller
31     */
32    public static Jaxb2Marshaller jaxb2Marshaller() {
33      final Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
34      // marshaller.setPackagesToScan("");
35      final Map<String, Object> properties = newLinkedHashMap();
36      properties.put(Marshaller.JAXB_ENCODING, Defaults.UTF_8.name());
37      properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, FALSE);
38      properties.put(Marshaller.JAXB_FRAGMENT, TRUE);
39      marshaller.setMarshallerProperties(properties);
40      return marshaller;
41    }
42  
43    /**
44     * unmarshal.
45     *
46     * @param marshaller marshaller
47     * @param xml        xml
48     * @param type       type
49     * @param <T>        type
50     * @return object
51     */
52    @SneakyThrows
53    public static <T> T unmarshal(final Jaxb2Marshaller marshaller, final String xml,
54      final Class<T> type) {
55      final JAXBElement<T> element = marshaller.getJaxbContext().createUnmarshaller()
56        .unmarshal(new StreamSource(new StringReader(xml)), type);
57      return element.getValue();
58    }
59  
60    @NoArgsConstructor
61    public static class DatimeAdapter extends XmlAdapter<String, DateTime> {
62  
63      @Override
64      public DateTime unmarshal(String s) throws Exception {
65        return new DateTime(s, Defaults.UTC_P8);
66      }
67  
68      @Override
69      public String marshal(DateTime date) throws Exception {
70        return Defaults.ISO8601.print(date);
71      }
72    }
73  }