KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xerces > internal > jaxp > SAXParserImpl


1 /*
2  *
3  * The Apache Software License, Version 1.1
4  *
5  *
6  * Copyright (c) 2000-2004 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 "Xerces" 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 and was
53  * originally based on software copyright (c) 1999, Sun Microsystems, Inc.,
54  * http://www.sun.com. For more information on the Apache Software
55  * Foundation, please see <http://www.apache.org/>.
56  */

57
58 package com.sun.org.apache.xerces.internal.jaxp;
59
60 import java.util.Enumeration JavaDoc;
61 import java.util.HashMap JavaDoc;
62 import java.util.Hashtable JavaDoc;
63
64 import javax.xml.parsers.SAXParserFactory JavaDoc;
65 import javax.xml.validation.Schema JavaDoc;
66
67 import com.sun.org.apache.xerces.internal.impl.Constants;
68 import com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser;
69 import com.sun.org.apache.xerces.internal.parsers.JAXPConfiguration;
70 import org.xml.sax.SAXException JavaDoc;
71 import org.xml.sax.SAXNotRecognizedException JavaDoc;
72 import org.xml.sax.SAXNotSupportedException JavaDoc;
73 import org.xml.sax.XMLReader JavaDoc;
74 import com.sun.org.apache.xerces.internal.util.SecurityManager;
75 import com.sun.org.apache.xerces.internal.util.SAXMessageFormatter;
76 import com.sun.org.apache.xerces.internal.xni.XNIException;
77 import com.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration;
78
79 /**
80  * This is the implementation specific class for the
81  * <code>javax.xml.parsers.SAXParser</code>.
82  *
83  * @author Rajiv Mordani
84  * @author Edwin Goei
85  *
86  * @version $Id: SAXParserImpl.java,v 1.1.2.2 2007/03/09 16:11:55 spericas Exp $
87  */

88 public class SAXParserImpl extends javax.xml.parsers.SAXParser JavaDoc
89     implements JAXPConstants {
90
91         // Should XMLParserConfiguration have reset, ? we have reset at component level
92
private final JAXPConfiguration parserConfiguration;
93     private final AbstractSAXParser xmlReader;
94     private String JavaDoc schemaLanguage = null; // null means DTD
95
private final Schema JavaDoc grammar;
96     private final SecurityManager JavaDoc secureProcessing;
97     private boolean isXIncludeAware;
98     private boolean enableSecureProcessing = true;
99
100     //we have to keep the reference to features and SAXParserFactory so that
101
//we can set the SAXParser to the same state when it
102
//was createed from the factory.
103
private Hashtable JavaDoc features;
104     private SAXParserFactory JavaDoc spf;
105     
106     private Hashtable JavaDoc parserFeatures = new Hashtable JavaDoc();
107     
108     public boolean isXIncludeAware() {
109         return isXIncludeAware;
110     }
111     
112
113     /**
114      * Create a SAX parser with the associated features
115      * @param features Hashtable of SAX features, may be null
116      */

117     SAXParserImpl(SAXParserFactory JavaDoc spfactory, Hashtable JavaDoc factoryfeatures)
118         throws SAXException JavaDoc
119     {
120         this.spf = spfactory ;
121         this.features = factoryfeatures;
122         // inherit
123
secureProcessing = new SecurityManager JavaDoc();
124         this.grammar = spf.getSchema();
125         parserConfiguration = new JAXPConfiguration(grammar);
126         xmlReader = new com.sun.org.apache.xerces.internal.parsers.SAXParser(parserConfiguration);
127         
128         //initialize the feature as per factory settings..
129
init();
130     }
131
132     /** Reset this instance back to factory settings */
133     void resetSettings() throws SAXNotSupportedException JavaDoc, SAXNotRecognizedException JavaDoc {
134         Enumeration JavaDoc keys = parserFeatures.keys();
135         
136         while(keys.hasMoreElements()){
137             String JavaDoc propertyId = (String JavaDoc)keys.nextElement();
138             Object JavaDoc value = parserFeatures.get(propertyId);
139             if(value instanceof Boolean JavaDoc){
140                 //System.out.println("Remvoing feature = " + propertyId + " with value = " + parserConfiguration.getFeatureDefaultValue(propertyId));
141
//this means it is a feature, we have to get default value from the configuration
142
xmlReader.setFeature(propertyId, parserConfiguration.getFeatureDefaultValue(propertyId));
143             }
144             else{//it's a property
145
//System.out.println("Remvoing property = " + propertyId);
146
//null value should delete the property from underlying implementation.
147
xmlReader.setProperty(propertyId, null);
148             }
149         }
150         //clear the hashtable once we have removed all the properties.
151
parserFeatures.clear();
152         
153     }
154     
155     //initialize the features as per factory settings.
156
void init() throws SAXNotSupportedException JavaDoc, SAXNotRecognizedException JavaDoc {
157                 
158         schemaLanguage = null ;
159         this.isXIncludeAware = spf.isXIncludeAware();
160         if(features != null ){
161             Object JavaDoc tmpValue = features.get(Constants.FEATURE_SECURE_PROCESSING);
162             if( tmpValue != null )
163                 enableSecureProcessing = ((Boolean JavaDoc)tmpValue).booleanValue();
164         }
165         
166         if(enableSecureProcessing){
167             try {
168                 setProperty(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, secureProcessing);
169             } catch (SAXNotRecognizedException JavaDoc sex) {
170                 sex.printStackTrace();
171             } catch (SAXNotSupportedException JavaDoc se) {
172                 se.printStackTrace();
173             }
174         }
175         
176         xmlReader.setFeature(
177                 Constants.XERCES_FEATURE_PREFIX + Constants.XINCLUDE_AWARE,
178                 isXIncludeAware);
179         
180         // If validating, provide a default ErrorHandler that prints
181
// validation errors with a warning telling the user to set an
182
// ErrorHandler.
183
if (spf.isValidating()) {
184             xmlReader.setErrorHandler(new DefaultValidationErrorHandler());
185         }
186
187         xmlReader.setFeature(Constants.SAX_FEATURE_PREFIX +
188                              Constants.VALIDATION_FEATURE, spf.isValidating());
189
190         // JAXP "namespaceAware" == SAX Namespaces feature
191
// Note: there is a compatibility problem here with default values:
192
// JAXP default is false while SAX 2 default is true!
193
xmlReader.setFeature(Constants.SAX_FEATURE_PREFIX +
194                              Constants.NAMESPACES_FEATURE,
195                              spf.isNamespaceAware());
196
197         // SAX "namespaces" and "namespace-prefixes" features should not
198
// both be false. We make them opposite for backward compatibility
199
// since JAXP 1.0 apps may want to receive xmlns* attributes.
200
xmlReader.setFeature(Constants.SAX_FEATURE_PREFIX +
201                              Constants.NAMESPACE_PREFIXES_FEATURE,
202                              !spf.isNamespaceAware());
203         setFeatures(features);
204         
205     }//init()
206

207     /**
208      * Set any features of our XMLReader based on any features set on the
209      * SAXParserFactory.
210      *
211      * XXX Does not handle possible conflicts between SAX feature names and
212      * JAXP specific feature names, eg. SAXParserFactory.isValidating()
213      */

214     private void setFeatures(Hashtable JavaDoc features)
215         throws SAXNotSupportedException JavaDoc, SAXNotRecognizedException JavaDoc
216     {
217         if (features != null) {
218             for (Enumeration JavaDoc e = features.keys(); e.hasMoreElements();) {
219                 String JavaDoc feature = (String JavaDoc)e.nextElement();
220                 boolean value = ((Boolean JavaDoc)features.get(feature)).booleanValue();
221                 if(!feature.equals(Constants.FEATURE_SECURE_PROCESSING))
222                     xmlReader.setFeature(feature, value);
223             }
224         }
225     }
226     
227     /**
228      * @deprecated
229      */

230     public org.xml.sax.Parser JavaDoc getParser() throws SAXException JavaDoc {
231         return xmlReader;
232     }
233
234     /**
235       * <p>Reset this <code>DocumentBuilder</code> to its original configuration.</p>
236       *
237       * <p><code>DocumentBuilder</code> is reset to the same state as when it was created with
238       * {@link DocumentBuilderFactory#newDocumentBuilder()}.
239       * <code>reset()</code> is designed to allow the reuse of existing <code>DocumentBuilder</code>s
240       * thus saving resources associated with the creation of new <code>DocumentBuilder</code>s.</p>
241       *
242       * <p>The reset <code>DocumentBuilder</code> is not guaranteed to have the same {@link EntityResolver} or {@link ErrorHandler}
243       * <code>Object</code>s, e.g. {@link Object#equals(Object obj)}. It is guaranteed to have a functionally equal
244       * <code>EntityResolver</code> and <code>ErrorHandler</code>.</p>
245       *
246       * @since 1.5
247       */

248
249     public void reset(){
250         if(xmlReader != null){
251             try{
252                 xmlReader.reset();
253                 //set the object back to its factory settings
254
resetSettings();
255                 
256             }
257             //xxx: underlying implementation reset throws XNIException what should we do in this case ?
258
//if there was any propery that is not being supported
259
//exception would have been thrown when setting it on the underlying implementation.
260
catch(XNIException ex){
261                 //coninue.
262
}
263             catch(SAXException JavaDoc sax){}
264         }
265     }
266
267     
268     /**
269      * Returns the XMLReader that is encapsulated by the implementation of
270      * this class.
271      */

272     public XMLReader JavaDoc getXMLReader() {
273         return xmlReader;
274     }
275
276     public boolean isNamespaceAware() {
277         try {
278             return xmlReader.getFeature(Constants.SAX_FEATURE_PREFIX +
279                                         Constants.NAMESPACES_FEATURE);
280         } catch (SAXException JavaDoc x) {
281             throw new IllegalStateException JavaDoc(x.getMessage());
282         }
283     }
284
285     public boolean isValidating() {
286         try {
287             return xmlReader.getFeature(Constants.SAX_FEATURE_PREFIX +
288                                         Constants.VALIDATION_FEATURE);
289         } catch (SAXException JavaDoc x) {
290             throw new IllegalStateException JavaDoc(x.getMessage());
291         }
292     }
293
294     /**
295      * Sets the particular property in the underlying implementation of
296      * org.xml.sax.XMLReader.
297      */

298     public void setProperty(String JavaDoc name, Object JavaDoc value)
299         throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc
300     {
301         // the spec says if a schema is given via SAXParserFactory
302
// the JAXP 1.2 properties shouldn't be allowed. So
303
// reject them first.
304
if(grammar!=null) {
305             if (JAXP_SCHEMA_LANGUAGE.equals(name)
306             || JAXP_SCHEMA_SOURCE.equals(name)) {
307                 throw new SAXNotSupportedException JavaDoc(
308                     SAXMessageFormatter.formatMessage(null, "schema-already-specified", null));
309             }
310         }
311         
312         if (JAXP_SCHEMA_LANGUAGE.equals(name)) {
313             // JAXP 1.2 support
314
if ( W3C_XML_SCHEMA.equals(value) ) {
315                 //None of the properties will take effect till the setValidating(true) has been called
316
if( isValidating() ) {
317                     schemaLanguage = W3C_XML_SCHEMA;
318                     xmlReader.setFeature(Constants.XERCES_FEATURE_PREFIX +
319                                      Constants.SCHEMA_VALIDATION_FEATURE,
320                                      true);
321                     //also set the schema full checking to true.
322
xmlReader.setFeature(Constants.XERCES_FEATURE_PREFIX +
323                                      Constants.SCHEMA_FULL_CHECKING,
324                                      true);
325                     //add this among the list of parser features since this is added
326
//on the parser instance and should be set to default value during
327
//reset.
328
parserFeatures.put(Constants.XERCES_FEATURE_PREFIX +
329                                      Constants.SCHEMA_VALIDATION_FEATURE, new Boolean JavaDoc(true));
330                     parserFeatures.put(Constants.XERCES_FEATURE_PREFIX +
331                                      Constants.SCHEMA_FULL_CHECKING, new Boolean JavaDoc(true));
332                                      
333                     // this will allow the parser not to emit DTD-related
334
// errors, as the spec demands
335
xmlReader.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
336                     parserFeatures.put(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
337                     
338                 }
339                 else{
340                     //System.out.println("Property = " + name + "is not set");
341
}
342                 
343             } else if (value == null) {
344                 schemaLanguage = null;
345                 xmlReader.setFeature(Constants.XERCES_FEATURE_PREFIX +
346                                      Constants.SCHEMA_VALIDATION_FEATURE,
347                                      false);
348                 parserFeatures.put(Constants.XERCES_FEATURE_PREFIX +
349                                      Constants.SCHEMA_VALIDATION_FEATURE,
350                                      new Boolean JavaDoc(false));
351                 
352             } else {
353                 // REVISIT: It would be nice if we could format this message
354
// using a user specified locale as we do in the underlying
355
// XMLReader -- mrglavas
356
throw new SAXNotSupportedException JavaDoc(
357                     SAXMessageFormatter.formatMessage(null, "schema-not-supported", null));
358             }
359         }
360         else if(JAXP_SCHEMA_SOURCE.equals(name)) {
361             //If we are not validating then don't check for JAXP_SCHEMA_LANGUAGE, JAXP_SCHEMA_SOURCED
362
if ( isValidating() ) {
363                 String JavaDoc val = (String JavaDoc)getProperty(JAXP_SCHEMA_LANGUAGE);
364                 if ( val != null && W3C_XML_SCHEMA.equals(val) ) {
365                     xmlReader.setProperty(name, value);
366                     parserFeatures.put(name, value);
367                 }
368                 else {
369                     throw new SAXNotSupportedException JavaDoc(
370                         SAXMessageFormatter.formatMessage(null,
371                         "jaxp-order-not-supported",
372                         new Object JavaDoc[] {JAXP_SCHEMA_LANGUAGE, JAXP_SCHEMA_SOURCE}));
373                 }
374             }
375         }
376         /*else if(name.equlas(Constants.ENTITY_EXPANSION_LIMIT)){
377             String elimit = (String)value;
378             if(elimit != null && elimit != ""){
379                 int val = Integer.parseInt(elimit);
380                 secureProcessing.setEntityExpansionLimit(val);
381             }
382         }else if(name.equals(Constants.MAX_OCCUR_LIMIT)) {
383             String mlimit = (String)value;
384             if(mlimit != null && mlimit != ""){
385                 int val = Integer.parseInt(mlimit);
386                 secureProcessing.setMaxOccurNodeLimit(val);
387             }
388         }*/

389         else if(value instanceof Boolean JavaDoc){
390             //assume feature
391
xmlReader.setFeature(name,((Boolean JavaDoc)value).booleanValue());
392             parserFeatures.put(name, value);
393         }
394         else{
395             xmlReader.setProperty(name, value);
396             // If value is null, remove property from Hashtable
397
if (value == null) {
398                 parserFeatures.remove(name);
399             } else {
400                 parserFeatures.put(name, value);
401             }
402         }
403     }
404
405     /**
406      * returns the particular property requested for in the underlying
407      * implementation of org.xml.sax.XMLReader.
408      */

409     public Object JavaDoc getProperty(String JavaDoc name)
410         throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc
411     {
412         // TODO: reroute those properties to use new JAXP1.3 API. -KK
413
if (JAXP_SCHEMA_LANGUAGE.equals(name)) {
414             // JAXP 1.2 support
415
return schemaLanguage;
416         } else {
417             return xmlReader.getProperty(name);
418         }
419     }
420
421     
422     public Schema JavaDoc getSchema(){
423         return grammar;
424     }
425     
426     /**
427      * <p>Return True if secure processing in effect.</p>
428      * Defaults to <code>false</code>.</p>
429      *
430      * @return state of Schema Caching
431      */

432     public boolean isSecureProcessing(){
433         return secureProcessing!=null;
434     }
435
436     
437 }
438
Popular Tags