01: /*
02: * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
03: * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
04: */
05:
06: package javax.xml.bind.annotation;
07:
08: import org.w3c.dom.Document;
09: import org.w3c.dom.DocumentFragment;
10: import org.w3c.dom.Element;
11: import org.w3c.dom.Node;
12:
13: import javax.xml.bind.ValidationEventHandler;
14: import javax.xml.parsers.DocumentBuilder;
15: import javax.xml.transform.Source;
16: import javax.xml.transform.dom.DOMResult;
17: import javax.xml.transform.dom.DOMSource;
18:
19: /**
20: * {@link DomHandler} implementation for W3C DOM (<code>org.w3c.dom</code> package.)
21: *
22: * @author Kohsuke Kawaguchi
23: * @since JAXB2.0
24: */
25: public class W3CDomHandler implements DomHandler<Element, DOMResult> {
26:
27: private DocumentBuilder builder;
28:
29: /**
30: * Default constructor.
31: *
32: * It is up to a JAXB provider to decide which DOM implementation
33: * to use or how that is configured.
34: */
35: public W3CDomHandler() {
36: this .builder = null;
37: }
38:
39: /**
40: * Constructor that allows applications to specify which DOM implementation
41: * to be used.
42: *
43: * @param builder
44: * must not be null. JAXB uses this {@link DocumentBuilder} to create
45: * a new element.
46: */
47: public W3CDomHandler(DocumentBuilder builder) {
48: if (builder == null)
49: throw new IllegalArgumentException();
50: this .builder = builder;
51: }
52:
53: public DocumentBuilder getBuilder() {
54: return builder;
55: }
56:
57: public void setBuilder(DocumentBuilder builder) {
58: this .builder = builder;
59: }
60:
61: public DOMResult createUnmarshaller(
62: ValidationEventHandler errorHandler) {
63: if (builder == null)
64: return new DOMResult();
65: else
66: return new DOMResult(builder.newDocument());
67: }
68:
69: public Element getElement(DOMResult r) {
70: // JAXP spec is ambiguous about what really happens in this case,
71: // so work defensively
72: Node n = r.getNode();
73: if (n instanceof Document) {
74: return ((Document) n).getDocumentElement();
75: }
76: if (n instanceof Element)
77: return (Element) n;
78: if (n instanceof DocumentFragment)
79: return (Element) n.getChildNodes().item(0);
80:
81: // if the result object contains something strange,
82: // it is not a user problem, but it is a JAXB provider's problem.
83: // That's why we throw a runtime exception.
84: throw new IllegalStateException(n.toString());
85: }
86:
87: public Source marshal(Element element,
88: ValidationEventHandler errorHandler) {
89: return new DOMSource(element);
90: }
91: }
|