KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xquark > util > DOMReader


1 /*
2  * This file belongs to the XQuark distribution.
3  * Copyright (C) 2003 Universite de Versailles Saint-Quentin.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307.
18  * You can also get it at http://www.gnu.org/licenses/lgpl.html
19  *
20  * For more information on this software, see http://www.xquark.org.
21  */

22
23 package org.xquark.util;
24
25 import java.io.IOException JavaDoc;
26 import java.util.Iterator JavaDoc;
27
28 import org.w3c.dom.*;
29 import org.xml.sax.*;
30 import org.xml.sax.ext.LexicalHandler JavaDoc;
31
32 /**
33  * Define a DOM-tree walker that produces SAX events.
34  *
35  * <p><B> WARNING : DOM must support namespaces !!!</p>
36  * <p>Special Feature:</p>
37  * <code>http://wwww.xquark.org/sax/features/fragment</code> disables SAX
38  * startDocument() and endDocument() events triggering
39  *
40  * @see org.xml.sax.XMLReader, org.w3c.dom.Element
41  */

42 public class DOMReader implements XMLReader, Locator, SAXConstants
43 {
44     private static final String JavaDoc RCSRevision = "$Revision: 1.3 $";
45     private static final String JavaDoc RCSName = "$Name: $";
46     
47     protected boolean fragment = false;
48     /**
49      * The DOM document or element that will be parsed.
50      */

51     protected Node root;
52     
53     /**
54      * The actual ContentHandler
55      */

56     protected ContentHandler contentHandler = null;
57     
58     /**
59      * The actual DTDHandler
60      */

61     protected DTDHandler dtdHandler = null;
62     
63     /**
64      * The actual ErrorHandler
65      */

66     protected ErrorHandler errorHandler = null;
67     
68     /**
69      * The actual EntityResolver
70      */

71     protected EntityResolver entityResolver = null;
72     
73     /**
74      * The actual LexicalHandler
75      */

76     protected LexicalHandler JavaDoc lexicalHandler = null;
77     
78     /**
79      * The DOM to SAX wrapper used for attributes
80      */

81     protected DOM2SAXAttrs wAtts = new DOM2SAXAttrs();
82     
83     public DOMReader(){}
84     
85     public DOMReader(Document doc)
86     {setDocument(doc);} // SR 25/08/2000 Better customize contructor than overload XMLReader interface.
87

88     public DOMReader(Element root)
89     {setRoot(root);} // SR 25/08/2000 Better customize contructor than overload XMLReader interface.
90

91     public void setDocument(Document doc)
92     {this.root = doc;}
93     
94     public void setRoot(Node root)
95     {this.root = root;}
96     
97     public ContentHandler getContentHandler()
98     {
99         return contentHandler;
100     }
101     
102     public DTDHandler getDTDHandler()
103     {
104         return dtdHandler;
105     }
106     
107     public EntityResolver getEntityResolver()
108     {
109         return entityResolver;
110     }
111     
112     public ErrorHandler getErrorHandler()
113     {
114         return errorHandler;
115     }
116     
117     public boolean getFeature(String JavaDoc name)
118     throws SAXNotRecognizedException,
119     SAXNotSupportedException
120     {
121         if (name.equals(FRAGMENT_FEATURE))
122             return fragment;
123         if (name.equals(SAX_NAMESPACE_FEATURE))
124             return true;
125         if (name.equals(SAX_PREFIX_FEATURE))
126             return false;
127         throw new SAXNotRecognizedException("Don't recognize feature \""+name+"\"");
128     }
129     
130     /**
131      * Return the current lexical handler used by this object
132      */

133 /* SR 28/08/2000 : Not in XMLReader interface. Use GetProperty and SetProperty
134         public LexicalHandler getLexicalHandler()
135         {
136                 return lexicalHandler;
137         }
138  */

139     public Object JavaDoc getProperty(String JavaDoc name)
140     throws SAXNotRecognizedException,
141     SAXNotSupportedException
142     {
143         if (name.equals(SAX_LEXICAL_PROPERTY))
144             return lexicalHandler;
145         else
146             throw new SAXNotRecognizedException("Property \""+name+"\" not recognized");
147     }
148     
149     public void parse(InputSource input) // SR 25/08/2000 To be full SAX XMLReader compliant : see constructor.
150
throws SAXException,
151     IOException JavaDoc
152     {
153         // input source is ignored
154
parse("");
155     }
156     
157     public void parse(String JavaDoc systemId)
158     throws SAXException,
159     IOException JavaDoc
160     {
161         // systemId is ignored
162
if ((contentHandler != null) && !fragment)
163         {
164             contentHandler.setDocumentLocator(this);
165             contentHandler.startDocument();
166         }
167         if (root == null)
168             throw new SAXException("A DOM document or element must be provided.");
169         else
170         {
171             switch (root.getNodeType())
172             {
173                 case Node.ELEMENT_NODE:
174                 // add 06/06/2003
175
case Node.TEXT_NODE:
176                     parseNode(root);
177                     break;
178                 case Node.DOCUMENT_FRAGMENT_NODE:
179                 case Node.DOCUMENT_NODE:
180                     parseChildNodes(root);
181                     break;
182                 default:
183                     throw new SAXException("The root node provided for browsing must be an Element, a Document or a Document fragment.");
184             }
185             if ((contentHandler != null) && !fragment)
186                 contentHandler.endDocument();
187         }
188     }
189         
190     /**
191      * Parse Node childs and report their content in the ContentHandler.
192      *
193      * @param node the node
194      */

195     protected void parseChildNodes(Node node) throws SAXException {
196         NodeList nl=node.getChildNodes();
197         int nbchilds=nl.getLength();
198         for (int i=0; i<nbchilds; i++)
199             parseNode(nl.item(i));
200     }
201     
202     /**
203      * Parse a Node and report is content in the ContentHandler.
204      *
205      * @param node the node to parse
206      */

207     protected void parseNode(Node node) throws SAXException {
208         switch (node.getNodeType())
209         {
210             case Node.ELEMENT_NODE:
211                 if (contentHandler != null) {
212                     generateStartElement(node);
213                 }
214                 parseChildNodes(node);
215                 if (contentHandler != null)
216                 {
217                     generateEndElement(node);
218                 }
219                 break;
220             case Node.PROCESSING_INSTRUCTION_NODE:
221                 if (contentHandler != null)
222                     generateProcessingInstruction(node);
223                 break;
224             case Node.TEXT_NODE:
225                 if (contentHandler != null)
226                     generateText(node);
227                 break;
228             case Node.CDATA_SECTION_NODE:
229                 if (contentHandler != null)
230                     generateCDataSection(node);
231                 break;
232             case Node.COMMENT_NODE:
233                 if (lexicalHandler != null)
234                     generateComment(node);
235                 break;
236             case Node.ENTITY_REFERENCE_NODE:
237                 if (contentHandler != null)
238                     generateEntityReference(node);
239                 break;
240             case Node.DOCUMENT_FRAGMENT_NODE:
241             case Node.DOCUMENT_NODE:
242             case Node.DOCUMENT_TYPE_NODE:
243             case Node.ENTITY_NODE:
244             case Node.NOTATION_NODE:
245             case Node.ATTRIBUTE_NODE:
246                 break;
247         }
248     }
249     
250     protected void generateStartElement(Node node) throws SAXException {
251         String JavaDoc uri = node.getNamespaceURI();
252         if (uri == null) uri = "";
253         String JavaDoc local = node.getLocalName();
254         if (local == null) local = "";
255         String JavaDoc prefix = node.getPrefix();
256         String JavaDoc qname = prefix == null ? local : prefix + ":" +local;
257         // OPTIM SR 23/05/2001 DOMAttributes atts=null;
258
wAtts.setDOMAttributes(node.getAttributes());
259         Iterator JavaDoc it = wAtts.getPrefixIterator(); // OPTIM SR 23/05/2001
260
if (it != null)
261             while (it.hasNext()) {
262                 Attr a = (Attr)it.next();
263                 contentHandler.startPrefixMapping(
264                 a.getLocalName().equals(XMLNS_PREFIX) ? "": a.getLocalName(), // default prefix
265
a.getValue());
266             }
267         contentHandler.startElement(uri, local, qname, wAtts);
268     }
269     
270     protected void generateEndElement(Node node) throws SAXException {
271         String JavaDoc uri = node.getNamespaceURI();
272         if (uri == null) uri = "";
273         String JavaDoc local = node.getLocalName();
274         if (local == null) local = "";
275         String JavaDoc prefix = node.getPrefix();
276         String JavaDoc qname = prefix == null ? local : prefix + ":" +local;
277         contentHandler.endElement(uri, local, qname);
278         // Need to reset wAtts after recursive call to parseChildNodes
279
wAtts.setDOMAttributes(node.getAttributes());
280         Iterator JavaDoc it = wAtts.getPrefixIterator(); // OPTIM SR 23/05/2001
281
if (it != null)
282             // WARNING : endPrefixMapping ordered has not been reversed
283
while (it.hasNext()) {
284                 Attr a = (Attr)it.next();
285                 contentHandler.endPrefixMapping(a.getLocalName().equals(XMLNS_PREFIX) ? "": a.getLocalName());
286             }
287     }
288
289     protected void generateProcessingInstruction(Node node) throws SAXException {
290         contentHandler.processingInstruction(node.getNodeName(), node.getNodeValue());
291     }
292     
293     protected void generateText(Node node) throws SAXException {
294         String JavaDoc value = node.getNodeValue();
295         if (value != null)
296             contentHandler.characters(value.toCharArray(), 0, value.length());
297     }
298     
299     protected void generateComment(Node node) throws SAXException {
300         String JavaDoc value = node.getNodeValue();
301         if (value != null)
302             lexicalHandler.comment(value.toCharArray(), 0, value.length());
303     }
304     
305     protected void generateCDataSection(Node node) throws SAXException {
306         if (lexicalHandler != null) lexicalHandler.startCDATA();
307         String JavaDoc value = node.getNodeValue();
308         if (value != null)
309             contentHandler.characters(value.toCharArray(), 0, value.length());
310         if (lexicalHandler != null) lexicalHandler.endCDATA();
311     }
312     
313     protected void generateEntityReference(Node node) throws SAXException {
314         contentHandler.skippedEntity(node.getNodeName());
315     }
316     
317     public void setContentHandler(ContentHandler handler)
318     {
319         contentHandler = handler;
320     }
321     
322     public void setDTDHandler(DTDHandler handler)
323     {
324         dtdHandler = handler;
325     }
326     
327     public void setEntityResolver(EntityResolver resolver)
328     {
329         entityResolver = resolver;
330     }
331     
332     public void setErrorHandler(ErrorHandler handler)
333     {
334         errorHandler = handler;
335     }
336     
337     public void setFeature(String JavaDoc name, boolean value)
338     throws SAXNotRecognizedException,
339     SAXNotSupportedException
340     {
341         if (name.equals(FRAGMENT_FEATURE))
342             fragment = value;
343         else if (name.equals(SAX_NAMESPACE_FEATURE))
344         {
345             if (!value)
346                 throw new SAXNotSupportedException
347                 ("Feature: \""
348                 + name
349                 + "="
350                 + value
351                 + "\" not supported");
352         }
353         else if (name.equals(SAX_PREFIX_FEATURE))
354         {
355             if (value)
356                 throw new SAXNotSupportedException
357                 ("Feature: \""
358                 + name
359                 + "="
360                 + value
361                 + "\" not supported");
362         }
363         else
364             throw new SAXNotRecognizedException("Feature \""+name+"\" not recognized.");
365     }
366     
367     /**
368      * Set the current lexical handler
369      */

370 /* SR 28/08/2000 : Not in XMLReader interface. Use GetProperty and SetProperty
371         public void setLexicalHandler (LexicalHandler handler)
372         {
373                 lexicalHandler=handler;
374         }
375  */

376     public void setProperty(String JavaDoc name, Object JavaDoc value)
377     throws SAXNotRecognizedException,
378     SAXNotSupportedException
379     {
380         if (name.equals("http://xml.org/sax/properties/lexical-handler"))
381             lexicalHandler = (LexicalHandler JavaDoc)value;
382         else
383             throw new SAXNotRecognizedException("Don't recognize property \""+name+"\"");
384     }
385     
386     public int getColumnNumber()
387     { return -1; }
388     
389     public int getLineNumber()
390     { return -1; }
391     
392     public String JavaDoc getPublicId()
393     { return null; }
394     
395     public String JavaDoc getSystemId()
396     { return null; }
397 }
398
399
400
Popular Tags