Path: blob/aarch64-shenandoah-jdk8u272-b10/jaxp/src/org/xml/sax/helpers/NamespaceSupport.java
48576 views
/*1* Copyright (c) 2000, 2015, 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*/2425// NamespaceSupport.java - generic Namespace support for SAX.26// http://www.saxproject.org27// Written by David Megginson28// This class is in the Public Domain. NO WARRANTY!29// $Id: NamespaceSupport.java,v 1.5 2004/11/03 22:53:09 jsuttor Exp $3031package org.xml.sax.helpers;3233import java.util.ArrayList;34import java.util.Collections;35import java.util.EmptyStackException;36import java.util.Enumeration;37import java.util.HashMap;38import java.util.List;39import java.util.Map;404142/**43* Encapsulate Namespace logic for use by applications using SAX,44* or internally by SAX drivers.45*46* <blockquote>47* <em>This module, both source code and documentation, is in the48* Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>49* See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>50* for further information.51* </blockquote>52*53* <p>This class encapsulates the logic of Namespace processing: it54* tracks the declarations currently in force for each context and55* automatically processes qualified XML names into their Namespace56* parts; it can also be used in reverse for generating XML qnames57* from Namespaces.</p>58*59* <p>Namespace support objects are reusable, but the reset method60* must be invoked between each session.</p>61*62* <p>Here is a simple session:</p>63*64* <pre>65* String parts[] = new String[3];66* NamespaceSupport support = new NamespaceSupport();67*68* support.pushContext();69* support.declarePrefix("", "http://www.w3.org/1999/xhtml");70* support.declarePrefix("dc", "http://www.purl.org/dc#");71*72* parts = support.processName("p", parts, false);73* System.out.println("Namespace URI: " + parts[0]);74* System.out.println("Local name: " + parts[1]);75* System.out.println("Raw name: " + parts[2]);76*77* parts = support.processName("dc:title", parts, false);78* System.out.println("Namespace URI: " + parts[0]);79* System.out.println("Local name: " + parts[1]);80* System.out.println("Raw name: " + parts[2]);81*82* support.popContext();83* </pre>84*85* <p>Note that this class is optimized for the use case where most86* elements do not contain Namespace declarations: if the same87* prefix/URI mapping is repeated for each context (for example), this88* class will be somewhat less efficient.</p>89*90* <p>Although SAX drivers (parsers) may choose to use this class to91* implement namespace handling, they are not required to do so.92* Applications must track namespace information themselves if they93* want to use namespace information.94*95* @since SAX 2.096* @author David Megginson97*/98public class NamespaceSupport99{100101102////////////////////////////////////////////////////////////////////103// Constants.104////////////////////////////////////////////////////////////////////105106107/**108* The XML Namespace URI as a constant.109* The value is <code>http://www.w3.org/XML/1998/namespace</code>110* as defined in the "Namespaces in XML" * recommendation.111*112* <p>This is the Namespace URI that is automatically mapped113* to the "xml" prefix.</p>114*/115public final static String XMLNS =116"http://www.w3.org/XML/1998/namespace";117118119/**120* The namespace declaration URI as a constant.121* The value is <code>http://www.w3.org/xmlns/2000/</code>, as defined122* in a backwards-incompatible erratum to the "Namespaces in XML"123* recommendation. Because that erratum postdated SAX2, SAX2 defaults124* to the original recommendation, and does not normally use this URI.125*126*127* <p>This is the Namespace URI that is optionally applied to128* <em>xmlns</em> and <em>xmlns:*</em> attributes, which are used to129* declare namespaces. </p>130*131* @since SAX 2.1alpha132* @see #setNamespaceDeclUris133* @see #isNamespaceDeclUris134*/135public final static String NSDECL =136"http://www.w3.org/xmlns/2000/";137138139/**140* An empty enumeration.141*/142private final static Enumeration EMPTY_ENUMERATION =143Collections.enumeration(new ArrayList<String>());144145146////////////////////////////////////////////////////////////////////147// Constructor.148////////////////////////////////////////////////////////////////////149150151/**152* Create a new Namespace support object.153*/154public NamespaceSupport ()155{156reset();157}158159160161////////////////////////////////////////////////////////////////////162// Context management.163////////////////////////////////////////////////////////////////////164165166/**167* Reset this Namespace support object for reuse.168*169* <p>It is necessary to invoke this method before reusing the170* Namespace support object for a new session. If namespace171* declaration URIs are to be supported, that flag must also172* be set to a non-default value.173* </p>174*175* @see #setNamespaceDeclUris176*/177public void reset ()178{179contexts = new Context[32];180namespaceDeclUris = false;181contextPos = 0;182contexts[contextPos] = currentContext = new Context();183currentContext.declarePrefix("xml", XMLNS);184}185186187/**188* Start a new Namespace context.189* The new context will automatically inherit190* the declarations of its parent context, but it will also keep191* track of which declarations were made within this context.192*193* <p>Event callback code should start a new context once per element.194* This means being ready to call this in either of two places.195* For elements that don't include namespace declarations, the196* <em>ContentHandler.startElement()</em> callback is the right place.197* For elements with such a declaration, it'd done in the first198* <em>ContentHandler.startPrefixMapping()</em> callback.199* A boolean flag can be used to200* track whether a context has been started yet. When either of201* those methods is called, it checks the flag to see if a new context202* needs to be started. If so, it starts the context and sets the203* flag. After <em>ContentHandler.startElement()</em>204* does that, it always clears the flag.205*206* <p>Normally, SAX drivers would push a new context at the beginning207* of each XML element. Then they perform a first pass over the208* attributes to process all namespace declarations, making209* <em>ContentHandler.startPrefixMapping()</em> callbacks.210* Then a second pass is made, to determine the namespace-qualified211* names for all attributes and for the element name.212* Finally all the information for the213* <em>ContentHandler.startElement()</em> callback is available,214* so it can then be made.215*216* <p>The Namespace support object always starts with a base context217* already in force: in this context, only the "xml" prefix is218* declared.</p>219*220* @see org.xml.sax.ContentHandler221* @see #popContext222*/223public void pushContext ()224{225int max = contexts.length;226227contextPos++;228229// Extend the array if necessary230if (contextPos >= max) {231Context newContexts[] = new Context[max*2];232System.arraycopy(contexts, 0, newContexts, 0, max);233max *= 2;234contexts = newContexts;235}236237// Allocate the context if necessary.238currentContext = contexts[contextPos];239if (currentContext == null) {240contexts[contextPos] = currentContext = new Context();241}242243// Set the parent, if any.244if (contextPos > 0) {245currentContext.setParent(contexts[contextPos - 1]);246}247}248249250/**251* Revert to the previous Namespace context.252*253* <p>Normally, you should pop the context at the end of each254* XML element. After popping the context, all Namespace prefix255* mappings that were previously in force are restored.</p>256*257* <p>You must not attempt to declare additional Namespace258* prefixes after popping a context, unless you push another259* context first.</p>260*261* @see #pushContext262*/263public void popContext ()264{265contexts[contextPos].clear();266contextPos--;267if (contextPos < 0) {268throw new EmptyStackException();269}270currentContext = contexts[contextPos];271}272273274275////////////////////////////////////////////////////////////////////276// Operations within a context.277////////////////////////////////////////////////////////////////////278279280/**281* Declare a Namespace prefix. All prefixes must be declared282* before they are referenced. For example, a SAX driver (parser)283* would scan an element's attributes284* in two passes: first for namespace declarations,285* then a second pass using {@link #processName processName()} to286* interpret prefixes against (potentially redefined) prefixes.287*288* <p>This method declares a prefix in the current Namespace289* context; the prefix will remain in force until this context290* is popped, unless it is shadowed in a descendant context.</p>291*292* <p>To declare the default element Namespace, use the empty string as293* the prefix.</p>294*295* <p>Note that there is an asymmetry in this library: {@link296* #getPrefix getPrefix} will not return the "" prefix,297* even if you have declared a default element namespace.298* To check for a default namespace,299* you have to look it up explicitly using {@link #getURI getURI}.300* This asymmetry exists to make it easier to look up prefixes301* for attribute names, where the default prefix is not allowed.</p>302*303* @param prefix The prefix to declare, or the empty string to304* indicate the default element namespace. This may never have305* the value "xml" or "xmlns".306* @param uri The Namespace URI to associate with the prefix.307* @return true if the prefix was legal, false otherwise308*309* @see #processName310* @see #getURI311* @see #getPrefix312*/313public boolean declarePrefix (String prefix, String uri)314{315if (prefix.equals("xml") || prefix.equals("xmlns")) {316return false;317} else {318currentContext.declarePrefix(prefix, uri);319return true;320}321}322323324/**325* Process a raw XML qualified name, after all declarations in the326* current context have been handled by {@link #declarePrefix327* declarePrefix()}.328*329* <p>This method processes a raw XML qualified name in the330* current context by removing the prefix and looking it up among331* the prefixes currently declared. The return value will be the332* array supplied by the caller, filled in as follows:</p>333*334* <dl>335* <dt>parts[0]</dt>336* <dd>The Namespace URI, or an empty string if none is337* in use.</dd>338* <dt>parts[1]</dt>339* <dd>The local name (without prefix).</dd>340* <dt>parts[2]</dt>341* <dd>The original raw name.</dd>342* </dl>343*344* <p>All of the strings in the array will be internalized. If345* the raw name has a prefix that has not been declared, then346* the return value will be null.</p>347*348* <p>Note that attribute names are processed differently than349* element names: an unprefixed element name will receive the350* default Namespace (if any), while an unprefixed attribute name351* will not.</p>352*353* @param qName The XML qualified name to be processed.354* @param parts An array supplied by the caller, capable of355* holding at least three members.356* @param isAttribute A flag indicating whether this is an357* attribute name (true) or an element name (false).358* @return The supplied array holding three internalized strings359* representing the Namespace URI (or empty string), the360* local name, and the XML qualified name; or null if there361* is an undeclared prefix.362* @see #declarePrefix363* @see java.lang.String#intern */364public String [] processName (String qName, String parts[],365boolean isAttribute)366{367String myParts[] = currentContext.processName(qName, isAttribute);368if (myParts == null) {369return null;370} else {371parts[0] = myParts[0];372parts[1] = myParts[1];373parts[2] = myParts[2];374return parts;375}376}377378379/**380* Look up a prefix and get the currently-mapped Namespace URI.381*382* <p>This method looks up the prefix in the current context.383* Use the empty string ("") for the default Namespace.</p>384*385* @param prefix The prefix to look up.386* @return The associated Namespace URI, or null if the prefix387* is undeclared in this context.388* @see #getPrefix389* @see #getPrefixes390*/391public String getURI (String prefix)392{393return currentContext.getURI(prefix);394}395396397/**398* Return an enumeration of all prefixes whose declarations are399* active in the current context.400* This includes declarations from parent contexts that have401* not been overridden.402*403* <p><strong>Note:</strong> if there is a default prefix, it will not be404* returned in this enumeration; check for the default prefix405* using the {@link #getURI getURI} with an argument of "".</p>406*407* @return An enumeration of prefixes (never empty).408* @see #getDeclaredPrefixes409* @see #getURI410*/411public Enumeration getPrefixes ()412{413return currentContext.getPrefixes();414}415416417/**418* Return one of the prefixes mapped to a Namespace URI.419*420* <p>If more than one prefix is currently mapped to the same421* URI, this method will make an arbitrary selection; if you422* want all of the prefixes, use the {@link #getPrefixes}423* method instead.</p>424*425* <p><strong>Note:</strong> this will never return the empty (default) prefix;426* to check for a default prefix, use the {@link #getURI getURI}427* method with an argument of "".</p>428*429* @param uri the namespace URI430* @return one of the prefixes currently mapped to the URI supplied,431* or null if none is mapped or if the URI is assigned to432* the default namespace433* @see #getPrefixes(java.lang.String)434* @see #getURI435*/436public String getPrefix (String uri)437{438return currentContext.getPrefix(uri);439}440441442/**443* Return an enumeration of all prefixes for a given URI whose444* declarations are active in the current context.445* This includes declarations from parent contexts that have446* not been overridden.447*448* <p>This method returns prefixes mapped to a specific Namespace449* URI. The xml: prefix will be included. If you want only one450* prefix that's mapped to the Namespace URI, and you don't care451* which one you get, use the {@link #getPrefix getPrefix}452* method instead.</p>453*454* <p><strong>Note:</strong> the empty (default) prefix is <em>never</em> included455* in this enumeration; to check for the presence of a default456* Namespace, use the {@link #getURI getURI} method with an457* argument of "".</p>458*459* @param uri The Namespace URI.460* @return An enumeration of prefixes (never empty).461* @see #getPrefix462* @see #getDeclaredPrefixes463* @see #getURI464*/465public Enumeration getPrefixes (String uri)466{467List<String> prefixes = new ArrayList<>();468Enumeration allPrefixes = getPrefixes();469while (allPrefixes.hasMoreElements()) {470String prefix = (String)allPrefixes.nextElement();471if (uri.equals(getURI(prefix))) {472prefixes.add(prefix);473}474}475return Collections.enumeration(prefixes);476}477478479/**480* Return an enumeration of all prefixes declared in this context.481*482* <p>The empty (default) prefix will be included in this483* enumeration; note that this behaviour differs from that of484* {@link #getPrefix} and {@link #getPrefixes}.</p>485*486* @return An enumeration of all prefixes declared in this487* context.488* @see #getPrefixes489* @see #getURI490*/491public Enumeration getDeclaredPrefixes ()492{493return currentContext.getDeclaredPrefixes();494}495496/**497* Controls whether namespace declaration attributes are placed498* into the {@link #NSDECL NSDECL} namespace499* by {@link #processName processName()}. This may only be500* changed before any contexts have been pushed.501*502* @since SAX 2.1alpha503*504* @exception IllegalStateException when attempting to set this505* after any context has been pushed.506*/507public void setNamespaceDeclUris (boolean value)508{509if (contextPos != 0)510throw new IllegalStateException ();511if (value == namespaceDeclUris)512return;513namespaceDeclUris = value;514if (value)515currentContext.declarePrefix ("xmlns", NSDECL);516else {517contexts[contextPos] = currentContext = new Context();518currentContext.declarePrefix("xml", XMLNS);519}520}521522/**523* Returns true if namespace declaration attributes are placed into524* a namespace. This behavior is not the default.525*526* @since SAX 2.1alpha527*/528public boolean isNamespaceDeclUris ()529{ return namespaceDeclUris; }530531532533////////////////////////////////////////////////////////////////////534// Internal state.535////////////////////////////////////////////////////////////////////536537private Context contexts[];538private Context currentContext;539private int contextPos;540private boolean namespaceDeclUris;541542543////////////////////////////////////////////////////////////////////544// Internal classes.545////////////////////////////////////////////////////////////////////546547/**548* Internal class for a single Namespace context.549*550* <p>This module caches and reuses Namespace contexts,551* so the number allocated552* will be equal to the element depth of the document, not to the total553* number of elements (i.e. 5-10 rather than tens of thousands).554* Also, data structures used to represent contexts are shared when555* possible (child contexts without declarations) to further reduce556* the amount of memory that's consumed.557* </p>558*/559final class Context {560561/**562* Create the root-level Namespace context.563*/564Context ()565{566copyTables();567}568569570/**571* (Re)set the parent of this Namespace context.572* The context must either have been freshly constructed,573* or must have been cleared.574*575* @param context The parent Namespace context object.576*/577void setParent (Context parent)578{579this.parent = parent;580declarations = null;581prefixTable = parent.prefixTable;582uriTable = parent.uriTable;583elementNameTable = parent.elementNameTable;584attributeNameTable = parent.attributeNameTable;585defaultNS = parent.defaultNS;586declSeen = false;587}588589/**590* Makes associated state become collectible,591* invalidating this context.592* {@link #setParent} must be called before593* this context may be used again.594*/595void clear ()596{597parent = null;598prefixTable = null;599uriTable = null;600elementNameTable = null;601attributeNameTable = null;602defaultNS = null;603}604605606/**607* Declare a Namespace prefix for this context.608*609* @param prefix The prefix to declare.610* @param uri The associated Namespace URI.611* @see org.xml.sax.helpers.NamespaceSupport#declarePrefix612*/613void declarePrefix (String prefix, String uri)614{615// Lazy processing...616// if (!declsOK)617// throw new IllegalStateException (618// "can't declare any more prefixes in this context");619if (!declSeen) {620copyTables();621}622if (declarations == null) {623declarations = new ArrayList<>();624}625626prefix = prefix.intern();627uri = uri.intern();628if ("".equals(prefix)) {629if ("".equals(uri)) {630defaultNS = null;631} else {632defaultNS = uri;633}634} else {635prefixTable.put(prefix, uri);636uriTable.put(uri, prefix); // may wipe out another prefix637}638declarations.add(prefix);639}640641642/**643* Process an XML qualified name in this context.644*645* @param qName The XML qualified name.646* @param isAttribute true if this is an attribute name.647* @return An array of three strings containing the648* URI part (or empty string), the local part,649* and the raw name, all internalized, or null650* if there is an undeclared prefix.651* @see org.xml.sax.helpers.NamespaceSupport#processName652*/653String [] processName (String qName, boolean isAttribute)654{655String name[];656Map<String, String[]> table;657658// Select the appropriate table.659if (isAttribute) {660table = attributeNameTable;661} else {662table = elementNameTable;663}664665// Start by looking in the cache, and666// return immediately if the name667// is already known in this content668name = (String[])table.get(qName);669if (name != null) {670return name;671}672673// We haven't seen this name in this674// context before. Maybe in the parent675// context, but we can't assume prefix676// bindings are the same.677name = new String[3];678name[2] = qName.intern();679int index = qName.indexOf(':');680681682// No prefix.683if (index == -1) {684if (isAttribute) {685if (qName == "xmlns" && namespaceDeclUris)686name[0] = NSDECL;687else688name[0] = "";689} else if (defaultNS == null) {690name[0] = "";691} else {692name[0] = defaultNS;693}694name[1] = name[2];695}696697// Prefix698else {699String prefix = qName.substring(0, index);700String local = qName.substring(index+1);701String uri;702if ("".equals(prefix)) {703uri = defaultNS;704} else {705uri = (String)prefixTable.get(prefix);706}707if (uri == null708|| (!isAttribute && "xmlns".equals (prefix))) {709return null;710}711name[0] = uri;712name[1] = local.intern();713}714715// Save in the cache for future use.716// (Could be shared with parent context...)717table.put(name[2], name);718return name;719}720721722/**723* Look up the URI associated with a prefix in this context.724*725* @param prefix The prefix to look up.726* @return The associated Namespace URI, or null if none is727* declared.728* @see org.xml.sax.helpers.NamespaceSupport#getURI729*/730String getURI (String prefix)731{732if ("".equals(prefix)) {733return defaultNS;734} else if (prefixTable == null) {735return null;736} else {737return (String)prefixTable.get(prefix);738}739}740741742/**743* Look up one of the prefixes associated with a URI in this context.744*745* <p>Since many prefixes may be mapped to the same URI,746* the return value may be unreliable.</p>747*748* @param uri The URI to look up.749* @return The associated prefix, or null if none is declared.750* @see org.xml.sax.helpers.NamespaceSupport#getPrefix751*/752String getPrefix (String uri)753{754if (uriTable == null) {755return null;756} else {757return (String)uriTable.get(uri);758}759}760761762/**763* Return an enumeration of prefixes declared in this context.764*765* @return An enumeration of prefixes (possibly empty).766* @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes767*/768Enumeration getDeclaredPrefixes ()769{770if (declarations == null) {771return EMPTY_ENUMERATION;772} else {773return Collections.enumeration(declarations);774}775}776777/**778* Return an enumeration of all prefixes currently in force.779*780* <p>The default prefix, if in force, is <em>not</em>781* returned, and will have to be checked for separately.</p>782*783* @return An enumeration of prefixes (never empty).784* @see org.xml.sax.helpers.NamespaceSupport#getPrefixes785*/786Enumeration getPrefixes ()787{788if (prefixTable == null) {789return EMPTY_ENUMERATION;790} else {791return Collections.enumeration(prefixTable.keySet());792}793}794795796797////////////////////////////////////////////////////////////////798// Internal methods.799////////////////////////////////////////////////////////////////800801802/**803* Copy on write for the internal tables in this context.804*805* <p>This class is optimized for the normal case where most806* elements do not contain Namespace declarations.</p>807*/808private void copyTables ()809{810if (prefixTable != null) {811prefixTable = new HashMap<>(prefixTable);812} else {813prefixTable = new HashMap<>();814}815if (uriTable != null) {816uriTable = new HashMap<>(uriTable);817} else {818uriTable = new HashMap<>();819}820elementNameTable = new HashMap<>();821attributeNameTable = new HashMap<>();822declSeen = true;823}824825826827////////////////////////////////////////////////////////////////828// Protected state.829////////////////////////////////////////////////////////////////830831Map<String, String> prefixTable;832Map<String, String> uriTable;833Map<String, String[]> elementNameTable;834Map<String, String[]> attributeNameTable;835String defaultNS = null;836837838839////////////////////////////////////////////////////////////////840// Internal state.841////////////////////////////////////////////////////////////////842843private List<String> declarations = null;844private boolean declSeen = false;845private Context parent = null;846}847}848849// end of NamespaceSupport.java850851852