KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > util > xml > catalog > readers > DOMCatalogReader


1 // DOMCatalogReader.java - Read XML Catalog files
2

3 /* ====================================================================
4  * The Apache Software License, Version 1.1
5  *
6  * Copyright (c) 2001-2003 The Apache Software Foundation. All rights
7  * reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution,
22  * if any, must include the following acknowledgment:
23  * "This product includes software developed by the
24  * Apache Software Foundation (http://www.apache.org/)."
25  * Alternately, this acknowledgment may appear in the software itself,
26  * if and wherever such third-party acknowledgments normally appear.
27  *
28  * 4. The names "Apache" and "Apache Software Foundation" must
29  * not be used to endorse or promote products derived from this
30  * software without prior written permission. For written
31  * permission, please contact apache@apache.org.
32  *
33  * 5. Products derived from this software may not be called "Apache",
34  * nor may "Apache" appear in their name, without prior written
35  * permission of the Apache Software Foundation.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals on behalf of the Apache Software Foundation. For more
53  * information on the Apache Software Foundation, please see
54  * <http://www.apache.org/>.
55  */

56
57 package org.jboss.util.xml.catalog.readers;
58
59 import java.util.Hashtable JavaDoc;
60 import java.io.IOException JavaDoc;
61 import java.io.InputStream JavaDoc;
62 import java.net.URL JavaDoc;
63 import java.net.URLConnection JavaDoc;
64 import java.net.MalformedURLException JavaDoc;
65
66 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
67 import javax.xml.parsers.DocumentBuilder JavaDoc;
68 import javax.xml.parsers.ParserConfigurationException JavaDoc;
69
70 import org.jboss.util.xml.catalog.Catalog;
71 import org.jboss.util.xml.catalog.CatalogException;
72 import org.jboss.util.xml.catalog.helpers.Namespaces;
73 import org.jboss.util.xml.catalog.readers.CatalogReader;
74
75 import org.xml.sax.SAXException JavaDoc;
76 import org.w3c.dom.*;
77
78 /**
79  * A DOM-based CatalogReader.
80  *
81  * <p>This class is used to read XML Catalogs using the DOM. This reader
82  * has an advantage over the SAX-based reader that it can analyze the
83  * DOM tree rather than simply a series of SAX events. It has the disadvantage
84  * that it requires all of the code necessary to build and walk a DOM
85  * tree.</p>
86  *
87  * <p>Since the choice of CatalogReaders (in the InputStream case) can only
88  * be made on the basis of MIME type, the following problem occurs: only
89  * one CatalogReader can exist for all XML mime types. In order to get
90  * around this problem, the DOMCatalogReader relies on a set of external
91  * CatalogParsers to actually build the catalog.</p>
92  *
93  * <p>The selection of CatalogParsers is made on the basis of the QName
94  * of the root element of the document.</p>
95  *
96  * <p>This class requires the <a HREF="http://java.sun.com/aboutJava/communityprocess/final/jsr005/index.html">Java API for XML Parsing</a>.</p>
97  *
98  * @see Catalog
99  * @see CatalogReader
100  * @see SAXCatalogReader
101  * @see TextCatalogReader
102  * @see DOMCatalogParser
103  *
104  * @author Norman Walsh
105  * <a HREF="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
106  *
107  * @version 1.0
108  */

109 public class DOMCatalogReader implements CatalogReader {
110   /**
111    * Mapping table from QNames to CatalogParser classes.
112    *
113    * <p>Each key in this hash table has the form "elementname"
114    * or "{namespaceuri}elementname". The former is used if the
115    * namespace URI is null.</p>
116    */

117   protected Hashtable JavaDoc namespaceMap = new Hashtable JavaDoc();
118
119   /**
120    * Add a new parser to the reader.
121    *
122    * <p>This method associates the specified parserClass with the
123    * namespaceURI/rootElement names specified.</p>
124    *
125    * @param namespaceURI The namespace URI. <em>Not</em> the prefix.
126    * @param rootElement The name of the root element.
127    * @param parserClass The name of the parserClass to instantiate
128    * for this kind of catalog.
129    */

130   public void setCatalogParser(String JavaDoc namespaceURI,
131                    String JavaDoc rootElement,
132                    String JavaDoc parserClass) {
133     if (namespaceURI == null) {
134       namespaceMap.put(rootElement, parserClass);
135     } else {
136       namespaceMap.put("{"+namespaceURI+"}"+rootElement, parserClass);
137     }
138   }
139
140   /**
141    * Get the name of the parser class for a given catalog type.
142    *
143    * <p>This method returns the parserClass associated with the
144    * namespaceURI/rootElement names specified.</p>
145    *
146    * @param namespaceURI The namespace URI. <em>Not</em> the prefix.
147    * @param rootElement The name of the root element.
148    * @return The parser class.
149    */

150   public String JavaDoc getCatalogParser(String JavaDoc namespaceURI,
151                  String JavaDoc rootElement) {
152     if (namespaceURI == null) {
153       return (String JavaDoc) namespaceMap.get(rootElement);
154     } else {
155       return (String JavaDoc) namespaceMap.get("{"+namespaceURI+"}"+rootElement);
156     }
157   }
158
159   /**
160    * Null constructor; something for subclasses to call.
161    */

162   public DOMCatalogReader() { }
163
164   /**
165    * Read a catalog from an input stream.
166    *
167    * <p>This class reads a catalog from an input stream:</p>
168    *
169    * <ul>
170    * <li>Based on the QName of the root element, it determines which
171    * parser to instantiate for this catalog.</li>
172    * <li>It constructs a DOM Document from the catalog and</li>
173    * <li>For each child of the root node, it calls the parser's
174    * parseCatalogEntry method. This method is expected to make
175    * appropriate calls back into the catalog to add entries for the
176    * entries in the catalog. It is free to do this in whatever manner
177    * is appropriate (perhaps using just the node passed in, perhaps
178    * wandering arbitrarily throughout the tree).</li>
179    * </ul>
180    *
181    * @param catalog The catalog for which this reader is called.
182    * @param is The input stream that is to be read.
183    * @throws IOException if the URL cannot be read.
184    * @throws UnknownCatalogFormatException if the catalog format is
185    * not recognized.
186    * @throws UnparseableCatalogException if the catalog cannot be parsed.
187    * (For example, if it is supposed to be XML and isn't well-formed or
188    * if the parser class cannot be instantiated.)
189    */

190   public void readCatalog(Catalog catalog, InputStream JavaDoc is)
191     throws IOException JavaDoc, CatalogException {
192
193     DocumentBuilderFactory JavaDoc factory = null;
194     DocumentBuilder JavaDoc builder = null;
195
196     factory = DocumentBuilderFactory.newInstance();
197     factory.setNamespaceAware(false);
198     factory.setValidating(false);
199     try {
200       builder = factory.newDocumentBuilder();
201     } catch (ParserConfigurationException JavaDoc pce) {
202       throw new CatalogException(CatalogException.UNPARSEABLE);
203     }
204
205     Document doc = null;
206
207     try {
208       doc = builder.parse(is);
209     } catch (SAXException JavaDoc se) {
210       throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
211     }
212
213     Element root = doc.getDocumentElement();
214
215     String JavaDoc namespaceURI = Namespaces.getNamespaceURI(root);
216     String JavaDoc localName = Namespaces.getLocalName(root);
217
218     String JavaDoc domParserClass = getCatalogParser(namespaceURI,
219                          localName);
220
221     if (domParserClass == null) {
222       if (namespaceURI == null) {
223     catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
224                           + localName);
225       } else {
226     catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
227                           + "{" + namespaceURI + "}"
228                           + localName);
229       }
230       return;
231     }
232
233     DOMCatalogParser domParser = null;
234
235     try {
236       domParser = (DOMCatalogParser) Class.forName(domParserClass).newInstance();
237     } catch (ClassNotFoundException JavaDoc cnfe) {
238       catalog.getCatalogManager().debug.message(1, "Cannot load XML Catalog Parser class", domParserClass);
239       throw new CatalogException(CatalogException.UNPARSEABLE);
240     } catch (InstantiationException JavaDoc ie) {
241       catalog.getCatalogManager().debug.message(1, "Cannot instantiate XML Catalog Parser class", domParserClass);
242       throw new CatalogException(CatalogException.UNPARSEABLE);
243     } catch (IllegalAccessException JavaDoc iae) {
244       catalog.getCatalogManager().debug.message(1, "Cannot access XML Catalog Parser class", domParserClass);
245       throw new CatalogException(CatalogException.UNPARSEABLE);
246     } catch (ClassCastException JavaDoc cce ) {
247       catalog.getCatalogManager().debug.message(1, "Cannot cast XML Catalog Parser class", domParserClass);
248       throw new CatalogException(CatalogException.UNPARSEABLE);
249     }
250
251     Node node = root.getFirstChild();
252     while (node != null) {
253       domParser.parseCatalogEntry(catalog, node);
254       node = node.getNextSibling();
255     }
256   }
257
258   /**
259    * Read the catalog behind the specified URL.
260    *
261    * @see #readCatalog(Catalog, InputStream)
262    *
263    * @param catalog The catalog for which we are reading.
264    * @param fileUrl The URL of the document that should be read.
265    *
266    * @throws MalformedURLException if the specified URL cannot be
267    * turned into a URL object.
268    * @throws IOException if the URL cannot be read.
269    * @throws UnknownCatalogFormatException if the catalog format is
270    * not recognized.
271    * @throws UnparseableCatalogException if the catalog cannot be parsed.
272    * (For example, if it is supposed to be XML and isn't well-formed.)
273    */

274   public void readCatalog(Catalog catalog, String JavaDoc fileUrl)
275     throws MalformedURLException JavaDoc, IOException JavaDoc, CatalogException {
276     URL JavaDoc url = new URL JavaDoc(fileUrl);
277     URLConnection JavaDoc urlCon = url.openConnection();
278     readCatalog(catalog, urlCon.getInputStream());
279   }
280 }
281
Popular Tags