01: package com.sun.xml.xsom.util;
02:
03: import com.sun.xml.xsom.XSAnnotation;
04: import com.sun.xml.xsom.parser.AnnotationContext;
05: import com.sun.xml.xsom.parser.AnnotationParser;
06: import com.sun.xml.xsom.parser.AnnotationParserFactory;
07: import org.w3c.dom.Document;
08: import org.w3c.dom.Element;
09: import org.w3c.dom.Node;
10: import org.xml.sax.ContentHandler;
11: import org.xml.sax.EntityResolver;
12: import org.xml.sax.ErrorHandler;
13:
14: import javax.xml.transform.TransformerConfigurationException;
15: import javax.xml.transform.dom.DOMResult;
16: import javax.xml.transform.sax.SAXTransformerFactory;
17: import javax.xml.transform.sax.TransformerHandler;
18:
19: /**
20: * {@link AnnotationParserFactory} that parses annotations into a W3C DOM.
21: *
22: * <p>
23: * If you use this parser factory, you'll get {@link Element} that represents
24: * <xs:annotation> from {@link XSAnnotation#getAnnotation()}.
25: *
26: * <p>
27: * When multiple <xs:annotation>s are found for the given schema component,
28: * you'll see all <xs:appinfo>s and <xs:documentation>s combined under
29: * one <xs:annotation> element.
30: *
31: * @author Kohsuke Kawaguchi
32: */
33: public class DomAnnotationParserFactory implements
34: AnnotationParserFactory {
35: public AnnotationParser create() {
36: return new AnnotationParserImpl();
37: }
38:
39: private static final SAXTransformerFactory stf = (SAXTransformerFactory) SAXTransformerFactory
40: .newInstance();
41:
42: private static class AnnotationParserImpl extends AnnotationParser {
43:
44: /**
45: * Identity transformer used to parse SAX into DOM.
46: */
47: private final TransformerHandler transformer;
48: private DOMResult result;
49:
50: AnnotationParserImpl() {
51: try {
52: transformer = stf.newTransformerHandler();
53: } catch (TransformerConfigurationException e) {
54: throw new Error(e); // impossible
55: }
56: }
57:
58: public ContentHandler getContentHandler(
59: AnnotationContext context, String parentElementName,
60: ErrorHandler errorHandler, EntityResolver entityResolver) {
61: result = new DOMResult();
62: transformer.setResult(result);
63: return transformer;
64: }
65:
66: public Object getResult(Object existing) {
67: Document dom = (Document) result.getNode();
68: Element e = dom.getDocumentElement();
69: if (existing instanceof Element) {
70: // merge all the children
71: Element prev = (Element) existing;
72: Node anchor = e.getFirstChild();
73: while (prev.getFirstChild() != null) {
74: Node move = prev.getFirstChild();
75: e.insertBefore(
76: e.getOwnerDocument().adoptNode(move),
77: anchor);
78: }
79: }
80: return e;
81: }
82: }
83: }
|