1 17 18 19 20 package org.apache.fop.util; 21 22 import javax.xml.transform.TransformerConfigurationException ; 23 import javax.xml.transform.dom.DOMResult ; 24 import javax.xml.transform.sax.SAXTransformerFactory ; 25 import javax.xml.transform.sax.TransformerHandler ; 26 27 import org.w3c.dom.DOMImplementation ; 28 import org.w3c.dom.Document ; 29 import org.xml.sax.Attributes ; 30 import org.xml.sax.ContentHandler ; 31 import org.xml.sax.SAXException ; 32 33 36 public class DOMBuilderContentHandlerFactory implements ContentHandlerFactory { 37 38 private static SAXTransformerFactory tFactory 39 = (SAXTransformerFactory )SAXTransformerFactory.newInstance(); 40 41 private String namespaceURI; 42 private DOMImplementation domImplementation; 43 44 49 public DOMBuilderContentHandlerFactory(String namespaceURI, 50 DOMImplementation domImplementation) { 51 this.namespaceURI = namespaceURI; 52 this.domImplementation = domImplementation; 53 } 54 55 56 public String [] getSupportedNamespaces() { 57 return new String [] {namespaceURI}; 58 } 59 60 61 public ContentHandler createContentHandler() throws SAXException { 62 return new Handler (); 63 } 64 65 private class Handler extends DelegatingContentHandler 66 implements ContentHandlerFactory.ObjectSource { 67 68 private Document doc; 69 private ObjectBuiltListener obListener; 70 71 public Handler() throws SAXException { 72 super(); 73 } 74 75 public Document getDocument() { 76 return this.doc; 77 } 78 79 82 public Object getObject() { 83 return getDocument(); 84 } 85 86 89 public void setObjectBuiltListener(ObjectBuiltListener listener) { 90 this.obListener = listener; 91 } 92 93 96 public void startDocument() throws SAXException { 97 if (doc != null) { 99 super.startDocument(); 100 } 101 } 102 103 106 public void startElement(String uri, String localName, String qName, Attributes atts) 107 throws SAXException { 108 if (doc == null) { 109 TransformerHandler handler; 110 try { 111 handler = tFactory.newTransformerHandler(); 112 } catch (TransformerConfigurationException e) { 113 throw new SAXException ("Error creating a new TransformerHandler", e); 114 } 115 doc = domImplementation.createDocument(namespaceURI, qName, null); 116 doc.removeChild(doc.getDocumentElement()); 118 handler.setResult(new DOMResult (doc)); 119 setDelegateContentHandler(handler); 120 setDelegateLexicalHandler(handler); 121 setDelegateDTDHandler(handler); 122 handler.startDocument(); 123 } 124 super.startElement(uri, localName, qName, atts); 125 } 126 127 130 public void endDocument() throws SAXException { 131 super.endDocument(); 132 if (obListener != null) { 133 obListener.notifyObjectBuilt(getObject()); 134 } 135 } 136 137 } 138 139 } 140 | Popular Tags |