1 package org.kuali.ole.ncip.converter;
2
3 import groovy.json.JsonBuilder;
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.StringReader;
14
15
16
17
18
19
20
21
22 public class OleCirculationHandler {
23 private XMLInputFactory xmlInputFactory;
24 private static final Logger LOG = LoggerFactory.getLogger(OleCirculationHandler.class);
25 public Object unmarshalXMLContent(Class clazz, String content) {
26 Object unmarshaledObject = null;
27 try {
28 JAXBContext jaxbContext = JAXBContextFactory.getJAXBContextForClass(clazz);
29 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
30 XMLInputFactory xmlInputFactory = getXmlInputFactory();
31 XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(content));
32 unmarshaledObject = jaxbUnmarshaller.unmarshal(xmlStreamReader);
33 } catch (Exception e) {
34 LOG.error(e.getMessage(), e);
35 throw new RuntimeException(e);
36 }
37 if (unmarshaledObject instanceof JAXBElement) {
38 return ((JAXBElement) unmarshaledObject).getValue();
39 }
40 return unmarshaledObject;
41 }
42
43 public String marshalToJSON(Object object) throws JAXBException {
44 JsonBuilder jsonBuilder = new JsonBuilder(object);
45 return jsonBuilder.toPrettyString();
46 }
47
48 private XMLInputFactory getXmlInputFactory() {
49 if (null == xmlInputFactory) {
50 xmlInputFactory = XMLInputFactory.newInstance();
51 }
52 return xmlInputFactory;
53 }
54 }