Path: blob/master/src/java.xml/share/classes/javax/xml/parsers/DocumentBuilderFactory.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.DocumentBuilderFactoryImpl;28import javax.xml.validation.Schema;2930/**31* Defines a factory API that enables applications to obtain a32* parser that produces DOM object trees from XML documents.33*34* @author Jeff Suttor35* @author Neeraj Bajaj36*37* @since 1.438*/3940public abstract class DocumentBuilderFactory {41private static final String DEFAULT_IMPL =42"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";43private boolean validating = false;44private boolean namespaceAware = false;45private boolean whitespace = false;46private boolean expandEntityRef = true;47private boolean ignoreComments = false;48private boolean coalescing = false;4950/**51* Protected constructor to prevent instantiation.52* Use {@link #newInstance()}.53*/54protected DocumentBuilderFactory () {55}5657/**58* Creates a new NamespaceAware instance of the {@code DocumentBuilderFactory}59* builtin system-default implementation. Parsers produced by the factory60* instance provides support for XML namespaces by default.61*62* @implSpec63* In addition to creating a factory instance using the same process as64* {@link #newDefaultInstance()}, this method must set NamespaceAware to true.65*66* @return a new instance of the {@code DocumentBuilderFactory} builtin67* system-default implementation.68*69* @since 1370*/71public static DocumentBuilderFactory newDefaultNSInstance() {72return makeNSAware(new DocumentBuilderFactoryImpl());73}7475/**76* Creates a new NamespaceAware instance of a {@code DocumentBuilderFactory}.77* Parsers produced by the factory instance provides support for XML namespaces78* by default.79*80* @implSpec81* In addition to creating a factory instance using the same process as82* {@link #newInstance()}, this method must set NamespaceAware to true.83*84* @return a new instance of a {@code DocumentBuilderFactory}85*86* @throws FactoryConfigurationError in case of {@linkplain87* java.util.ServiceConfigurationError service configuration error}88* or if the implementation is not available or cannot be instantiated.89*90* @since 1391*/92public static DocumentBuilderFactory newNSInstance() {93return makeNSAware(FactoryFinder.find(DocumentBuilderFactory.class, DEFAULT_IMPL));94}9596/**97* Creates a new NamespaceAware instance of a {@code DocumentBuilderFactory}98* from the class name. Parsers produced by the factory instance provides99* support for XML namespaces by default.100*101* @implSpec102* In addition to creating a factory instance using the same process as103* {@link #newInstance(java.lang.String, java.lang.ClassLoader)}, this method104* must set NamespaceAware to true.105*106* @param factoryClassName a fully qualified factory class name that provides107* implementation of108* {@code javax.xml.parsers.DocumentBuilderFactory}.109*110* @param classLoader the {@code ClassLoader} used to load the factory class.111* If it is {@code null}, the current {@code Thread}'s112* context classLoader is used to load the factory class.113*114* @return a new instance of a {@code DocumentBuilderFactory}115*116* @throws FactoryConfigurationError if {@code factoryClassName} is {@code null}, or117* the factory class cannot be loaded, instantiated.118*119* @since 13120*/121public static DocumentBuilderFactory newNSInstance(String factoryClassName,122ClassLoader classLoader) {123return makeNSAware(FactoryFinder.newInstance(124DocumentBuilderFactory.class, factoryClassName, classLoader, false));125}126127/**128* Creates a new instance of the {@code DocumentBuilderFactory} builtin129* system-default implementation.130*131* @return A new instance of the {@code DocumentBuilderFactory} builtin132* system-default implementation.133*134* @since 9135*/136public static DocumentBuilderFactory newDefaultInstance() {137return new DocumentBuilderFactoryImpl();138}139140/**141* Obtains a new instance of a {@code DocumentBuilderFactory}.142* This method uses the143* <a href="../../../module-summary.html#LookupMechanism">JAXP Lookup Mechanism</a>144* to determine the {@code DocumentBuilderFactory} implementation class to load.145*146* <p>147* Once an application has obtained a reference to a148* {@code DocumentBuilderFactory}, it can use the factory to149* configure and obtain parser instances.150*151*152* <h4>Tip for Trouble-shooting</h4>153* <p>154* Setting the {@code jaxp.debug} system property will cause155* this method to print a lot of debug messages156* to {@code System.err} about what it is doing and where it is looking at.157*158* <p>159* If you have problems loading {@link DocumentBuilder}s, try:160* <pre>161* java -Djaxp.debug=1 YourProgram ....162* </pre>163*164* @return New instance of a {@code DocumentBuilderFactory}165*166* @throws FactoryConfigurationError in case of {@linkplain167* java.util.ServiceConfigurationError service configuration error} or if168* the implementation is not available or cannot be instantiated.169*/170public static DocumentBuilderFactory newInstance() {171return FactoryFinder.find(172/* The default property name according to the JAXP spec */173DocumentBuilderFactory.class, // "javax.xml.parsers.DocumentBuilderFactory"174/* The fallback implementation class name */175DEFAULT_IMPL);176}177178/**179* Obtain a new instance of a {@code DocumentBuilderFactory} from class name.180* This function is useful when there are multiple providers in the classpath.181* It gives more control to the application as it can specify which provider182* should be loaded.183*184* <p>Once an application has obtained a reference to a {@code DocumentBuilderFactory}185* it can use the factory to configure and obtain parser instances.186*187*188* <h4>Tip for Trouble-shooting</h4>189* <p>Setting the {@code jaxp.debug} system property will cause190* this method to print a lot of debug messages191* to {@code System.err} about what it is doing and where it is looking at.192*193* <p> If you have problems try:194* <pre>195* java -Djaxp.debug=1 YourProgram ....196* </pre>197*198* @param factoryClassName fully qualified factory class name that provides199* implementation of {@code javax.xml.parsers.DocumentBuilderFactory}.200*201* @param classLoader {@code ClassLoader} used to load the factory class. If {@code null}202* current {@code Thread}'s context classLoader is used to load the factory class.203*204* @return New instance of a {@code DocumentBuilderFactory}205*206* @throws FactoryConfigurationError if {@code factoryClassName} is {@code null}, or207* the factory class cannot be loaded, instantiated.208*209* @see #newInstance()210*211* @since 1.6212*/213public static DocumentBuilderFactory newInstance(String factoryClassName, ClassLoader classLoader){214//do not fallback if given classloader can't find the class, throw exception215return FactoryFinder.newInstance(DocumentBuilderFactory.class,216factoryClassName, classLoader, false);217}218219private static DocumentBuilderFactory makeNSAware(DocumentBuilderFactory dbf) {220dbf.setNamespaceAware(true);221return dbf;222}223224/**225* Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}226* using the currently configured parameters.227*228* @return A new instance of a DocumentBuilder.229*230* @throws ParserConfigurationException if a DocumentBuilder231* cannot be created which satisfies the configuration requested.232*/233234public abstract DocumentBuilder newDocumentBuilder()235throws ParserConfigurationException;236237238/**239* Specifies that the parser produced by this code will240* provide support for XML namespaces. By default the value of this is set241* to {@code false}242*243* @param awareness true if the parser produced will provide support244* for XML namespaces; false otherwise.245*/246247public void setNamespaceAware(boolean awareness) {248this.namespaceAware = awareness;249}250251/**252* Specifies that the parser produced by this code will253* validate documents as they are parsed. By default the value of this254* is set to {@code false}.255*256* <p>257* Note that "the validation" here means258* <a href="http://www.w3.org/TR/REC-xml#proc-types">a validating259* parser</a> as defined in the XML recommendation.260* In other words, it essentially just controls the DTD validation.261* (except the legacy two properties defined in JAXP 1.2.)262*263* <p>264* To use modern schema languages such as W3C XML Schema or265* RELAX NG instead of DTD, you can configure your parser to be266* a non-validating parser by leaving the {@link #setValidating(boolean)}267* method {@code false}, then use the {@link #setSchema(Schema)}268* method to associate a schema to a parser.269*270* @param validating true if the parser produced will validate documents271* as they are parsed; false otherwise.272*/273274public void setValidating(boolean validating) {275this.validating = validating;276}277278/**279* Specifies that the parsers created by this factory must eliminate280* whitespace in element content (sometimes known loosely as281* 'ignorable whitespace') when parsing XML documents (see XML Rec282* 2.10). Note that only whitespace which is directly contained within283* element content that has an element only content model (see XML284* Rec 3.2.1) will be eliminated. Due to reliance on the content model285* this setting requires the parser to be in validating mode. By default286* the value of this is set to {@code false}.287*288* @param whitespace true if the parser created must eliminate whitespace289* in the element content when parsing XML documents;290* false otherwise.291*/292293public void setIgnoringElementContentWhitespace(boolean whitespace) {294this.whitespace = whitespace;295}296297/**298* Specifies that the parser produced by this code will299* expand entity reference nodes. By default the value of this is set to300* {@code true}301*302* @param expandEntityRef true if the parser produced will expand entity303* reference nodes; false otherwise.304*/305306public void setExpandEntityReferences(boolean expandEntityRef) {307this.expandEntityRef = expandEntityRef;308}309310/**311* Specifies that the parser produced by this code will312* ignore comments. By default the value of this is set to {@code false}.313*314* @param ignoreComments {@code boolean} value to ignore comments during processing315*/316317public void setIgnoringComments(boolean ignoreComments) {318this.ignoreComments = ignoreComments;319}320321/**322* Specifies that the parser produced by this code will323* convert CDATA nodes to Text nodes and append it to the324* adjacent (if any) text node. By default the value of this is set to325* {@code false}326*327* @param coalescing true if the parser produced will convert CDATA nodes328* to Text nodes and append it to the adjacent (if any)329* text node; false otherwise.330*/331332public void setCoalescing(boolean coalescing) {333this.coalescing = coalescing;334}335336/**337* Indicates whether or not the factory is configured to produce338* parsers which are namespace aware.339*340* @return true if the factory is configured to produce parsers which341* are namespace aware; false otherwise.342*/343344public boolean isNamespaceAware() {345return namespaceAware;346}347348/**349* Indicates whether or not the factory is configured to produce350* parsers which validate the XML content during parse.351*352* @return true if the factory is configured to produce parsers353* which validate the XML content during parse; false otherwise.354*/355356public boolean isValidating() {357return validating;358}359360/**361* Indicates whether or not the factory is configured to produce362* parsers which ignore ignorable whitespace in element content.363*364* @return true if the factory is configured to produce parsers365* which ignore ignorable whitespace in element content;366* false otherwise.367*/368369public boolean isIgnoringElementContentWhitespace() {370return whitespace;371}372373/**374* Indicates whether or not the factory is configured to produce375* parsers which expand entity reference nodes.376*377* @return true if the factory is configured to produce parsers378* which expand entity reference nodes; false otherwise.379*/380381public boolean isExpandEntityReferences() {382return expandEntityRef;383}384385/**386* Indicates whether or not the factory is configured to produce387* parsers which ignores comments.388*389* @return true if the factory is configured to produce parsers390* which ignores comments; false otherwise.391*/392393public boolean isIgnoringComments() {394return ignoreComments;395}396397/**398* Indicates whether or not the factory is configured to produce399* parsers which converts CDATA nodes to Text nodes and appends it to400* the adjacent (if any) Text node.401*402* @return true if the factory is configured to produce parsers403* which converts CDATA nodes to Text nodes and appends it to404* the adjacent (if any) Text node; false otherwise.405*/406407public boolean isCoalescing() {408return coalescing;409}410411/**412* Allows the user to set specific attributes on the underlying413* implementation.414* <p>415* All implementations that implement JAXP 1.5 or newer are required to416* support the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} and417* {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_SCHEMA} properties.418*419* <ul>420* <li>421* Setting the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} property422* restricts the access to external DTDs, external Entity References to the423* protocols specified by the property.424* If access is denied during parsing due to the restriction of this property,425* {@link org.xml.sax.SAXException} will be thrown by the parse methods defined by426* {@link javax.xml.parsers.DocumentBuilder}.427* </li>428* <li>429* Setting the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_SCHEMA} property430* restricts the access to external Schema set by the schemaLocation attribute to431* the protocols specified by the property. If access is denied during parsing432* due to the restriction of this property, {@link org.xml.sax.SAXException}433* will be thrown by the parse methods defined by434* {@link javax.xml.parsers.DocumentBuilder}.435* </li>436* </ul>437*438* @param name The name of the attribute.439* @param value The value of the attribute.440*441* @throws IllegalArgumentException thrown if the underlying442* implementation doesn't recognize the attribute.443*/444public abstract void setAttribute(String name, Object value)445throws IllegalArgumentException;446447/**448* Allows the user to retrieve specific attributes on the underlying449* implementation.450*451* @param name The name of the attribute.452*453* @return value The value of the attribute.454*455* @throws IllegalArgumentException thrown if the underlying456* implementation doesn't recognize the attribute.457*/458public abstract Object getAttribute(String name)459throws IllegalArgumentException;460461/**462* Set a feature for this {@code DocumentBuilderFactory}463* and {@code DocumentBuilder}s created by this factory.464*465* <p>466* Feature names are fully qualified {@link java.net.URI}s.467* Implementations may define their own features.468* A {@link ParserConfigurationException} is thrown if this {@code DocumentBuilderFactory} or the469* {@code DocumentBuilder}s it creates cannot support the feature.470* It is possible for a {@code DocumentBuilderFactory} to expose a feature value but be unable to change its state.471*472*473* <p>474* All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature.475* When the feature is:476* <ul>477* <li>478* {@code true}: the implementation will limit XML processing to conform to implementation limits.479* Examples include entity expansion limits and XML Schema constructs that would consume large amounts of resources.480* If XML processing is limited for security reasons, it will be reported via a call to the registered481* {@link org.xml.sax.ErrorHandler#fatalError(SAXParseException exception)}.482* See {@link DocumentBuilder#setErrorHandler(org.xml.sax.ErrorHandler errorHandler)}.483* </li>484* <li>485* {@code false}: the implementation will processing XML according to the XML specifications without486* regard to possible implementation limits.487* </li>488* </ul>489*490* @param name Feature name.491* @param value Is feature state {@code true} or {@code false}.492*493* @throws ParserConfigurationException if this {@code DocumentBuilderFactory} or the {@code DocumentBuilder}s494* it creates cannot support this feature.495* @throws NullPointerException If the {@code name} parameter is null.496* @since 1.5497*/498public abstract void setFeature(String name, boolean value)499throws ParserConfigurationException;500501/**502* Get the state of the named feature.503*504* <p>505* Feature names are fully qualified {@link java.net.URI}s.506* Implementations may define their own features.507* An {@link ParserConfigurationException} is thrown if this {@code DocumentBuilderFactory} or the508* {@code DocumentBuilder}s it creates cannot support the feature.509* It is possible for an {@code DocumentBuilderFactory} to expose a feature value but be unable to change its state.510*511* @param name Feature name.512*513* @return State of the named feature.514*515* @throws ParserConfigurationException if this {@code DocumentBuilderFactory}516* or the {@code DocumentBuilder}s it creates cannot support this feature.517* @since 1.5518*/519public abstract boolean getFeature(String name)520throws ParserConfigurationException;521522523/**524* Gets the {@link Schema} object specified through525* the {@link #setSchema(Schema schema)} method.526*527* @return528* the {@link Schema} object that was last set through529* the {@link #setSchema(Schema)} method, or null530* if the method was not invoked since a {@link DocumentBuilderFactory}531* is created.532*533* @throws UnsupportedOperationException When implementation does not534* override this method.535*536* @since 1.5537*/538public Schema getSchema() {539throw new UnsupportedOperationException(540"This parser does not support specification \""541+ this.getClass().getPackage().getSpecificationTitle()542+ "\" version \""543+ this.getClass().getPackage().getSpecificationVersion()544+ "\""545);546547}548549/**550* Set the {@link Schema} to be used by parsers created551* from this factory.552*553* <p>554* When a {@link Schema} is non-null, a parser will use a validator555* created from it to validate documents before it passes information556* down to the application.557*558* <p>When errors are found by the validator, the parser is responsible559* to report them to the user-specified {@link org.xml.sax.ErrorHandler}560* (or if the error handler is not set, ignore them or throw them), just561* like any other errors found by the parser itself.562* In other words, if the user-specified {@link org.xml.sax.ErrorHandler}563* is set, it must receive those errors, and if not, they must be564* treated according to the implementation specific565* default error handling rules.566*567* <p>568* A validator may modify the outcome of a parse (for example by569* adding default values that were missing in documents), and a parser570* is responsible to make sure that the application will receive571* modified DOM trees.572*573* <p>574* Initially, null is set as the {@link Schema}.575*576* <p>577* This processing will take effect even if578* the {@link #isValidating()} method returns {@code false}.579*580* <p>It is an error to use581* the {@code http://java.sun.com/xml/jaxp/properties/schemaSource}582* property and/or the {@code http://java.sun.com/xml/jaxp/properties/schemaLanguage}583* property in conjunction with a {@link Schema} object.584* Such configuration will cause a {@link ParserConfigurationException}585* exception when the {@link #newDocumentBuilder()} is invoked.586*587*588* <h4>Note for implementors</h4>589*590* <p>591* A parser must be able to work with any {@link Schema}592* implementation. However, parsers and schemas are allowed593* to use implementation-specific custom mechanisms594* as long as they yield the result described in the specification.595*596*597* @param schema {@code Schema} to use or {@code null}598* to remove a schema.599*600* @throws UnsupportedOperationException When implementation does not601* override this method.602*603* @since 1.5604*/605public void setSchema(Schema schema) {606throw new UnsupportedOperationException(607"This parser does not support specification \""608+ this.getClass().getPackage().getSpecificationTitle()609+ "\" version \""610+ this.getClass().getPackage().getSpecificationVersion()611+ "\""612);613}614615616617/**618* Set state of XInclude processing.619*620* <p>If XInclude markup is found in the document instance, should it be621* processed as specified in <a href="http://www.w3.org/TR/xinclude/">622* XML Inclusions (XInclude) Version 1.0</a>.623*624* <p>XInclude processing defaults to {@code false}.625*626* @param state Set XInclude processing to {@code true} or627* {@code false}628*629* @throws UnsupportedOperationException When implementation does not630* override this method.631*632* @since 1.5633*/634public void setXIncludeAware(final boolean state) {635if (state) {636throw new UnsupportedOperationException(" setXIncludeAware " +637"is not supported on this JAXP" +638" implementation or earlier: " + this.getClass());639}640}641642/**643* Get state of XInclude processing.644*645* @return current state of XInclude processing646*647* @throws UnsupportedOperationException When implementation does not648* override this method.649*650* @since 1.5651*/652public boolean isXIncludeAware() {653throw new UnsupportedOperationException(654"This parser does not support specification \""655+ this.getClass().getPackage().getSpecificationTitle()656+ "\" version \""657+ this.getClass().getPackage().getSpecificationVersion()658+ "\""659);660}661}662663664