View Javadoc
1   package org.kuali.ole.ncip.converter;
2   
3   import org.codehaus.jackson.map.ObjectMapper;
4   import org.slf4j.Logger;
5   import org.slf4j.LoggerFactory;
6   
7   import javax.xml.bind.JAXBContext;
8   import javax.xml.bind.JAXBElement;
9   import javax.xml.bind.JAXBException;
10  import javax.xml.bind.Unmarshaller;
11  import javax.xml.stream.XMLInputFactory;
12  import javax.xml.stream.XMLStreamReader;
13  import java.io.IOException;
14  import java.io.StringReader;
15  
16  /**
17   * Created with IntelliJ IDEA.
18   * User: maheswarang
19   * Date: 9/2/13
20   * Time: 4:38 PM
21   * To change this template use File | Settings | File Templates.
22   */
23  public class OleCirculationHandler {
24      private XMLInputFactory xmlInputFactory;
25      private static final Logger LOG             = LoggerFactory.getLogger(OleCirculationHandler.class);
26      public Object unmarshalXMLContent(Class clazz, String content) {
27          Object unmarshaledObject = null;
28          try {
29              JAXBContext jaxbContext = JAXBContextFactory.getJAXBContextForClass(clazz);
30              Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
31              XMLInputFactory xmlInputFactory = getXmlInputFactory();
32              XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(content));
33              unmarshaledObject = jaxbUnmarshaller.unmarshal(xmlStreamReader);
34          } catch (Exception e) {
35              LOG.error(e.getMessage(), e);
36              throw new RuntimeException(e);
37          }
38          if (unmarshaledObject instanceof JAXBElement) {
39              return ((JAXBElement) unmarshaledObject).getValue();
40          }
41          return unmarshaledObject;
42      }
43  
44      /*public String marshalToJSON(Object object) throws JAXBException {
45          JsonBuilder jsonBuilder = new JsonBuilder(object);
46          return jsonBuilder.toPrettyString();
47      }*/
48  
49      public String marshalToJSON(Object object) throws JAXBException, IOException {
50          ObjectMapper objectMapper = new ObjectMapper();
51          return objectMapper.defaultPrettyPrintingWriter().writeValueAsString(object);
52      }
53  
54      private XMLInputFactory getXmlInputFactory() {
55          if (null == xmlInputFactory) {
56              xmlInputFactory = XMLInputFactory.newInstance();
57          }
58          return xmlInputFactory;
59      }
60  }