01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.cocoon.xml;
18:
19: import org.apache.cocoon.xml.dom.DOMStreamer;
20: import org.w3c.dom.Document;
21: import org.w3c.dom.Node;
22: import org.xml.sax.ContentHandler;
23: import org.xml.sax.SAXException;
24:
25: import javax.xml.parsers.DocumentBuilder;
26: import javax.xml.parsers.DocumentBuilderFactory;
27: import javax.xml.parsers.ParserConfigurationException;
28:
29: /**
30: * Abstract implementation of {@link XMLFragment} for objects that are more
31: * easily represented as a DOM.
32: *
33: * <p>The {@link #toSAX} method is implemented by streaming (using a
34: * {@link DOMStreamer}) the results of the {@link #toDOM(Node)} that must be
35: * implemented by concrete subclasses.</p>
36: *
37: * @author <a href="mailto:sylvain.wallez@anyware-tech.com">Sylvain Wallez</a>
38: * @version CVS $Id: AbstractDOMFragment.java 433543 2006-08-22 06:22:54Z crossley $
39: */
40: public abstract class AbstractDOMFragment implements XMLFragment {
41:
42: /**
43: * Generates SAX events representing the object's state by serializing the
44: * result of <code>toDOM()</code>.
45: */
46: public void toSAX(ContentHandler handler) throws SAXException {
47: // The ComponentManager is unknown here : use JAXP to create a document
48: DocumentBuilder builder;
49: try {
50: builder = DocumentBuilderFactory.newInstance()
51: .newDocumentBuilder();
52: } catch (ParserConfigurationException e) {
53: throw new SAXException("Couldn't get a DocumentBuilder", e);
54: }
55:
56: Document doc = builder.newDocument();
57:
58: // Create a DocumentFragment that will hold the results of toDOM()
59: // (which can create several top-level elements)
60: Node df = doc.createDocumentFragment();
61:
62: // Build the DOM representation of this object
63: try {
64: toDOM(df);
65: } catch (Exception e) {
66: throw new SAXException(
67: "Exception while converting object to DOM", e);
68: }
69:
70: // Stream the document fragment
71: handler.startDocument();
72: new DOMStreamer(handler).stream(df);
73: handler.endDocument();
74: }
75: }
|