KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Copyright 2004 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 import java.util.ArrayList JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.Locale JavaDoc;
23
24 import org.apache.xerces.impl.Constants;
25 import org.apache.xerces.impl.XML11DTDScannerImpl;
26 import org.apache.xerces.impl.XML11DocumentScannerImpl;
27 import org.apache.xerces.impl.XML11NSDocumentScannerImpl;
28 import org.apache.xerces.impl.XMLDTDScannerImpl;
29 import org.apache.xerces.impl.XMLDocumentScannerImpl;
30 import org.apache.xerces.impl.XMLEntityHandler;
31 import org.apache.xerces.impl.XMLEntityManager;
32 import org.apache.xerces.impl.XMLErrorReporter;
33 import org.apache.xerces.impl.XMLNSDocumentScannerImpl;
34 import org.apache.xerces.impl.XMLVersionDetector;
35 import org.apache.xerces.impl.dv.DTDDVFactory;
36 import org.apache.xerces.impl.msg.XMLMessageFormatter;
37 import org.apache.xerces.impl.validation.ValidationManager;
38 import org.apache.xerces.util.ParserConfigurationSettings;
39 import org.apache.xerces.util.SymbolTable;
40 import org.apache.xerces.xni.XMLDTDContentModelHandler;
41 import org.apache.xerces.xni.XMLDTDHandler;
42 import org.apache.xerces.xni.XMLDocumentHandler;
43 import org.apache.xerces.xni.XMLLocator;
44 import org.apache.xerces.xni.XNIException;
45 import org.apache.xerces.xni.grammars.XMLGrammarPool;
46 import org.apache.xerces.xni.parser.XMLComponent;
47 import org.apache.xerces.xni.parser.XMLComponentManager;
48 import org.apache.xerces.xni.parser.XMLConfigurationException;
49 import org.apache.xerces.xni.parser.XMLDTDScanner;
50 import org.apache.xerces.xni.parser.XMLDocumentScanner;
51 import org.apache.xerces.xni.parser.XMLDocumentSource;
52 import org.apache.xerces.xni.parser.XMLEntityResolver;
53 import org.apache.xerces.xni.parser.XMLErrorHandler;
54 import org.apache.xerces.xni.parser.XMLInputSource;
55 import org.apache.xerces.xni.parser.XMLPullParserConfiguration;
56
57 /**
58  * This class is the non vlaidating parser configuration
59  * used to parse XML 1.0 and XML 1.1 documents.
60  *
61  * Xerces parser that uses this configuration is <strong>not</strong> <a HREF="http://www.w3.org/TR/REC-xml#sec-conformance">conformant</a>
62  * non-validating XML processor, since conformant non-validating processor is required
63  * to process "all the declarations they read in the internal DTD subset ... must use the information in those declarations to normalize attribute values,
64  * include the replacement text of internal entities, and supply default attribute values".
65
66  * @author Elena Litani, IBM
67  * @author John Kim, IBM
68  * @author Michael Glavassevich, IBM
69  *
70  * @version $Id: XML11NonValidatingConfiguration.java,v 1.2 2004/07/23 15:50:15 mrglavas Exp $
71  */

72 public class XML11NonValidatingConfiguration extends ParserConfigurationSettings
73     implements XMLPullParserConfiguration, XML11Configurable {
74
75     //
76
// Constants
77
//
78
protected final static String JavaDoc XML11_DATATYPE_VALIDATOR_FACTORY =
79         "org.apache.xerces.impl.dv.dtd.XML11DTDDVFactoryImpl";
80
81     // feature identifiers
82

83     /** Feature identifier: validation. */
84     protected static final String JavaDoc VALIDATION =
85         Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE;
86     
87     /** Feature identifier: namespaces. */
88     protected static final String JavaDoc NAMESPACES =
89         Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE;
90     
91     /** Feature identifier: external general entities. */
92     protected static final String JavaDoc EXTERNAL_GENERAL_ENTITIES =
93         Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE;
94     
95     /** Feature identifier: external parameter entities. */
96     protected static final String JavaDoc EXTERNAL_PARAMETER_ENTITIES =
97         Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE;
98     
99     
100     /** Feature identifier: continue after fatal error. */
101     protected static final String JavaDoc CONTINUE_AFTER_FATAL_ERROR =
102         Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE;
103
104    
105     // property identifiers
106

107     /** Property identifier: xml string. */
108     protected static final String JavaDoc XML_STRING =
109         Constants.SAX_PROPERTY_PREFIX + Constants.XML_STRING_PROPERTY;
110
111     /** Property identifier: symbol table. */
112     protected static final String JavaDoc SYMBOL_TABLE =
113         Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
114
115     /** Property identifier: error handler. */
116     protected static final String JavaDoc ERROR_HANDLER =
117         Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY;
118
119     /** Property identifier: entity resolver. */
120     protected static final String JavaDoc ENTITY_RESOLVER =
121         Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
122
123     /** Property identifier: error reporter. */
124     protected static final String JavaDoc ERROR_REPORTER =
125         Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
126
127     /** Property identifier: entity manager. */
128     protected static final String JavaDoc ENTITY_MANAGER =
129         Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY;
130
131     /** Property identifier document scanner: */
132     protected static final String JavaDoc DOCUMENT_SCANNER =
133         Constants.XERCES_PROPERTY_PREFIX + Constants.DOCUMENT_SCANNER_PROPERTY;
134
135     /** Property identifier: DTD scanner. */
136     protected static final String JavaDoc DTD_SCANNER =
137         Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_SCANNER_PROPERTY;
138
139     /** Property identifier: grammar pool. */
140     protected static final String JavaDoc XMLGRAMMAR_POOL =
141         Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
142
143     /** Property identifier: DTD validator. */
144     protected static final String JavaDoc DTD_VALIDATOR =
145         Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_VALIDATOR_PROPERTY;
146
147     /** Property identifier: namespace binder. */
148     protected static final String JavaDoc NAMESPACE_BINDER =
149         Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_BINDER_PROPERTY;
150
151     /** Property identifier: datatype validator factory. */
152     protected static final String JavaDoc DATATYPE_VALIDATOR_FACTORY =
153         Constants.XERCES_PROPERTY_PREFIX + Constants.DATATYPE_VALIDATOR_FACTORY_PROPERTY;
154
155     protected static final String JavaDoc VALIDATION_MANAGER =
156         Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
157
158     // debugging
159

160     /** Set to true and recompile to print exception stack trace. */
161     protected static final boolean PRINT_EXCEPTION_STACK_TRACE = false;
162
163     //
164
// Data
165
//
166
protected SymbolTable fSymbolTable;
167     protected XMLInputSource fInputSource;
168     protected ValidationManager fValidationManager;
169     protected XMLVersionDetector fVersionDetector;
170     protected XMLLocator fLocator;
171     protected Locale JavaDoc fLocale;
172     
173     /** XML 1.0 Components. */
174     protected ArrayList JavaDoc fComponents;
175     
176     /** XML 1.1. Components. */
177     protected ArrayList JavaDoc fXML11Components = null;
178     
179     /** Common components: XMLEntityManager, XMLErrorReporter */
180     protected ArrayList JavaDoc fCommonComponents = null;
181     
182     /** The document handler. */
183     protected XMLDocumentHandler fDocumentHandler;
184     
185     /** The DTD handler. */
186     protected XMLDTDHandler fDTDHandler;
187     
188     /** The DTD content model handler. */
189     protected XMLDTDContentModelHandler fDTDContentModelHandler;
190     
191     /** Last component in the document pipeline */
192     protected XMLDocumentSource fLastComponent;
193     
194     /**
195      * True if a parse is in progress. This state is needed because
196      * some features/properties cannot be set while parsing (e.g.
197      * namespaces).
198      */

199     protected boolean fParseInProgress = false;
200     
201     /** fConfigUpdated is set to true if there has been any change to the configuration settings,
202      * i.e a feature or a property was changed.
203      */

204     protected boolean fConfigUpdated = false;
205     
206     //
207
// XML 1.0 components
208
//
209

210     /** The XML 1.0 Datatype validator factory. */
211     protected DTDDVFactory fDatatypeValidatorFactory;
212     
213     /** The XML 1.0 Document scanner that does namespace binding. */
214     protected XMLNSDocumentScannerImpl fNamespaceScanner;
215     
216     /** The XML 1.0 Non-namespace implementation of scanner */
217     protected XMLDocumentScannerImpl fNonNSScanner;
218     
219     /** The XML 1.0 DTD scanner. */
220     protected XMLDTDScanner fDTDScanner;
221     
222     //
223
// XML 1.1 components
224
//
225

226     /** The XML 1.1 datatype factory. **/
227     protected DTDDVFactory fXML11DatatypeFactory = null;
228     
229     /** The XML 1.1 document scanner that does namespace binding. **/
230     protected XML11NSDocumentScannerImpl fXML11NSDocScanner = null;
231     
232     /** The XML 1.1 document scanner that does not do namespace binding. **/
233     protected XML11DocumentScannerImpl fXML11DocScanner = null;
234     
235     /** The XML 1.1 DTD scanner. **/
236     protected XML11DTDScannerImpl fXML11DTDScanner = null;
237     
238     //
239
// Common components
240
//
241

242     /** Grammar pool. */
243     protected XMLGrammarPool fGrammarPool;
244     
245     /** Error reporter. */
246     protected XMLErrorReporter fErrorReporter;
247     
248     /** Entity manager. */
249     protected XMLEntityManager fEntityManager;
250     
251     /** Current scanner */
252     protected XMLDocumentScanner fCurrentScanner;
253     
254     /** Current Datatype validator factory. */
255     protected DTDDVFactory fCurrentDVFactory;
256     
257     /** Current DTD scanner. */
258     protected XMLDTDScanner fCurrentDTDScanner;
259     
260     
261     /** Flag indiciating whether XML11 components have been initialized. */
262     private boolean f11Initialized = false;
263
264     //
265
// Constructors
266
//
267

268     /** Default constructor. */
269     public XML11NonValidatingConfiguration() {
270         this(null, null, null);
271     } // <init>()
272

273     /**
274      * Constructs a parser configuration using the specified symbol table.
275      *
276      * @param symbolTable The symbol table to use.
277      */

278     public XML11NonValidatingConfiguration(SymbolTable symbolTable) {
279         this(symbolTable, null, null);
280     } // <init>(SymbolTable)
281

282     /**
283      * Constructs a parser configuration using the specified symbol table and
284      * grammar pool.
285      * <p>
286      * <strong>REVISIT:</strong>
287      * Grammar pool will be updated when the new validation engine is
288      * implemented.
289      *
290      * @param symbolTable The symbol table to use.
291      * @param grammarPool The grammar pool to use.
292      */

293     public XML11NonValidatingConfiguration(SymbolTable symbolTable, XMLGrammarPool grammarPool) {
294         this(symbolTable, grammarPool, null);
295     } // <init>(SymbolTable,XMLGrammarPool)
296

297     /**
298      * Constructs a parser configuration using the specified symbol table,
299      * grammar pool, and parent settings.
300      * <p>
301      * <strong>REVISIT:</strong>
302      * Grammar pool will be updated when the new validation engine is
303      * implemented.
304      *
305      * @param symbolTable The symbol table to use.
306      * @param grammarPool The grammar pool to use.
307      * @param parentSettings The parent settings.
308      */

309     public XML11NonValidatingConfiguration(
310         SymbolTable symbolTable,
311         XMLGrammarPool grammarPool,
312         XMLComponentManager parentSettings) {
313         
314         super(parentSettings);
315
316         // create a vector to hold all the components in use
317
// XML 1.0 specialized components
318
fComponents = new ArrayList JavaDoc();
319         // XML 1.1 specialized components
320
fXML11Components = new ArrayList JavaDoc();
321         // Common components for XML 1.1. and XML 1.0
322
fCommonComponents = new ArrayList JavaDoc();
323
324         // create storage for recognized features and properties
325
fRecognizedFeatures = new ArrayList JavaDoc();
326         fRecognizedProperties = new ArrayList JavaDoc();
327
328         // create table for features and properties
329
fFeatures = new HashMap JavaDoc();
330         fProperties = new HashMap JavaDoc();
331
332         // add default recognized features
333
final String JavaDoc[] recognizedFeatures =
334             {
335                 CONTINUE_AFTER_FATAL_ERROR, // from XMLDTDScannerImpl
336
VALIDATION,
337                 NAMESPACES,
338                 EXTERNAL_GENERAL_ENTITIES,
339                 EXTERNAL_PARAMETER_ENTITIES,
340                 PARSER_SETTINGS
341             };
342         addRecognizedFeatures(recognizedFeatures);
343         
344         // set state for default features
345
fFeatures.put(VALIDATION, Boolean.FALSE);
346         fFeatures.put(NAMESPACES, Boolean.TRUE);
347         fFeatures.put(EXTERNAL_GENERAL_ENTITIES, Boolean.TRUE);
348         fFeatures.put(EXTERNAL_PARAMETER_ENTITIES, Boolean.TRUE);
349         fFeatures.put(CONTINUE_AFTER_FATAL_ERROR, Boolean.FALSE);
350         fFeatures.put(PARSER_SETTINGS, Boolean.TRUE);
351
352         // add default recognized properties
353
final String JavaDoc[] recognizedProperties =
354             {
355                 XML_STRING,
356                 SYMBOL_TABLE,
357                 ERROR_HANDLER,
358                 ENTITY_RESOLVER,
359                 ERROR_REPORTER,
360                 ENTITY_MANAGER,
361                 DOCUMENT_SCANNER,
362                 DTD_SCANNER,
363                 DTD_VALIDATOR,
364                 DATATYPE_VALIDATOR_FACTORY,
365                 VALIDATION_MANAGER,
366                 XML_STRING,
367                 XMLGRAMMAR_POOL, };
368         addRecognizedProperties(recognizedProperties);
369         
370         if (symbolTable == null) {
371             symbolTable = new SymbolTable();
372         }
373         fSymbolTable = symbolTable;
374         fProperties.put(SYMBOL_TABLE, fSymbolTable);
375         
376         fGrammarPool = grammarPool;
377         if (fGrammarPool != null) {
378             fProperties.put(XMLGRAMMAR_POOL, fGrammarPool);
379         }
380
381         fEntityManager = new XMLEntityManager();
382         fProperties.put(ENTITY_MANAGER, fEntityManager);
383         addCommonComponent(fEntityManager);
384
385         fErrorReporter = new XMLErrorReporter();
386         fErrorReporter.setDocumentLocator(fEntityManager.getEntityScanner());
387         fProperties.put(ERROR_REPORTER, fErrorReporter);
388         addCommonComponent(fErrorReporter);
389
390         fNamespaceScanner = new XMLNSDocumentScannerImpl();
391         fProperties.put(DOCUMENT_SCANNER, fNamespaceScanner);
392         addComponent((XMLComponent) fNamespaceScanner);
393
394         fDTDScanner = new XMLDTDScannerImpl();
395         fProperties.put(DTD_SCANNER, fDTDScanner);
396         addComponent((XMLComponent) fDTDScanner);
397     
398         fDatatypeValidatorFactory = DTDDVFactory.getInstance();
399         fProperties.put(DATATYPE_VALIDATOR_FACTORY, fDatatypeValidatorFactory);
400
401         fValidationManager = new ValidationManager();
402         fProperties.put(VALIDATION_MANAGER, fValidationManager);
403         
404         fVersionDetector = new XMLVersionDetector();
405         
406         // add message formatters
407
if (fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN) == null) {
408             XMLMessageFormatter xmft = new XMLMessageFormatter();
409             fErrorReporter.putMessageFormatter(XMLMessageFormatter.XML_DOMAIN, xmft);
410             fErrorReporter.putMessageFormatter(XMLMessageFormatter.XMLNS_DOMAIN, xmft);
411         }
412
413         // set locale
414
try {
415             setLocale(Locale.getDefault());
416         } catch (XNIException e) {
417             // do nothing
418
// REVISIT: What is the right thing to do? -Ac
419
}
420         
421         fConfigUpdated = false;
422
423     } // <init>(SymbolTable,XMLGrammarPool)
424

425     /**
426      * Sets the input source for the document to parse.
427      *
428      * @param inputSource The document's input source.
429      *
430      * @exception XMLConfigurationException Thrown if there is a
431      * configuration error when initializing the
432      * parser.
433      * @exception IOException Thrown on I/O error.
434      *
435      * @see #parse(boolean)
436      */

437     public void setInputSource(XMLInputSource inputSource)
438         throws XMLConfigurationException, IOException JavaDoc {
439
440         // REVISIT: this method used to reset all the components and
441
// construct the pipeline. Now reset() is called
442
// in parse (boolean) just before we parse the document
443
// Should this method still throw exceptions..?
444

445         fInputSource = inputSource;
446
447     } // setInputSource(XMLInputSource)
448

449     /**
450      * Set the locale to use for messages.
451      *
452      * @param locale The locale object to use for localization of messages.
453      *
454      * @exception XNIException Thrown if the parser does not support the
455      * specified locale.
456      */

457     public void setLocale(Locale JavaDoc locale) throws XNIException {
458         fLocale = locale;
459         fErrorReporter.setLocale(locale);
460     } // setLocale(Locale)
461

462     /**
463      * Sets the document handler on the last component in the pipeline
464      * to receive information about the document.
465      *
466      * @param documentHandler The document handler.
467      */

468     public void setDocumentHandler(XMLDocumentHandler documentHandler) {
469         fDocumentHandler = documentHandler;
470         if (fLastComponent != null) {
471             fLastComponent.setDocumentHandler(fDocumentHandler);
472             if (fDocumentHandler !=null){
473                 fDocumentHandler.setDocumentSource(fLastComponent);
474             }
475         }
476     } // setDocumentHandler(XMLDocumentHandler)
477

478     /** Returns the registered document handler. */
479     public XMLDocumentHandler getDocumentHandler() {
480         return fDocumentHandler;
481     } // getDocumentHandler():XMLDocumentHandler
482

483     /**
484      * Sets the DTD handler.
485      *
486      * @param dtdHandler The DTD handler.
487      */

488     public void setDTDHandler(XMLDTDHandler dtdHandler) {
489         fDTDHandler = dtdHandler;
490     } // setDTDHandler(XMLDTDHandler)
491

492     /** Returns the registered DTD handler. */
493     public XMLDTDHandler getDTDHandler() {
494         return fDTDHandler;
495     } // getDTDHandler():XMLDTDHandler
496

497     /**
498      * Sets the DTD content model handler.
499      *
500      * @param handler The DTD content model handler.
501      */

502     public void setDTDContentModelHandler(XMLDTDContentModelHandler handler) {
503         fDTDContentModelHandler = handler;
504     } // setDTDContentModelHandler(XMLDTDContentModelHandler)
505

506     /** Returns the registered DTD content model handler. */
507     public XMLDTDContentModelHandler getDTDContentModelHandler() {
508         return fDTDContentModelHandler;
509     } // getDTDContentModelHandler():XMLDTDContentModelHandler
510

511     /**
512      * Sets the resolver used to resolve external entities. The EntityResolver
513      * interface supports resolution of public and system identifiers.
514      *
515      * @param resolver The new entity resolver. Passing a null value will
516      * uninstall the currently installed resolver.
517      */

518     public void setEntityResolver(XMLEntityResolver resolver) {
519         fProperties.put(ENTITY_RESOLVER, resolver);
520     } // setEntityResolver(XMLEntityResolver)
521

522     /**
523      * Return the current entity resolver.
524      *
525      * @return The current entity resolver, or null if none
526      * has been registered.
527      * @see #setEntityResolver
528      */

529     public XMLEntityResolver getEntityResolver() {
530         return (XMLEntityResolver)fProperties.get(ENTITY_RESOLVER);
531     } // getEntityResolver():XMLEntityResolver
532

533     /**
534      * Allow an application to register an error event handler.
535      *
536      * <p>If the application does not register an error handler, all
537      * error events reported by the SAX parser will be silently
538      * ignored; however, normal processing may not continue. It is
539      * highly recommended that all SAX applications implement an
540      * error handler to avoid unexpected bugs.</p>
541      *
542      * <p>Applications may register a new or different handler in the
543      * middle of a parse, and the SAX parser must begin using the new
544      * handler immediately.</p>
545      *
546      * @param errorHandler The error handler.
547      * @exception java.lang.NullPointerException If the handler
548      * argument is null.
549      * @see #getErrorHandler
550      */

551     public void setErrorHandler(XMLErrorHandler errorHandler) {
552         fProperties.put(ERROR_HANDLER, errorHandler);
553     } // setErrorHandler(XMLErrorHandler)
554

555     /**
556      * Return the current error handler.
557      *
558      * @return The current error handler, or null if none
559      * has been registered.
560      * @see #setErrorHandler
561      */

562     public XMLErrorHandler getErrorHandler() {
563         // REVISIT: Should this be a property?
564
return (XMLErrorHandler)fProperties.get(ERROR_HANDLER);
565     } // getErrorHandler():XMLErrorHandler
566

567
568     /**
569      * If the application decides to terminate parsing before the xml document
570      * is fully parsed, the application should call this method to free any
571      * resource allocated during parsing. For example, close all opened streams.
572      */

573     public void cleanup() {
574         fEntityManager.closeReaders();
575     }
576
577     /**
578      * Parses the specified input source.
579      *
580      * @param source The input source.
581      *
582      * @exception XNIException Throws exception on XNI error.
583      * @exception java.io.IOException Throws exception on i/o error.
584      */

585     public void parse(XMLInputSource source) throws XNIException, IOException JavaDoc {
586
587         if (fParseInProgress) {
588             // REVISIT - need to add new error message
589
throw new XNIException("FWK005 parse may not be called while parsing.");
590         }
591         fParseInProgress = true;
592
593         try {
594             setInputSource(source);
595             parse(true);
596         } catch (XNIException ex) {
597             if (PRINT_EXCEPTION_STACK_TRACE)
598                 ex.printStackTrace();
599             throw ex;
600         } catch (IOException JavaDoc ex) {
601             if (PRINT_EXCEPTION_STACK_TRACE)
602                 ex.printStackTrace();
603             throw ex;
604         } catch (RuntimeException JavaDoc ex) {
605             if (PRINT_EXCEPTION_STACK_TRACE)
606                 ex.printStackTrace();
607             throw ex;
608         } catch (Exception JavaDoc ex) {
609             if (PRINT_EXCEPTION_STACK_TRACE)
610                 ex.printStackTrace();
611             throw new XNIException(ex);
612         } finally {
613             fParseInProgress = false;
614             // close all streams opened by xerces
615
this.cleanup();
616         }
617
618     } // parse(InputSource)
619

620     public boolean parse(boolean complete) throws XNIException, IOException JavaDoc {
621         //
622
// reset and configure pipeline and set InputSource.
623
if (fInputSource != null) {
624             try {
625                 fValidationManager.reset();
626                 fVersionDetector.reset(this);
627                 resetCommon();
628
629                 short version = fVersionDetector.determineDocVersion(fInputSource);
630                 if (version == Constants.XML_VERSION_1_1) {
631                     initXML11Components();
632                     configureXML11Pipeline();
633                     resetXML11();
634                 } else {
635                     configurePipeline();
636                     reset();
637                 }
638                 
639                 // mark configuration as fixed
640
fConfigUpdated = false;
641
642                 // resets and sets the pipeline.
643
fVersionDetector.startDocumentParsing((XMLEntityHandler) fCurrentScanner, version);
644                 fInputSource = null;
645             } catch (XNIException ex) {
646                 if (PRINT_EXCEPTION_STACK_TRACE)
647                     ex.printStackTrace();
648                 throw ex;
649             } catch (IOException JavaDoc ex) {
650                 if (PRINT_EXCEPTION_STACK_TRACE)
651                     ex.printStackTrace();
652                 throw ex;
653             } catch (RuntimeException JavaDoc ex) {
654                 if (PRINT_EXCEPTION_STACK_TRACE)
655                     ex.printStackTrace();
656                 throw ex;
657             } catch (Exception JavaDoc ex) {
658                 if (PRINT_EXCEPTION_STACK_TRACE)
659                     ex.printStackTrace();
660                 throw new XNIException(ex);
661             }
662         }
663
664         try {
665             return fCurrentScanner.scanDocument(complete);
666         } catch (XNIException ex) {
667             if (PRINT_EXCEPTION_STACK_TRACE)
668                 ex.printStackTrace();
669             throw ex;
670         } catch (IOException JavaDoc ex) {
671             if (PRINT_EXCEPTION_STACK_TRACE)
672                 ex.printStackTrace();
673             throw ex;
674         } catch (RuntimeException JavaDoc ex) {
675             if (PRINT_EXCEPTION_STACK_TRACE)
676                 ex.printStackTrace();
677             throw ex;
678         } catch (Exception JavaDoc ex) {
679             if (PRINT_EXCEPTION_STACK_TRACE)
680                 ex.printStackTrace();
681             throw new XNIException(ex);
682         }
683
684     } // parse(boolean):boolean
685

686     /**
687      * Returns the state of a feature.
688      *
689      * @param featureId The feature identifier.
690          * @return true if the feature is supported
691      *
692      * @throws XMLConfigurationException Thrown for configuration error.
693      * In general, components should
694      * only throw this exception if
695      * it is <strong>really</strong>
696      * a critical error.
697      */

698     public boolean getFeature(String JavaDoc featureId)
699         throws XMLConfigurationException {
700             // make this feature special
701
if (featureId.equals(PARSER_SETTINGS)){
702             return fConfigUpdated;
703         }
704         return super.getFeature(featureId);
705
706     } // getFeature(String):boolean
707

708     /**
709      * Set the state of a feature.
710      *
711      * Set the state of any feature in a SAX2 parser. The parser
712      * might not recognize the feature, and if it does recognize
713      * it, it might not be able to fulfill the request.
714      *
715      * @param featureId The unique identifier (URI) of the feature.
716      * @param state The requested state of the feature (true or false).
717      *
718      * @exception org.apache.xerces.xni.parser.XMLConfigurationException If the
719      * requested feature is not known.
720      */

721     public void setFeature(String JavaDoc featureId, boolean state)
722         throws XMLConfigurationException {
723         fConfigUpdated = true;
724         // forward to every XML 1.0 component
725
int count = fComponents.size();
726         for (int i = 0; i < count; i++) {
727             XMLComponent c = (XMLComponent) fComponents.get(i);
728             c.setFeature(featureId, state);
729         }
730         // forward it to common components
731
count = fCommonComponents.size();
732         for (int i = 0; i < count; i++) {
733             XMLComponent c = (XMLComponent) fCommonComponents.get(i);
734             c.setFeature(featureId, state);
735         }
736                 
737         // forward to every XML 1.1 component
738
count = fXML11Components.size();
739         for (int i = 0; i < count; i++) {
740             XMLComponent c = (XMLComponent) fXML11Components.get(i);
741             try{
742                 c.setFeature(featureId, state);
743             }
744             catch (Exception JavaDoc e){
745                 // no op
746
}
747         }
748         // save state if noone "objects"
749
super.setFeature(featureId, state);
750
751     } // setFeature(String,boolean)
752

753     /**
754      * setProperty
755      *
756      * @param propertyId
757      * @param value
758      */

759     public void setProperty(String JavaDoc propertyId, Object JavaDoc value)
760         throws XMLConfigurationException {
761         fConfigUpdated = true;
762         // forward to every XML 1.0 component
763
int count = fComponents.size();
764         for (int i = 0; i < count; i++) {
765             XMLComponent c = (XMLComponent) fComponents.get(i);
766             c.setProperty(propertyId, value);
767         }
768         // forward it to every common Component
769
count = fCommonComponents.size();
770         for (int i = 0; i < count; i++) {
771             XMLComponent c = (XMLComponent) fCommonComponents.get(i);
772             c.setProperty(propertyId, value);
773         }
774         // forward it to every XML 1.1 component
775
count = fXML11Components.size();
776         for (int i = 0; i < count; i++) {
777             XMLComponent c = (XMLComponent) fXML11Components.get(i);
778             try{
779                 c.setProperty(propertyId, value);
780             }
781             catch (Exception JavaDoc e){
782                 // ignore it
783
}
784         }
785
786         // store value if noone "objects"
787
super.setProperty(propertyId, value);
788
789     } // setProperty(String,Object)
790

791
792     /** Returns the locale. */
793     public Locale JavaDoc getLocale() {
794         return fLocale;
795     } // getLocale():Locale
796

797     /**
798      * reset all XML 1.0 components before parsing and namespace context
799      */

800     protected void reset() throws XNIException {
801         int count = fComponents.size();
802         for (int i = 0; i < count; i++) {
803             XMLComponent c = (XMLComponent) fComponents.get(i);
804             c.reset(this);
805         }
806
807     } // reset()
808

809     /**
810      * reset all common components before parsing
811      */

812     protected void resetCommon() throws XNIException {
813         // reset common components
814
int count = fCommonComponents.size();
815         for (int i = 0; i < count; i++) {
816             XMLComponent c = (XMLComponent) fCommonComponents.get(i);
817             c.reset(this);
818         }
819
820     } // resetCommon()
821

822     
823     /**
824      * reset all components before parsing and namespace context
825      */

826     protected void resetXML11() throws XNIException {
827         // reset every component
828
int count = fXML11Components.size();
829         for (int i = 0; i < count; i++) {
830             XMLComponent c = (XMLComponent) fXML11Components.get(i);
831             c.reset(this);
832         }
833
834     } // resetXML11()
835

836
837     /**
838      * Configures the XML 1.1 pipeline.
839      * Note: this method also resets the new XML11 components.
840      */

841     protected void configureXML11Pipeline() {
842         if (fCurrentDVFactory != fXML11DatatypeFactory) {
843             fCurrentDVFactory = fXML11DatatypeFactory;
844             setProperty(DATATYPE_VALIDATOR_FACTORY, fCurrentDVFactory);
845         }
846         
847         // setup DTD pipeline
848
if (fCurrentDTDScanner != fXML11DTDScanner) {
849             fCurrentDTDScanner = fXML11DTDScanner;
850             setProperty(DTD_SCANNER, fCurrentDTDScanner);
851         }
852         fXML11DTDScanner.setDTDHandler(fDTDHandler);
853         fXML11DTDScanner.setDTDContentModelHandler(fDTDContentModelHandler);
854
855         // setup XML 1.1 document pipeline
856
if (fFeatures.get(NAMESPACES) == Boolean.TRUE) {
857             if (fCurrentScanner != fXML11NSDocScanner) {
858                 fCurrentScanner = fXML11NSDocScanner;
859                 setProperty(DOCUMENT_SCANNER, fXML11NSDocScanner);
860             }
861
862             fXML11NSDocScanner.setDTDValidator(null);
863             fXML11NSDocScanner.setDocumentHandler(fDocumentHandler);
864             if (fDocumentHandler != null) {
865                 fDocumentHandler.setDocumentSource(fXML11NSDocScanner);
866             }
867             fLastComponent = fXML11NSDocScanner;
868
869         } else {
870             // create components
871
if (fXML11DocScanner == null) {
872                     // non namespace document pipeline
873
fXML11DocScanner = new XML11DocumentScannerImpl();
874                     addXML11Component(fXML11DocScanner);
875               }
876             if (fCurrentScanner != fXML11DocScanner) {
877                 fCurrentScanner = fXML11DocScanner;
878                 setProperty(DOCUMENT_SCANNER, fXML11DocScanner);
879             }
880             fXML11DocScanner.setDocumentHandler(fDocumentHandler);
881
882             if (fDocumentHandler != null) {
883                 fDocumentHandler.setDocumentSource(fXML11DocScanner);
884             }
885             fLastComponent = fXML11DocScanner;
886         }
887
888     } // configureXML11Pipeline()
889

890     /** Configures the pipeline. */
891     protected void configurePipeline() {
892         if (fCurrentDVFactory != fDatatypeValidatorFactory) {
893             fCurrentDVFactory = fDatatypeValidatorFactory;
894             // use XML 1.0 datatype library
895
setProperty(DATATYPE_VALIDATOR_FACTORY, fCurrentDVFactory);
896         }
897
898         // setup DTD pipeline
899
if (fCurrentDTDScanner != fDTDScanner) {
900             fCurrentDTDScanner = fDTDScanner;
901             setProperty(DTD_SCANNER, fCurrentDTDScanner);
902         }
903         fDTDScanner.setDTDHandler(fDTDHandler);
904         fDTDScanner.setDTDContentModelHandler(fDTDContentModelHandler);
905
906         // setup document pipeline
907
if (fFeatures.get(NAMESPACES) == Boolean.TRUE) {
908             if (fCurrentScanner != fNamespaceScanner) {
909                 fCurrentScanner = fNamespaceScanner;
910                 setProperty(DOCUMENT_SCANNER, fNamespaceScanner);
911             }
912             fNamespaceScanner.setDTDValidator(null);
913             fNamespaceScanner.setDocumentHandler(fDocumentHandler);
914             if (fDocumentHandler != null) {
915                 fDocumentHandler.setDocumentSource(fNamespaceScanner);
916             }
917             fLastComponent = fNamespaceScanner;
918         } else {
919             // create components
920
if (fNonNSScanner == null) {
921                 fNonNSScanner = new XMLDocumentScannerImpl();
922                 // add components
923
addComponent((XMLComponent) fNonNSScanner);
924               
925             }
926             if (fCurrentScanner != fNonNSScanner) {
927                 fCurrentScanner = fNonNSScanner;
928                 setProperty(DOCUMENT_SCANNER, fNonNSScanner);
929     
930             }
931
932             fNonNSScanner.setDocumentHandler(fDocumentHandler);
933             if (fDocumentHandler != null) {
934                 fDocumentHandler.setDocumentSource(fNonNSScanner);
935             }
936             fLastComponent = fNonNSScanner;
937         }
938
939     } // configurePipeline()
940

941
942     // features and properties
943

944     /**
945      * Check a feature. If feature is know and supported, this method simply
946      * returns. Otherwise, the appropriate exception is thrown.
947      *
948      * @param featureId The unique identifier (URI) of the feature.
949      *
950      * @throws XMLConfigurationException Thrown for configuration error.
951      * In general, components should
952      * only throw this exception if
953      * it is <strong>really</strong>
954      * a critical error.
955      */

956     protected void checkFeature(String JavaDoc featureId) throws XMLConfigurationException {
957
958         //
959
// Xerces Features
960
//
961

962         if (featureId.startsWith(Constants.XERCES_FEATURE_PREFIX)) {
963             final int suffixLength = featureId.length() - Constants.XERCES_FEATURE_PREFIX.length();
964             
965             //
966
// http://apache.org/xml/features/validation/dynamic
967
// Allows the parser to validate a document only when it
968
// contains a grammar. Validation is turned on/off based
969
// on each document instance, automatically.
970
//
971
if (suffixLength == Constants.DYNAMIC_VALIDATION_FEATURE.length() &&
972                 featureId.endsWith(Constants.DYNAMIC_VALIDATION_FEATURE)) {
973                 return;
974             }
975
976             //
977
// http://apache.org/xml/features/validation/default-attribute-values
978
//
979
if (suffixLength == Constants.DEFAULT_ATTRIBUTE_VALUES_FEATURE.length() &&
980                 featureId.endsWith(Constants.DEFAULT_ATTRIBUTE_VALUES_FEATURE)) {
981                 // REVISIT
982
short type = XMLConfigurationException.NOT_SUPPORTED;
983                 throw new XMLConfigurationException(type, featureId);
984             }
985             //
986
// http://apache.org/xml/features/validation/default-attribute-values
987
//
988
if (suffixLength == Constants.VALIDATE_CONTENT_MODELS_FEATURE.length() &&
989                 featureId.endsWith(Constants.VALIDATE_CONTENT_MODELS_FEATURE)) {
990                 // REVISIT
991
short type = XMLConfigurationException.NOT_SUPPORTED;
992                 throw new XMLConfigurationException(type, featureId);
993             }
994             //
995
// http://apache.org/xml/features/validation/nonvalidating/load-dtd-grammar
996
//
997
if (suffixLength == Constants.LOAD_DTD_GRAMMAR_FEATURE.length() &&
998                 featureId.endsWith(Constants.LOAD_DTD_GRAMMAR_FEATURE)) {
999                 return;
1000            }
1001            //
1002
// http://apache.org/xml/features/validation/nonvalidating/load-external-dtd
1003
//
1004
if (suffixLength == Constants.LOAD_EXTERNAL_DTD_FEATURE.length() &&
1005                featureId.endsWith(Constants.LOAD_EXTERNAL_DTD_FEATURE)) {
1006                return;
1007            }
1008
1009            //
1010
// http://apache.org/xml/features/validation/default-attribute-values
1011
//
1012
if (suffixLength == Constants.VALIDATE_DATATYPES_FEATURE.length() &&
1013                featureId.endsWith(Constants.VALIDATE_DATATYPES_FEATURE)) {
1014                short type = XMLConfigurationException.NOT_SUPPORTED;
1015                throw new XMLConfigurationException(type, featureId);
1016            }
1017                         
1018            // special performance feature: only component manager is allowed to set it.
1019
if (suffixLength == Constants.PARSER_SETTINGS.length() &&
1020                featureId.endsWith(Constants.PARSER_SETTINGS)) {
1021                short type = XMLConfigurationException.NOT_SUPPORTED;
1022                throw new XMLConfigurationException(type, featureId);
1023            }
1024        }
1025
1026        //
1027
// Not recognized
1028
//
1029

1030        super.checkFeature(featureId);
1031
1032    } // checkFeature(String)
1033

1034    /**
1035     * Check a property. If the property is know and supported, this method
1036     * simply returns. Otherwise, the appropriate exception is thrown.
1037     *
1038     * @param propertyId The unique identifier (URI) of the property
1039     * being set.
1040     *
1041     * @throws XMLConfigurationException Thrown for configuration error.
1042     * In general, components should
1043     * only throw this exception if
1044     * it is <strong>really</strong>
1045     * a critical error.
1046     */

1047    protected void checkProperty(String JavaDoc propertyId) throws XMLConfigurationException {
1048
1049        //
1050
// Xerces Properties
1051
//
1052

1053        if (propertyId.startsWith(Constants.XERCES_PROPERTY_PREFIX)) {
1054            final int suffixLength = propertyId.length() - Constants.XERCES_PROPERTY_PREFIX.length();
1055
1056            if (suffixLength == Constants.DTD_SCANNER_PROPERTY.length() &&
1057                propertyId.endsWith(Constants.DTD_SCANNER_PROPERTY)) {
1058                return;
1059            }
1060        }
1061        
1062        if (propertyId.startsWith(Constants.JAXP_PROPERTY_PREFIX)) {
1063            final int suffixLength = propertyId.length() - Constants.JAXP_PROPERTY_PREFIX.length();
1064
1065            if (suffixLength == Constants.SCHEMA_SOURCE.length() &&
1066                propertyId.endsWith(Constants.SCHEMA_SOURCE)) {
1067                return;
1068            }
1069        }
1070        
1071        // special cases
1072
if (propertyId.startsWith(Constants.SAX_PROPERTY_PREFIX)) {
1073            final int suffixLength = propertyId.length() - Constants.SAX_PROPERTY_PREFIX.length();
1074            
1075            //
1076
// http://xml.org/sax/properties/xml-string
1077
// Value type: String
1078
// Access: read-only
1079
// Get the literal string of characters associated with the
1080
// current event. If the parser recognises and supports this
1081
// property but is not currently parsing text, it should return
1082
// null (this is a good way to check for availability before the
1083
// parse begins).
1084
//
1085
if (suffixLength == Constants.XML_STRING_PROPERTY.length() &&
1086                propertyId.endsWith(Constants.XML_STRING_PROPERTY)) {
1087                // REVISIT - we should probably ask xml-dev for a precise
1088
// definition of what this is actually supposed to return, and
1089
// in exactly which circumstances.
1090
short type = XMLConfigurationException.NOT_SUPPORTED;
1091                throw new XMLConfigurationException(type, propertyId);
1092            }
1093        }
1094
1095        //
1096
// Not recognized
1097
//
1098

1099        super.checkProperty(propertyId);
1100
1101    } // checkProperty(String)
1102

1103
1104    /**
1105     * Adds a component to the parser configuration. This method will
1106     * also add all of the component's recognized features and properties
1107     * to the list of default recognized features and properties.
1108     *
1109     * @param component The component to add.
1110     */

1111    protected void addComponent(XMLComponent component) {
1112
1113        // don't add a component more than once
1114
if (fComponents.contains(component)) {
1115            return;
1116        }
1117        fComponents.add(component);
1118        addRecognizedParamsAndSetDefaults(component);
1119    
1120    } // addComponent(XMLComponent)
1121

1122    /**
1123     * Adds common component to the parser configuration. This method will
1124     * also add all of the component's recognized features and properties
1125     * to the list of default recognized features and properties.
1126     *
1127     * @param component The component to add.
1128     */

1129    protected void addCommonComponent(XMLComponent component) {
1130
1131        // don't add a component more than once
1132
if (fCommonComponents.contains(component)) {
1133            return;
1134        }
1135        fCommonComponents.add(component);
1136        addRecognizedParamsAndSetDefaults(component);
1137
1138    } // addCommonComponent(XMLComponent)
1139

1140    /**
1141     * Adds an XML 1.1 component to the parser configuration. This method will
1142     * also add all of the component's recognized features and properties
1143     * to the list of default recognized features and properties.
1144     *
1145     * @param component The component to add.
1146     */

1147    protected void addXML11Component(XMLComponent component) {
1148
1149        // don't add a component more than once
1150
if (fXML11Components.contains(component)) {
1151            return;
1152        }
1153        fXML11Components.add(component);
1154        addRecognizedParamsAndSetDefaults(component);
1155        
1156    } // addXML11Component(XMLComponent)
1157

1158    /**
1159     * Adds all of the component's recognized features and properties
1160     * to the list of default recognized features and properties, and
1161     * sets default values on the configuration for features and
1162     * properties which were previously absent from the configuration.
1163     *
1164     * @param component The component whose recognized features
1165     * and properties will be added to the configuration
1166     */

1167    protected void addRecognizedParamsAndSetDefaults(XMLComponent component) {
1168        
1169        // register component's recognized features
1170
String JavaDoc[] recognizedFeatures = component.getRecognizedFeatures();
1171        addRecognizedFeatures(recognizedFeatures);
1172        
1173        // register component's recognized properties
1174
String JavaDoc[] recognizedProperties = component.getRecognizedProperties();
1175        addRecognizedProperties(recognizedProperties);
1176
1177        // set default values
1178
if (recognizedFeatures != null) {
1179            for (int i = 0; i < recognizedFeatures.length; ++i) {
1180                String JavaDoc featureId = recognizedFeatures[i];
1181                Boolean JavaDoc state = component.getFeatureDefault(featureId);
1182                if (state != null) {
1183                    // Do not overwrite values already set on the configuration.
1184
if (!fFeatures.containsKey(featureId)) {
1185                        fFeatures.put(featureId, state);
1186                        // For newly added components who recognize this feature
1187
// but did not offer a default value, we need to make
1188
// sure these components will get an opportunity to read
1189
// the value before parsing begins.
1190
fConfigUpdated = true;
1191                    }
1192                }
1193            }
1194        }
1195        if (recognizedProperties != null) {
1196            for (int i = 0; i < recognizedProperties.length; ++i) {
1197                String JavaDoc propertyId = recognizedProperties[i];
1198                Object JavaDoc value = component.getPropertyDefault(propertyId);
1199                if (value != null) {
1200                    // Do not overwrite values already set on the configuration.
1201
if (!fProperties.containsKey(propertyId)) {
1202                        fProperties.put(propertyId, value);
1203                        // For newly added components who recognize this property
1204
// but did not offer a default value, we need to make
1205
// sure these components will get an opportunity to read
1206
// the value before parsing begins.
1207
fConfigUpdated = true;
1208                    }
1209                }
1210            }
1211        }
1212    }
1213
1214    private void initXML11Components() {
1215        if (!f11Initialized) {
1216
1217            // create datatype factory
1218
fXML11DatatypeFactory = DTDDVFactory.getInstance(XML11_DATATYPE_VALIDATOR_FACTORY);
1219
1220            // setup XML 1.1 DTD pipeline
1221
fXML11DTDScanner = new XML11DTDScannerImpl();
1222            addXML11Component(fXML11DTDScanner);
1223
1224            // setup XML 1.1. document pipeline - namespace aware
1225
fXML11NSDocScanner = new XML11NSDocumentScannerImpl();
1226            addXML11Component(fXML11NSDocScanner);
1227            
1228            f11Initialized = true;
1229        }
1230    }
1231
1232} // class XML11NonValidatingConfiguration
1233
Popular Tags