Path: blob/master/src/java.xml/share/classes/javax/xml/parsers/SAXParserFactory.java
40948 views
/*1* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.xml.parsers;2627import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;28import javax.xml.validation.Schema;29import org.xml.sax.SAXException;30import org.xml.sax.SAXNotRecognizedException;31import org.xml.sax.SAXNotSupportedException;3233/**34* Defines a factory API that enables applications to configure and35* obtain a SAX based parser to parse XML documents.36*37* @author Jeff Suttor38* @author Neeraj Bajaj39*40* @since 1.441*/42public abstract class SAXParserFactory {43private static final String DEFAULT_IMPL =44"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl";4546/**47* Should Parsers be validating?48*/49private boolean validating = false;5051/**52* Should Parsers be namespace aware?53*/54private boolean namespaceAware = false;5556/**57* Protected constructor to force use of {@link #newInstance()}.58*/59protected SAXParserFactory () {6061}6263/**64* Creates a new NamespaceAware instance of the {@code SAXParserFactory}65* builtin system-default implementation. Parsers produced by the factory66* instance provides support for XML namespaces by default.67*68* @implSpec69* In addition to creating a factory instance using the same process as70* {@link #newDefaultInstance()}, this method must set NamespaceAware to true.71*72* @return a new instance of the {@code SAXParserFactory} builtin73* system-default implementation.74*75* @since 1376*/77public static SAXParserFactory newDefaultNSInstance() {78return makeNSAware(new SAXParserFactoryImpl());79}8081/**82* Creates a new NamespaceAware instance of a {@code SAXParserFactory}.83* Parsers produced by the factory instance provides support for XML84* namespaces by default.85*86* @implSpec87* In addition to creating a factory instance using the same process as88* {@link #newInstance()}, this method must set NamespaceAware to true.89*90* @return a new instance of the {@code SAXParserFactory}91*92* @throws FactoryConfigurationError in case of {@linkplain93* java.util.ServiceConfigurationError service configuration error}94* or if the implementation is not available or cannot be instantiated.95*96* @since 1397*/98public static SAXParserFactory newNSInstance() {99return makeNSAware(FactoryFinder.find(SAXParserFactory.class, DEFAULT_IMPL));100}101102/**103* Creates a new NamespaceAware instance of a {@code SAXParserFactory} from104* the class name. Parsers produced by the factory instance provides105* support for XML namespaces by default.106*107* @implSpec108* In addition to creating a factory instance using the same process as109* {@link #newInstance(java.lang.String, java.lang.ClassLoader)}, this method110* must set NamespaceAware to true.111*112* @param factoryClassName a fully qualified factory class name that provides113* implementation of114* {@code javax.xml.parsers.SAXParserFactory}.115*116* @param classLoader the {@code ClassLoader} used to load the factory class.117* If it is {@code null}, the current {@code Thread}'s118* context classLoader is used to load the factory class.119*120* @return a new instance of the {@code SAXParserFactory}121*122* @throws FactoryConfigurationError if {@code factoryClassName} is {@code null}, or123* the factory class cannot be loaded, instantiated.124*125* @since 13126*/127public static SAXParserFactory newNSInstance(String factoryClassName,128ClassLoader classLoader) {129return makeNSAware(FactoryFinder.newInstance(130SAXParserFactory.class, factoryClassName, classLoader, false));131}132133/**134* Creates a new instance of the {@code SAXParserFactory} builtin135* system-default implementation.136*137* @return A new instance of the {@code SAXParserFactory} builtin138* system-default implementation.139*140* @since 9141*/142public static SAXParserFactory newDefaultInstance() {143return new SAXParserFactoryImpl();144}145146/**147* Obtains a new instance of a {@code SAXParserFactory}.148* This method uses the149* <a href="../../../module-summary.html#LookupMechanism">JAXP Lookup Mechanism</a>150* to determine the {@code SAXParserFactory} implementation class to load.151*152* <p>153* Once an application has obtained a reference to a154* {@code SAXParserFactory}, it can use the factory to155* configure and obtain parser instances.156*157*158*159* <h4>Tip for Trouble-shooting</h4>160* <p>161* Setting the {@code jaxp.debug} system property will cause162* this method to print a lot of debug messages163* to {@code System.err} about what it is doing and where it is looking at.164*165* <p>166* If you have problems loading {@link SAXParser}s, try:167* <pre>168* java -Djaxp.debug=1 YourProgram ....169* </pre>170*171*172* @return A new instance of a SAXParserFactory.173*174* @throws FactoryConfigurationError in case of {@linkplain175* java.util.ServiceConfigurationError service configuration error} or if176* the implementation is not available or cannot be instantiated.177*/178179public static SAXParserFactory newInstance() {180return FactoryFinder.find(181/* The default property name according to the JAXP spec */182SAXParserFactory.class,183/* The fallback implementation class name */184DEFAULT_IMPL);185}186187/**188* Obtain a new instance of a {@code SAXParserFactory} from class name.189* This function is useful when there are multiple providers in the classpath.190* It gives more control to the application as it can specify which provider191* should be loaded.192*193* <p>Once an application has obtained a reference to a {@code SAXParserFactory}194* it can use the factory to configure and obtain parser instances.195*196*197* <h4>Tip for Trouble-shooting</h4>198* <p>Setting the {@code jaxp.debug} system property will cause199* this method to print a lot of debug messages200* to {@code System.err} about what it is doing and where it is looking at.201*202* <p>203* If you have problems, try:204* <pre>205* java -Djaxp.debug=1 YourProgram ....206* </pre>207*208* @param factoryClassName fully qualified factory class name that provides implementation of {@code javax.xml.parsers.SAXParserFactory}.209*210* @param classLoader {@code ClassLoader} used to load the factory class. If {@code null}211* current {@code Thread}'s context classLoader is used to load the factory class.212*213* @return New instance of a {@code SAXParserFactory}214*215* @throws FactoryConfigurationError if {@code factoryClassName} is {@code null}, or216* the factory class cannot be loaded, instantiated.217*218* @see #newInstance()219*220* @since 1.6221*/222public static SAXParserFactory newInstance(String factoryClassName, ClassLoader classLoader){223//do not fallback if given classloader can't find the class, throw exception224return FactoryFinder.newInstance(SAXParserFactory.class,225factoryClassName, classLoader, false);226}227228private static SAXParserFactory makeNSAware(SAXParserFactory spf) {229spf.setNamespaceAware(true);230return spf;231}232233/**234* Creates a new instance of a SAXParser using the currently235* configured factory parameters.236*237* @return A new instance of a SAXParser.238*239* @throws ParserConfigurationException if a parser cannot240* be created which satisfies the requested configuration.241* @throws SAXException for SAX errors.242*/243244public abstract SAXParser newSAXParser()245throws ParserConfigurationException, SAXException;246247248/**249* Specifies that the parser produced by this code will250* provide support for XML namespaces. By default the value of this is set251* to {@code false}.252*253* @param awareness true if the parser produced by this code will254* provide support for XML namespaces; false otherwise.255*/256257public void setNamespaceAware(boolean awareness) {258this.namespaceAware = awareness;259}260261/**262* Specifies that the parser produced by this code will263* validate documents as they are parsed. By default the value of this is264* set to {@code false}.265*266* <p>267* Note that "the validation" here means268* <a href="http://www.w3.org/TR/REC-xml#proc-types">a validating269* parser</a> as defined in the XML recommendation.270* In other words, it essentially just controls the DTD validation.271* (except the legacy two properties defined in JAXP 1.2.)272*273* <p>274* To use modern schema languages such as W3C XML Schema or275* RELAX NG instead of DTD, you can configure your parser to be276* a non-validating parser by leaving the {@link #setValidating(boolean)}277* method {@code false}, then use the {@link #setSchema(Schema)}278* method to associate a schema to a parser.279*280* @param validating true if the parser produced by this code will281* validate documents as they are parsed; false otherwise.282*/283284public void setValidating(boolean validating) {285this.validating = validating;286}287288/**289* Indicates whether or not the factory is configured to produce290* parsers which are namespace aware.291*292* @return true if the factory is configured to produce293* parsers which are namespace aware; false otherwise.294*/295296public boolean isNamespaceAware() {297return namespaceAware;298}299300/**301* Indicates whether or not the factory is configured to produce302* parsers which validate the XML content during parse.303*304* @return true if the factory is configured to produce parsers which validate305* the XML content during parse; false otherwise.306*/307308public boolean isValidating() {309return validating;310}311312/**313* Sets the particular feature in the underlying implementation of314* org.xml.sax.XMLReader.315* A list of the core features and properties can be found at316* <a href="http://www.saxproject.org/">http://www.saxproject.org/</a>317*318* <p>All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature.319* When the feature is320* <ul>321* <li>322* {@code true}: the implementation will limit XML processing to conform to implementation limits.323* Examples include entity expansion limits and XML Schema constructs that would consume large amounts of resources.324* If XML processing is limited for security reasons, it will be reported via a call to the registered325* {@link org.xml.sax.ErrorHandler#fatalError(SAXParseException exception)}.326* See {@link SAXParser} {@code parse} methods for handler specification.327* </li>328* <li>329* When the feature is {@code false}, the implementation will processing XML according to the XML specifications without330* regard to possible implementation limits.331* </li>332* </ul>333*334* @param name The name of the feature to be set.335* @param value The value of the feature to be set.336*337* @throws ParserConfigurationException if a parser cannot338* be created which satisfies the requested configuration.339* @throws SAXNotRecognizedException When the underlying XMLReader does340* not recognize the property name.341* @throws SAXNotSupportedException When the underlying XMLReader342* recognizes the property name but doesn't support the343* property.344* @throws NullPointerException If the {@code name} parameter is null.345*346* @see org.xml.sax.XMLReader#setFeature347*/348public abstract void setFeature(String name, boolean value)349throws ParserConfigurationException, SAXNotRecognizedException,350SAXNotSupportedException;351352/**353*354* Returns the particular property requested for in the underlying355* implementation of org.xml.sax.XMLReader.356*357* @param name The name of the property to be retrieved.358*359* @return Value of the requested property.360*361* @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.362* @throws SAXNotRecognizedException When the underlying XMLReader does not recognize the property name.363* @throws SAXNotSupportedException When the underlying XMLReader recognizes the property name but doesn't support the property.364*365* @see org.xml.sax.XMLReader#getProperty366*/367public abstract boolean getFeature(String name)368throws ParserConfigurationException, SAXNotRecognizedException,369SAXNotSupportedException;370371372/**373* Gets the {@link Schema} object specified through374* the {@link #setSchema(Schema schema)} method.375*376*377* @throws UnsupportedOperationException When implementation does not378* override this method379*380* @return381* the {@link Schema} object that was last set through382* the {@link #setSchema(Schema)} method, or null383* if the method was not invoked since a {@link SAXParserFactory}384* is created.385*386* @since 1.5387*/388public Schema getSchema() {389throw new UnsupportedOperationException(390"This parser does not support specification \""391+ this.getClass().getPackage().getSpecificationTitle()392+ "\" version \""393+ this.getClass().getPackage().getSpecificationVersion()394+ "\""395);396}397398/**399* Set the {@link Schema} to be used by parsers created400* from this factory.401*402* <p>When a {@link Schema} is non-null, a parser will use a validator403* created from it to validate documents before it passes information404* down to the application.405*406* <p>When warnings/errors/fatal errors are found by the validator, the parser must407* handle them as if those errors were found by the parser itself.408* In other words, if the user-specified {@link org.xml.sax.ErrorHandler}409* is set, it must receive those errors, and if not, they must be410* treated according to the implementation specific411* default error handling rules.412*413* <p>A validator may modify the SAX event stream (for example by414* adding default values that were missing in documents), and a parser415* is responsible to make sure that the application will receive416* those modified event stream.417*418* <p>Initially, {@code null} is set as the {@link Schema}.419*420* <p>This processing will take effect even if421* the {@link #isValidating()} method returns {@code false}.422*423* <p>It is an error to use424* the {@code http://java.sun.com/xml/jaxp/properties/schemaSource}425* property and/or the {@code http://java.sun.com/xml/jaxp/properties/schemaLanguage}426* property in conjunction with a non-null {@link Schema} object.427* Such configuration will cause a {@link SAXException}428* exception when those properties are set on a {@link SAXParser}.429*430* <h4>Note for implementors</h4>431* <p>432* A parser must be able to work with any {@link Schema}433* implementation. However, parsers and schemas are allowed434* to use implementation-specific custom mechanisms435* as long as they yield the result described in the specification.436*437* @param schema {@code Schema} to use, {@code null} to remove a schema.438*439* @throws UnsupportedOperationException When implementation does not440* override this method441*442* @since 1.5443*/444public void setSchema(Schema schema) {445throw new UnsupportedOperationException(446"This parser does not support specification \""447+ this.getClass().getPackage().getSpecificationTitle()448+ "\" version \""449+ this.getClass().getPackage().getSpecificationVersion()450+ "\""451);452}453454/**455* Set state of XInclude processing.456*457* <p>If XInclude markup is found in the document instance, should it be458* processed as specified in <a href="http://www.w3.org/TR/xinclude/">459* XML Inclusions (XInclude) Version 1.0</a>.460*461* <p>XInclude processing defaults to {@code false}.462*463* @param state Set XInclude processing to {@code true} or464* {@code false}465*466* @throws UnsupportedOperationException When implementation does not467* override this method468*469* @since 1.5470*/471public void setXIncludeAware(final boolean state) {472if (state) {473throw new UnsupportedOperationException(" setXIncludeAware " +474"is not supported on this JAXP" +475" implementation or earlier: " + this.getClass());476}477}478479/**480* Get state of XInclude processing.481*482* @return current state of XInclude processing483*484* @throws UnsupportedOperationException When implementation does not485* override this method486*487* @since 1.5488*/489public boolean isXIncludeAware() {490throw new UnsupportedOperationException(491"This parser does not support specification \""492+ this.getClass().getPackage().getSpecificationTitle()493+ "\" version \""494+ this.getClass().getPackage().getSpecificationVersion()495+ "\""496);497}498}499500501