KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > xml > io > DOMParser


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: DOMParser.java,v 1.4 2005/01/26 08:29:24 jkjome Exp $
22  */

23
24 package org.enhydra.xml.io;
25
26 import java.io.IOException JavaDoc;
27
28 import javax.xml.parsers.DocumentBuilder JavaDoc;
29
30 import org.enhydra.apache.xerces.dom.DOMImplementationImpl;
31 import org.w3c.dom.DOMImplementation JavaDoc;
32 import org.w3c.dom.Document JavaDoc;
33 import org.xml.sax.EntityResolver JavaDoc;
34 import org.xml.sax.ErrorHandler JavaDoc;
35 import org.xml.sax.InputSource JavaDoc;
36 import org.xml.sax.SAXException JavaDoc;
37 import org.xml.sax.SAXNotRecognizedException JavaDoc;
38
39 // FIXME: Not completely sure how useful this is. It was originally done
40
// before JAXP was availble in Xerces, was suppose to evolve into a more
41
// general facility, but is now just used by XMLC.
42

43 /**
44  * XML parser that parsers to a DOM. This implements the JAXP DOM parser
45  * interface plus the following additional features:
46  *
47  * <UL>
48  * <LI> Control over the Document class that is created. This easily
49  * supports building a DTD-specific DOM.
50  * <LI> Simplified error handling.
51  * <LI> Finding the initial document via the entity resolver.
52  * </UL>
53  *
54  * @see javax.xml.parsers.DocumentBuilder
55  */

56 public class DOMParser extends DocumentBuilder JavaDoc {
57     /**
58      * Class name to use for the Document object.
59      */

60     private String JavaDoc documentClassName = null;
61
62     /**
63      * Error handler.
64      */

65     private ErrorHandler JavaDoc errorHandler = null;
66
67     /**
68      * Entity resolver.
69      */

70     private EntityResolver JavaDoc entityResolver = null;
71
72     /**
73      * Namespaces enabled.
74      */

75     private boolean enableNamespaces = true;
76
77     /**
78      * Validation enabled.
79      */

80     private boolean validationEnabled = true;
81
82     //FIXME: ErrorReporter reporter = new ErrorReporter(new PrintWriter(System.err, true));
83
//FIXME: should deal with ignorable white space.
84

85     /**
86      * Need standarderror handler, this is just a tmp hack.
87      */

88     class XercesParser extends org.enhydra.apache.xerces.parsers.DOMParser {
89         /**
90          * Construct a parser.
91          */

92         public XercesParser() throws SAXException JavaDoc {
93             if (documentClassName != null) {
94                 super.setDocumentClassName(documentClassName);
95             }
96             if (errorHandler != null) {
97                 super.setErrorHandler(errorHandler);
98             }
99             if (entityResolver != null) {
100                 super.setEntityResolver(entityResolver);
101             }
102             super.setNamespaces(enableNamespaces);
103             super.setValidation(validationEnabled);
104             super.setDeferNodeExpansion(false);
105
106         }
107
108         /**
109          * Resolve an input source using the entity resolver.
110          * @return The resolved source, or the originally specified
111          * source if it can't be resolved or is already open.
112          */

113         private InputSource JavaDoc resolve(InputSource JavaDoc inputSource)
114                 throws SAXException JavaDoc, IOException JavaDoc {
115             if ((inputSource.getByteStream() != null)
116                 || (inputSource.getCharacterStream() != null)) {
117                 return inputSource; // Already open
118
}
119
120             EntityResolver JavaDoc resolver = this.getEntityResolver();
121             if (resolver == null) {
122                 return inputSource; // No resolver
123
}
124
125             String JavaDoc publicId = inputSource.getPublicId();
126             String JavaDoc systemId = inputSource.getSystemId();
127             if ((publicId == null) && (systemId == null)) {
128                 // Shouldn't happen, but let parser generate error
129
return inputSource;
130             }
131
132             InputSource JavaDoc resolvedSource = resolver.resolveEntity(publicId,
133                                                                 systemId);
134             if (resolvedSource != null) {
135                 return resolvedSource;
136             } else {
137                 return inputSource;
138             }
139         }
140
141         /**
142          * Parse the document, possibly resolving it via the entity
143          * resolver.
144          */

145         public void parse(InputSource JavaDoc inputSource)
146             throws SAXException JavaDoc, IOException JavaDoc {
147             super.parse(resolve(inputSource));
148         }
149     }
150
151     //FIXME: Throws exception on parse failure, but ErrorReporter my be
152
// collectin output in memory. Recompiler deals with this, but it might
153
// be nice to include a standard mechanism.
154
/**
155      * Parse the content of the given input source as an XML document
156      * and return a new DOM Document object.
157      *
158      * @param is InputSource containing the content to be parsed.
159      * @exception IOException If any IO errors occur.
160      * @exception SAXException If any parse errors occur.
161      * @exception IllegalArgumentException If the InputSource is null
162      * @see org.xml.sax.DocumentHandler
163      * @see javax.xml.parsers.DocumentBuilder#parse
164      */

165     public Document JavaDoc parse(InputSource JavaDoc is)
166         throws SAXException JavaDoc, IOException JavaDoc {
167         XercesParser parser = new XercesParser();
168         parser.parse(is);
169         return parser.getDocument();
170     }
171
172     /**
173      * Enable or disable namespaces.
174      */

175     public void setNamespaceAware(boolean enable) {
176         enableNamespaces = enable;
177     }
178     
179     /**
180      * Indicates whether or not this parser is configured to
181      * understand namespaces.
182      * @see javax.xml.parsers.DocumentBuilder#isNamespaceAware
183      */

184     public boolean isNamespaceAware() {
185         return enableNamespaces;
186     }
187
188     /**
189      * Enable or disable validation.
190      */

191     public void setValidation(boolean enable) {
192         validationEnabled = enable;
193     }
194     
195     /**
196      * Indicates whether or not this parser is configured to
197      * validate XML documents.
198      * @see javax.xml.parsers.DocumentBuilder#isValidating
199      */

200     public boolean isValidating() {
201         return validationEnabled;
202     }
203
204     /**
205      * Specify the <code>EntityResolver</code> to be used to resolve
206      * entities present in the XML document to be parsed. Setting
207      * this to <code>null</code> will result in the underlying
208      * implementation using it's own default implementation and
209      * behavior.
210      * @see javax.xml.parsers.DocumentBuilder#setEntityResolver
211      */

212     public void setEntityResolver(EntityResolver JavaDoc er) {
213         entityResolver = er;
214     }
215
216     /**
217      * Get the <code>EntityResolver</code>
218      */

219     public EntityResolver JavaDoc getEntityResolver() {
220         return entityResolver;
221     }
222
223     /**
224      * Specify the <code>ErrorHandler</code> to be used handle parse
225      * errors. Setting
226      * this to <code>null</code> will result in the underlying
227      * implementation using it's own default implementation and
228      * behavior.
229      * @see javax.xml.parsers.DocumentBuilder#setErrorHandler
230      */

231     public void setErrorHandler(ErrorHandler JavaDoc eh) {
232         errorHandler = eh;
233     }
234
235     /**
236      * Get the <code>ErrorHandler</code>.
237      */

238     public ErrorHandler JavaDoc getErrorHandler() {
239         return errorHandler;
240     }
241
242     /**
243      * Set the document class for the document to construct.
244      * FIXME: need by-class object specificaion.
245      */

246     public void setDocumentClassName(String JavaDoc className) {
247         documentClassName = className;
248     }
249     
250     /**
251      * get the document class for the document to construct.
252      */

253     public String JavaDoc getDocumentClassName() {
254         return documentClassName;
255     }
256     
257
258     /**
259      * Obtain a new instance of a DOM Document object to build a DOM
260      * tree with.
261      * @see javax.xml.parsers.DocumentBuilder#newDocument
262      */

263     public Document JavaDoc newDocument() {
264         String JavaDoc className = (documentClassName != null)
265             ? documentClassName : org.enhydra.apache.xerces.parsers.DOMParser.DEFAULT_DOCUMENT_CLASS_NAME;
266         try {
267             Class JavaDoc documentClass = getClass().getClassLoader().loadClass(className);
268             return (Document JavaDoc)documentClass.newInstance();
269         } catch (Exception JavaDoc except) {
270             throw new XMLIOError(except);
271         }
272     }
273
274     /**
275      * Obtain an instance of a {@link org.w3c.dom.DOMImplementation} object.
276      *
277      * @return A new instance of a <code>DOMImplementation</code>.
278      */

279     public DOMImplementation JavaDoc getDOMImplementation() {
280         return DOMImplementationImpl.getDOMImplementation();
281     }
282
283     /**
284      * Generate a description of various attributes of the parser
285      * for debugging purposes.
286      */

287     public String JavaDoc toString() {
288         try {
289             StringBuffer JavaDoc buf = new StringBuffer JavaDoc(4096);
290             // Get a parser object with the current settings.
291
XercesParser parser = new XercesParser();
292
293             //FIXME: getFeaturesRecognized() actually returns
294
// unrecognized features, hence the checks.
295

296             String JavaDoc[] features = parser.getFeaturesRecognized();
297             buf.append("Parser features:\n");
298             for (int idx = 0; idx < features.length; idx++) {
299                 buf.append(" ");
300                 buf.append(features[idx]);
301                 buf.append("=");
302                 try {
303                     buf.append(parser.getFeature(features[idx]));
304                 } catch (SAXNotRecognizedException JavaDoc except) {
305                     buf.append("*** not recognized ***");
306                 }
307                 buf.append('\n');
308             }
309
310             String JavaDoc[] properties = parser.getPropertiesRecognized();
311             buf.append("Parser properties:\n");
312             for (int idx = 0; idx < properties.length; idx++) {
313                 buf.append(" ");
314                 buf.append(properties[idx]);
315                 buf.append("=");
316                 try {
317                     buf.append(parser.getFeature(properties[idx]));
318                 } catch (SAXNotRecognizedException JavaDoc except) {
319                     buf.append("*** not recognized ***");
320                 }
321                 buf.append('\n');
322             }
323             return buf.toString();
324         } catch (SAXException JavaDoc except) {
325             throw new XMLIOError(except);
326         }
327     }
328 }
329
Popular Tags