1 7 8 package org.dom4j.jaxb; 9 10 import java.io.StringReader ; 11 12 import javax.xml.bind.JAXBContext; 13 import javax.xml.bind.JAXBException; 14 import javax.xml.bind.Marshaller; 15 import javax.xml.bind.Unmarshaller; 16 import javax.xml.transform.Source ; 17 import javax.xml.transform.stream.StreamSource ; 18 19 import org.dom4j.dom.DOMDocument; 20 21 26 abstract class JAXBSupport { 27 private String contextPath; 28 29 private ClassLoader classloader; 30 31 private JAXBContext jaxbContext; 32 33 private Marshaller marshaller; 34 35 private Unmarshaller unmarshaller; 36 37 public JAXBSupport(String contextPath) { 38 this.contextPath = contextPath; 39 } 40 41 public JAXBSupport(String contextPath, ClassLoader classloader) { 42 this.contextPath = contextPath; 43 this.classloader = classloader; 44 } 45 46 58 protected org.dom4j.Element marshal(javax.xml.bind.Element element) 59 throws JAXBException { 60 DOMDocument doc = new DOMDocument(); 61 getMarshaller().marshal(element, doc); 62 63 return doc.getRootElement(); 64 } 65 66 78 protected javax.xml.bind.Element unmarshal(org.dom4j.Element element) 79 throws JAXBException { 80 Source source = new StreamSource (new StringReader (element.asXML())); 81 82 return (javax.xml.bind.Element) getUnmarshaller().unmarshal(source); 83 } 84 85 private Marshaller getMarshaller() throws JAXBException { 86 if (marshaller == null) { 87 marshaller = getContext().createMarshaller(); 88 } 89 90 return marshaller; 91 } 92 93 private Unmarshaller getUnmarshaller() throws JAXBException { 94 if (unmarshaller == null) { 95 unmarshaller = getContext().createUnmarshaller(); 96 } 97 98 return unmarshaller; 99 } 100 101 private JAXBContext getContext() throws JAXBException { 102 if (jaxbContext == null) { 103 if (classloader == null) { 104 jaxbContext = JAXBContext.newInstance(contextPath); 105 } else { 106 jaxbContext = JAXBContext.newInstance(contextPath, classloader); 107 } 108 } 109 110 return jaxbContext; 111 } 112 } 113 114 150 | Popular Tags |