1
2
3
4
5
6
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 /***
22 * DOCUMENT ME!
23 *
24 * @author Wonne Keysers (Realsoftware.be)
25 */
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 /***
47 * Marshals the given {@link javax.xml.bind.Element}in to its DOM4J
48 * counterpart.
49 *
50 * @param element
51 * JAXB Element to be marshalled
52 *
53 * @return the marshalled DOM4J {@link org.dom4j.Element}
54 *
55 * @throws JAXBException
56 * when an error occurs
57 */
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 /***
67 * Unmarshalls the specified DOM4J {@link org.dom4j.Element}into a {@link
68 * javax.xml.bind.Element}
69 *
70 * @param element
71 * the DOM4J element to unmarshall
72 *
73 * @return the unmarshalled JAXB object
74 *
75 * @throws JAXBException
76 * when an error occurs
77 */
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
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
148
149