1
2
3
4
5
6
7
8
9
10 package org.dom4j.jaxb;
11
12 import java.io.StringReader;
13
14 import javax.xml.bind.JAXBContext;
15 import javax.xml.bind.JAXBException;
16 import javax.xml.bind.Marshaller;
17 import javax.xml.bind.Unmarshaller;
18 import javax.xml.transform.Source;
19 import javax.xml.transform.stream.StreamSource;
20
21 import org.dom4j.dom.DOMDocument;
22
23 /***
24 * @author Wonne Keysers (Realsoftware.be)
25 */
26 abstract class JAXBSupport {
27
28 private String contextPath;
29 private ClassLoader classloader;
30
31 private JAXBContext jaxbContext;
32 private Marshaller marshaller;
33 private Unmarshaller unmarshaller;
34
35 public JAXBSupport(String contextPath) {
36 this.contextPath = contextPath;
37 }
38
39 public JAXBSupport(String contextPath, ClassLoader classloader) {
40 this.contextPath = contextPath;
41 this.classloader = classloader;
42 }
43
44 /***
45 * Marshals the given {@link javax.xml.bind.Element} in to its DOM4J counterpart.
46 *
47 * @param element JAXB Element to be marshalled
48 * @return the marshalled DOM4J {@link org.dom4j.Element}
49 * @throws JAXBException when an error occurs
50 */
51 protected org.dom4j.Element marshal(javax.xml.bind.Element element) throws JAXBException {
52 Marshaller marshaller = getMarshaller();
53
54 DOMDocument doc = new DOMDocument();
55 marshaller.marshal(element, doc);
56
57 return doc.getRootElement();
58 }
59
60 /***
61 * Unmarshalls the specified DOM4J {@link org.dom4j.Element} into a {@link javax.xml.bind.Element}
62 * @param element the DOM4J element to unmarshall
63 * @return the unmarshalled JAXB object
64 * @throws JAXBException when an error occurs
65 */protected javax.xml.bind.Element unmarshal(org.dom4j.Element element) throws JAXBException {
66 Unmarshaller unmarshaller = getUnmarshaller();
67
68 Source source = new StreamSource(new StringReader(element.asXML()));
69
70 return (javax.xml.bind.Element) unmarshaller.unmarshal(source);
71 }
72
73 private Marshaller getMarshaller() throws JAXBException {
74 if (marshaller == null) {
75 marshaller = getContext().createMarshaller();
76 }
77 return marshaller;
78 }
79
80 private Unmarshaller getUnmarshaller() throws JAXBException {
81 if (unmarshaller == null) {
82 unmarshaller = getContext().createUnmarshaller();
83 }
84 return unmarshaller;
85 }
86
87 private JAXBContext getContext() throws JAXBException {
88 if (jaxbContext == null) {
89 if (classloader == null) {
90 jaxbContext = JAXBContext.newInstance(contextPath);
91 }
92 else {
93 jaxbContext = JAXBContext.newInstance(contextPath, classloader);
94 }
95 }
96 return jaxbContext;
97 }
98
99 }
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147