View Javadoc
1   package org.kuali.ole.docstore.discovery.circulation;
2   
3   import org.codehaus.jackson.map.ObjectMapper;
4   import groovy.json.JsonBuilder;
5   import org.slf4j.Logger;
6   import org.slf4j.LoggerFactory;
7   
8   import javax.xml.bind.JAXBContext;
9   import javax.xml.bind.JAXBElement;
10  import javax.xml.bind.JAXBException;
11  import javax.xml.bind.Unmarshaller;
12  import javax.xml.stream.XMLInputFactory;
13  import javax.xml.stream.XMLStreamReader;
14  import java.io.IOException;
15  import java.io.StringReader;
16  
17  /**
18   * Created with IntelliJ IDEA.
19   * User: pvsubrah
20   * Date: 5/22/13
21   * Time: 10:32 AM
22   * To change this template use File | Settings | File Templates.
23   */
24  public class XmlContentHandler {
25      private XMLInputFactory xmlInputFactory;
26      private static final Logger LOG             = LoggerFactory.getLogger(XmlContentHandler.class);
27      public Object unmarshalXMLContent(Class clazz, String content) {
28          Object unmarshaledObject = null;
29          try {
30              JAXBContext jaxbContext = JAXBContextFactory.getJAXBContextForClass(clazz);
31              Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
32              XMLInputFactory xmlInputFactory = getXmlInputFactory();
33              XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(content));
34              unmarshaledObject = jaxbUnmarshaller.unmarshal(xmlStreamReader);
35          } catch (Exception e) {
36              LOG.error(e.getMessage(), 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, IOException {
45          ObjectMapper objectMapper = new ObjectMapper();
46          return objectMapper.defaultPrettyPrintingWriter().writeValueAsString(object);
47      }
48  
49      private XMLInputFactory getXmlInputFactory() {
50          if (null == xmlInputFactory) {
51              xmlInputFactory = XMLInputFactory.newInstance();
52          }
53          return xmlInputFactory;
54      }
55  }