KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > xerces > parsers > DOMParser


1 /*
2  * Copyright 2000-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.xerces.parsers;
18
19 import java.io.IOException JavaDoc;
20
21 import org.apache.xerces.impl.Constants;
22 import org.apache.xerces.util.EntityResolverWrapper;
23 import org.apache.xerces.util.EntityResolver2Wrapper;
24 import org.apache.xerces.util.ErrorHandlerWrapper;
25 import org.apache.xerces.util.SAXMessageFormatter;
26 import org.apache.xerces.util.SymbolTable;
27 import org.apache.xerces.xni.XNIException;
28 import org.apache.xerces.xni.grammars.XMLGrammarPool;
29 import org.apache.xerces.xni.parser.XMLConfigurationException;
30 import org.apache.xerces.xni.parser.XMLEntityResolver;
31 import org.apache.xerces.xni.parser.XMLErrorHandler;
32 import org.apache.xerces.xni.parser.XMLInputSource;
33 import org.apache.xerces.xni.parser.XMLParseException;
34 import org.apache.xerces.xni.parser.XMLParserConfiguration;
35 import org.w3c.dom.Node JavaDoc;
36 import org.xml.sax.EntityResolver JavaDoc;
37 import org.xml.sax.ErrorHandler JavaDoc;
38 import org.xml.sax.InputSource JavaDoc;
39 import org.xml.sax.SAXException JavaDoc;
40 import org.xml.sax.SAXNotRecognizedException JavaDoc;
41 import org.xml.sax.SAXNotSupportedException JavaDoc;
42 import org.xml.sax.SAXParseException JavaDoc;
43 import org.xml.sax.ext.EntityResolver2 JavaDoc;
44 import org.xml.sax.helpers.LocatorImpl JavaDoc;
45
46 /**
47  * This is the main Xerces DOM parser class. It uses the abstract DOM
48  * parser with a document scanner, a dtd scanner, and a validator, as
49  * well as a grammar pool.
50  *
51  * @author Arnaud Le Hors, IBM
52  * @author Andy Clark, IBM
53  *
54  * @version $Id: DOMParser.java,v 1.77 2005/06/24 02:33:43 mrglavas Exp $
55  */

56 public class DOMParser
57     extends AbstractDOMParser {
58
59     //
60
// Constants
61
//
62

63     // features
64

65     /** Feature identifier: EntityResolver2. */
66     protected static final String JavaDoc USE_ENTITY_RESOLVER2 =
67         Constants.SAX_FEATURE_PREFIX + Constants.USE_ENTITY_RESOLVER2_FEATURE;
68
69     // properties
70

71     /** Property identifier: symbol table. */
72     protected static final String JavaDoc SYMBOL_TABLE =
73         Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
74
75     /** Property identifier: XML grammar pool. */
76     protected static final String JavaDoc XMLGRAMMAR_POOL =
77         Constants.XERCES_PROPERTY_PREFIX+Constants.XMLGRAMMAR_POOL_PROPERTY;
78
79     /** Recognized properties. */
80     private static final String JavaDoc[] RECOGNIZED_PROPERTIES = {
81         SYMBOL_TABLE,
82         XMLGRAMMAR_POOL,
83     };
84     
85     //
86
// Data
87
//
88

89     // features
90

91     /** Use EntityResolver2. */
92     protected boolean fUseEntityResolver2 = true;
93
94     //
95
// Constructors
96
//
97

98     /**
99      * Constructs a DOM parser using the specified parser configuration.
100      */

101     public DOMParser(XMLParserConfiguration config) {
102         super(config);
103     } // <init>(XMLParserConfiguration)
104

105     /**
106      * Constructs a DOM parser using the dtd/xml schema parser configuration.
107      */

108     public DOMParser() {
109         this(null, null);
110     } // <init>()
111

112     /**
113      * Constructs a DOM parser using the specified symbol table.
114      */

115     public DOMParser(SymbolTable symbolTable) {
116         this(symbolTable, null);
117     } // <init>(SymbolTable)
118

119
120     /**
121      * Constructs a DOM parser using the specified symbol table and
122      * grammar pool.
123      */

124     public DOMParser(SymbolTable symbolTable, XMLGrammarPool grammarPool) {
125         super((XMLParserConfiguration)ObjectFactory.createObject(
126             "org.apache.xerces.xni.parser.XMLParserConfiguration",
127             "org.apache.xerces.parsers.XIncludeAwareParserConfiguration"
128             ));
129
130         // set properties
131
fConfiguration.addRecognizedProperties(RECOGNIZED_PROPERTIES);
132         if (symbolTable != null) {
133             fConfiguration.setProperty(SYMBOL_TABLE, symbolTable);
134         }
135         if (grammarPool != null) {
136             fConfiguration.setProperty(XMLGRAMMAR_POOL, grammarPool);
137         }
138
139     } // <init>(SymbolTable,XMLGrammarPool)
140

141     //
142
// XMLReader methods
143
//
144

145     /**
146      * Parses the input source specified by the given system identifier.
147      * <p>
148      * This method is equivalent to the following:
149      * <pre>
150      * parse(new InputSource(systemId));
151      * </pre>
152      *
153      * @param systemId The system identifier (URI).
154      *
155      * @exception org.xml.sax.SAXException Throws exception on SAX error.
156      * @exception java.io.IOException Throws exception on i/o error.
157      */

158     public void parse(String JavaDoc systemId) throws SAXException JavaDoc, IOException JavaDoc {
159
160         // parse document
161
XMLInputSource source = new XMLInputSource(null, systemId, null);
162         try {
163             parse(source);
164         }
165
166         // wrap XNI exceptions as SAX exceptions
167
catch (XMLParseException e) {
168             Exception JavaDoc ex = e.getException();
169             if (ex == null) {
170                 // must be a parser exception; mine it for locator info and throw
171
// a SAXParseException
172
LocatorImpl JavaDoc locatorImpl = new LocatorImpl JavaDoc();
173                 locatorImpl.setPublicId(e.getPublicId());
174                 locatorImpl.setSystemId(e.getExpandedSystemId());
175                 locatorImpl.setLineNumber(e.getLineNumber());
176                 locatorImpl.setColumnNumber(e.getColumnNumber());
177                 throw new SAXParseException JavaDoc(e.getMessage(), locatorImpl);
178             }
179             if (ex instanceof SAXException JavaDoc) {
180                 // why did we create an XMLParseException?
181
throw (SAXException JavaDoc)ex;
182             }
183             if (ex instanceof IOException JavaDoc) {
184                 throw (IOException JavaDoc)ex;
185             }
186             throw new SAXException JavaDoc(ex);
187         }
188         catch (XNIException e) {
189             e.printStackTrace();
190             Exception JavaDoc ex = e.getException();
191             if (ex == null) {
192                 throw new SAXException JavaDoc(e.getMessage());
193             }
194             if (ex instanceof SAXException JavaDoc) {
195                 throw (SAXException JavaDoc)ex;
196             }
197             if (ex instanceof IOException JavaDoc) {
198                 throw (IOException JavaDoc)ex;
199             }
200             throw new SAXException JavaDoc(ex);
201         }
202
203     } // parse(String)
204

205     /**
206      * parse
207      *
208      * @param inputSource
209      *
210      * @exception org.xml.sax.SAXException
211      * @exception java.io.IOException
212      */

213     public void parse(InputSource inputSource)
214         throws SAXException JavaDoc, IOException JavaDoc {
215
216         // parse document
217
try {
218             XMLInputSource xmlInputSource =
219                 new XMLInputSource(inputSource.getPublicId(),
220                                    inputSource.getSystemId(),
221                                    null);
222             xmlInputSource.setByteStream(inputSource.getByteStream());
223             xmlInputSource.setCharacterStream(inputSource.getCharacterStream());
224             xmlInputSource.setEncoding(inputSource.getEncoding());
225             parse(xmlInputSource);
226         }
227
228         // wrap XNI exceptions as SAX exceptions
229
catch (XMLParseException e) {
230             Exception JavaDoc ex = e.getException();
231             if (ex == null) {
232                 // must be a parser exception; mine it for locator info and throw
233
// a SAXParseException
234
LocatorImpl JavaDoc locatorImpl = new LocatorImpl JavaDoc();
235                 locatorImpl.setPublicId(e.getPublicId());
236                 locatorImpl.setSystemId(e.getExpandedSystemId());
237                 locatorImpl.setLineNumber(e.getLineNumber());
238                 locatorImpl.setColumnNumber(e.getColumnNumber());
239                 throw new SAXParseException JavaDoc(e.getMessage(), locatorImpl);
240             }
241             if (ex instanceof SAXException JavaDoc) {
242                 // why did we create an XMLParseException?
243
throw (SAXException JavaDoc)ex;
244             }
245             if (ex instanceof IOException JavaDoc) {
246                 throw (IOException JavaDoc)ex;
247             }
248             throw new SAXException JavaDoc(ex);
249         }
250         catch (XNIException e) {
251             Exception JavaDoc ex = e.getException();
252             if (ex == null) {
253                 throw new SAXException JavaDoc(e.getMessage());
254             }
255             if (ex instanceof SAXException JavaDoc) {
256                 throw (SAXException JavaDoc)ex;
257             }
258             if (ex instanceof IOException JavaDoc) {
259                 throw (IOException JavaDoc)ex;
260             }
261             throw new SAXException JavaDoc(ex);
262         }
263
264     } // parse(InputSource)
265

266     /**
267      * Sets the resolver used to resolve external entities. The EntityResolver
268      * interface supports resolution of public and system identifiers.
269      *
270      * @param resolver The new entity resolver. Passing a null value will
271      * uninstall the currently installed resolver.
272      */

273     public void setEntityResolver(EntityResolver resolver) {
274
275         try {
276             XMLEntityResolver xer = (XMLEntityResolver) fConfiguration.getProperty(ENTITY_RESOLVER);
277             if (fUseEntityResolver2 && resolver instanceof EntityResolver2 JavaDoc) {
278                 if (xer instanceof EntityResolver2Wrapper) {
279                     EntityResolver2Wrapper er2w = (EntityResolver2Wrapper) xer;
280                     er2w.setEntityResolver((EntityResolver2 JavaDoc) resolver);
281                 }
282                 else {
283                     fConfiguration.setProperty(ENTITY_RESOLVER,
284                             new EntityResolver2Wrapper((EntityResolver2 JavaDoc) resolver));
285                 }
286             }
287             else {
288                 if (xer instanceof EntityResolverWrapper) {
289                     EntityResolverWrapper erw = (EntityResolverWrapper) xer;
290                     erw.setEntityResolver(resolver);
291                 }
292                 else {
293                     fConfiguration.setProperty(ENTITY_RESOLVER,
294                             new EntityResolverWrapper(resolver));
295                 }
296             }
297         }
298         catch (XMLConfigurationException e) {
299             // do nothing
300
}
301
302     } // setEntityResolver(EntityResolver)
303

304     /**
305      * Return the current entity resolver.
306      *
307      * @return The current entity resolver, or null if none
308      * has been registered.
309      * @see #setEntityResolver
310      */

311     public EntityResolver getEntityResolver() {
312
313         EntityResolver entityResolver = null;
314         try {
315             XMLEntityResolver xmlEntityResolver =
316                 (XMLEntityResolver)fConfiguration.getProperty(ENTITY_RESOLVER);
317             if (xmlEntityResolver != null) {
318                 if (xmlEntityResolver instanceof EntityResolverWrapper) {
319                     entityResolver =
320                         ((EntityResolverWrapper) xmlEntityResolver).getEntityResolver();
321                 }
322                 else if (xmlEntityResolver instanceof EntityResolver2Wrapper) {
323                     entityResolver =
324                         ((EntityResolver2Wrapper) xmlEntityResolver).getEntityResolver();
325                 }
326             }
327         }
328         catch (XMLConfigurationException e) {
329             // do nothing
330
}
331         return entityResolver;
332
333     } // getEntityResolver():EntityResolver
334

335     /**
336      * Allow an application to register an error event handler.
337      *
338      * <p>If the application does not register an error handler, all
339      * error events reported by the SAX parser will be silently
340      * ignored; however, normal processing may not continue. It is
341      * highly recommended that all SAX applications implement an
342      * error handler to avoid unexpected bugs.</p>
343      *
344      * <p>Applications may register a new or different handler in the
345      * middle of a parse, and the SAX parser must begin using the new
346      * handler immediately.</p>
347      *
348      * @param errorHandler The error handler.
349      * @exception java.lang.NullPointerException If the handler
350      * argument is null.
351      * @see #getErrorHandler
352      */

353     public void setErrorHandler(ErrorHandler errorHandler) {
354
355         try {
356             XMLErrorHandler xeh = (XMLErrorHandler) fConfiguration.getProperty(ERROR_HANDLER);
357             if (xeh instanceof ErrorHandlerWrapper) {
358                 ErrorHandlerWrapper ehw = (ErrorHandlerWrapper) xeh;
359                 ehw.setErrorHandler(errorHandler);
360             }
361             else {
362                 fConfiguration.setProperty(ERROR_HANDLER,
363                         new ErrorHandlerWrapper(errorHandler));
364             }
365         }
366         catch (XMLConfigurationException e) {
367             // do nothing
368
}
369
370     } // setErrorHandler(ErrorHandler)
371

372     /**
373      * Return the current error handler.
374      *
375      * @return The current error handler, or null if none
376      * has been registered.
377      * @see #setErrorHandler
378      */

379     public ErrorHandler getErrorHandler() {
380
381         ErrorHandler errorHandler = null;
382         try {
383             XMLErrorHandler xmlErrorHandler =
384                 (XMLErrorHandler)fConfiguration.getProperty(ERROR_HANDLER);
385             if (xmlErrorHandler != null &&
386                 xmlErrorHandler instanceof ErrorHandlerWrapper) {
387                 errorHandler = ((ErrorHandlerWrapper)xmlErrorHandler).getErrorHandler();
388             }
389         }
390         catch (XMLConfigurationException e) {
391             // do nothing
392
}
393         return errorHandler;
394
395     } // getErrorHandler():ErrorHandler
396

397     /**
398      * Set the state of any feature in a SAX2 parser. The parser
399      * might not recognize the feature, and if it does recognize
400      * it, it might not be able to fulfill the request.
401      *
402      * @param featureId The unique identifier (URI) of the feature.
403      * @param state The requested state of the feature (true or false).
404      *
405      * @exception SAXNotRecognizedException If the
406      * requested feature is not known.
407      * @exception SAXNotSupportedException If the
408      * requested feature is known, but the requested
409      * state is not supported.
410      */

411     public void setFeature(String JavaDoc featureId, boolean state)
412         throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc {
413
414         try {
415             
416             // http://xml.org/sax/features/use-entity-resolver2
417
// controls whether the methods of an object implementing
418
// org.xml.sax.ext.EntityResolver2 will be used by the parser.
419
//
420
if (featureId.equals(USE_ENTITY_RESOLVER2)) {
421                 if (state != fUseEntityResolver2) {
422                     fUseEntityResolver2 = state;
423                     // Refresh EntityResolver wrapper.
424
setEntityResolver(getEntityResolver());
425                 }
426                 return;
427             }
428             
429             //
430
// Default handling
431
//
432

433             fConfiguration.setFeature(featureId, state);
434         }
435         catch (XMLConfigurationException e) {
436             String JavaDoc identifier = e.getIdentifier();
437             if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
438                 throw new SAXNotRecognizedException JavaDoc(
439                     SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
440                     "feature-not-recognized", new Object JavaDoc [] {identifier}));
441             }
442             else {
443                 throw new SAXNotSupportedException JavaDoc(
444                     SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
445                     "feature-not-supported", new Object JavaDoc [] {identifier}));
446             }
447         }
448
449     } // setFeature(String,boolean)
450

451     /**
452      * Query the state of a feature.
453      *
454      * Query the current state of any feature in a SAX2 parser. The
455      * parser might not recognize the feature.
456      *
457      * @param featureId The unique identifier (URI) of the feature
458      * being set.
459      * @return The current state of the feature.
460      * @exception org.xml.sax.SAXNotRecognizedException If the
461      * requested feature is not known.
462      * @exception SAXNotSupportedException If the
463      * requested feature is known but not supported.
464      */

465     public boolean getFeature(String JavaDoc featureId)
466         throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc {
467
468         try {
469
470             // http://xml.org/sax/features/use-entity-resolver2
471
// controls whether the methods of an object implementing
472
// org.xml.sax.ext.EntityResolver2 will be used by the parser.
473
//
474
if (featureId.equals(USE_ENTITY_RESOLVER2)) {
475                 return fUseEntityResolver2;
476             }
477             
478             //
479
// Default handling
480
//
481

482             return fConfiguration.getFeature(featureId);
483         }
484         catch (XMLConfigurationException e) {
485             String JavaDoc identifier = e.getIdentifier();
486             if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
487                 throw new SAXNotRecognizedException JavaDoc(
488                     SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
489                     "feature-not-recognized", new Object JavaDoc [] {identifier}));
490             }
491             else {
492                 throw new SAXNotSupportedException JavaDoc(
493                     SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
494                     "feature-not-supported", new Object JavaDoc [] {identifier}));
495             }
496         }
497
498     } // getFeature(String):boolean
499

500     /**
501      * Set the value of any property in a SAX2 parser. The parser
502      * might not recognize the property, and if it does recognize
503      * it, it might not support the requested value.
504      *
505      * @param propertyId The unique identifier (URI) of the property
506      * being set.
507      * @param value The value to which the property is being set.
508      *
509      * @exception SAXNotRecognizedException If the
510      * requested property is not known.
511      * @exception SAXNotSupportedException If the
512      * requested property is known, but the requested
513      * value is not supported.
514      */

515     public void setProperty(String JavaDoc propertyId, Object JavaDoc value)
516         throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc {
517
518         try {
519             fConfiguration.setProperty(propertyId, value);
520         }
521         catch (XMLConfigurationException e) {
522             String JavaDoc identifier = e.getIdentifier();
523             if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
524                 throw new SAXNotRecognizedException JavaDoc(
525                     SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
526                     "property-not-recognized", new Object JavaDoc [] {identifier}));
527             }
528             else {
529                 throw new SAXNotSupportedException JavaDoc(
530                     SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
531                     "property-not-supported", new Object JavaDoc [] {identifier}));
532             }
533         }
534
535     } // setProperty(String,Object)
536

537     /**
538      * Query the value of a property.
539      *
540      * Return the current value of a property in a SAX2 parser.
541      * The parser might not recognize the property.
542      *
543      * @param propertyId The unique identifier (URI) of the property
544      * being set.
545      * @return The current value of the property.
546      * @exception org.xml.sax.SAXNotRecognizedException If the
547      * requested property is not known.
548      * @exception SAXNotSupportedException If the
549      * requested property is known but not supported.
550      */

551     public Object JavaDoc getProperty(String JavaDoc propertyId)
552         throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc {
553
554        if (propertyId.equals(CURRENT_ELEMENT_NODE)) {
555            boolean deferred = false;
556            try {
557                deferred = getFeature(DEFER_NODE_EXPANSION);
558            }
559            catch (XMLConfigurationException e){
560                // ignore
561
}
562            if (deferred) {
563                throw new SAXNotSupportedException JavaDoc("Current element node cannot be queried when node expansion is deferred.");
564            }
565            return (fCurrentNode!=null &&
566                    fCurrentNode.getNodeType() == Node.ELEMENT_NODE)? fCurrentNode:null;
567        }
568
569         try {
570             return fConfiguration.getProperty(propertyId);
571         }
572         catch (XMLConfigurationException e) {
573             String JavaDoc identifier = e.getIdentifier();
574             if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
575                 throw new SAXNotRecognizedException JavaDoc(
576                     SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
577                     "property-not-recognized", new Object JavaDoc [] {identifier}));
578             }
579             else {
580                 throw new SAXNotSupportedException JavaDoc(
581                     SAXMessageFormatter.formatMessage(fConfiguration.getLocale(),
582                     "property-not-supported", new Object JavaDoc [] {identifier}));
583             }
584         }
585
586     } // getProperty(String):Object
587

588     /**
589      * Returns this parser's XMLParserConfiguration.
590      */

591     public XMLParserConfiguration getXMLParserConfiguration() {
592         return fConfiguration;
593     } // getXMLParserConfiguration():XMLParserConfiguration
594

595 } // class DOMParser
596
Popular Tags