1 // NamespaceSupport.java - generic Namespace support for SAX.
2 // http://www.saxproject.org
3 // Written by David Megginson
4 // This class is in the Public Domain. NO WARRANTY!
6 // $Id: NamespaceSupport.java,v 1.6.2.5 2002/01/29 21:34:14 dbrownell Exp $
8 package org
.xml
.sax
.helpers
;
10 import java
.util
.EmptyStackException
;
11 import java
.util
.Enumeration
;
12 import java
.util
.Hashtable
;
13 import java
.util
.Vector
;
17 * Encapsulate Namespace logic for use by applications using SAX,
18 * or internally by SAX drivers.
21 * <em>This module, both source code and documentation, is in the
22 * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
23 * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
24 * for further information.
27 * <p>This class encapsulates the logic of Namespace processing:
28 * it tracks the declarations currently in force for each context
29 * and automatically processes qualified XML 1.0 names into their
30 * Namespace parts; it can also be used in reverse for generating
31 * XML 1.0 from Namespaces.</p>
33 * <p>Namespace support objects are reusable, but the reset method
34 * must be invoked between each session.</p>
36 * <p>Here is a simple session:</p>
39 * String parts[] = new String[3];
40 * NamespaceSupport support = new NamespaceSupport();
42 * support.pushContext();
43 * support.declarePrefix("", "http://www.w3.org/1999/xhtml");
44 * support.declarePrefix("dc", "http://www.purl.org/dc#");
46 * parts = support.processName("p", parts, false);
47 * System.out.println("Namespace URI: " + parts[0]);
48 * System.out.println("Local name: " + parts[1]);
49 * System.out.println("Raw name: " + parts[2]);
51 * parts = support.processName("dc:title", parts, false);
52 * System.out.println("Namespace URI: " + parts[0]);
53 * System.out.println("Local name: " + parts[1]);
54 * System.out.println("Raw name: " + parts[2]);
56 * support.popContext();
59 * <p>Note that this class is optimized for the use case where most
60 * elements do not contain Namespace declarations: if the same
61 * prefix/URI mapping is repeated for each context (for example), this
62 * class will be somewhat less efficient.</p>
64 * <p>Although SAX drivers (parsers) may choose to use this class to
65 * implement namespace handling, they are not required to do so.
66 * Applications must track namespace information themselves if they
67 * want to use namespace information.
70 * @author David Megginson
71 * @version 2.0.1 (sax2r2)
73 public class NamespaceSupport
77 ////////////////////////////////////////////////////////////////////
79 ////////////////////////////////////////////////////////////////////
83 * The XML Namespace URI as a constant.
84 * The value is <code>http://www.w3.org/XML/1998/namespace</code>
85 * as defined in the XML Namespaces specification.
87 * <p>This is the Namespace URI that is automatically mapped
88 * to the "xml" prefix.</p>
90 public final static String XMLNS
=
91 "http://www.w3.org/XML/1998/namespace";
95 * An empty enumeration.
97 private final static Enumeration EMPTY_ENUMERATION
=
98 new Vector().elements();
101 ////////////////////////////////////////////////////////////////////
103 ////////////////////////////////////////////////////////////////////
107 * Create a new Namespace support object.
109 public NamespaceSupport ()
116 ////////////////////////////////////////////////////////////////////
117 // Context management.
118 ////////////////////////////////////////////////////////////////////
122 * Reset this Namespace support object for reuse.
124 * <p>It is necessary to invoke this method before reusing the
125 * Namespace support object for a new session.</p>
129 contexts
= new Context
[32];
131 contexts
[contextPos
] = currentContext
= new Context();
132 currentContext
.declarePrefix("xml", XMLNS
);
137 * Start a new Namespace context.
138 * The new context will automatically inherit
139 * the declarations of its parent context, but it will also keep
140 * track of which declarations were made within this context.
142 * <p>Event callback code should start a new context once per element.
143 * This means being ready to call this in either of two places.
144 * For elements that don't include namespace declarations, the
145 * <em>ContentHandler.startElement()</em> callback is the right place.
146 * For elements with such a declaration, it'd done in the first
147 * <em>ContentHandler.startPrefixMapping()</em> callback.
148 * A boolean flag can be used to
149 * track whether a context has been started yet. When either of
150 * those methods is called, it checks the flag to see if a new context
151 * needs to be started. If so, it starts the context and sets the
152 * flag. After <em>ContentHandler.startElement()</em>
153 * does that, it always clears the flag.
155 * <p>Normally, SAX drivers would push a new context at the beginning
156 * of each XML element. Then they perform a first pass over the
157 * attributes to process all namespace declarations, making
158 * <em>ContentHandler.startPrefixMapping()</em> callbacks.
159 * Then a second pass is made, to determine the namespace-qualified
160 * names for all attributes and for the element name.
161 * Finally all the information for the
162 * <em>ContentHandler.startElement()</em> callback is available,
163 * so it can then be made.
165 * <p>The Namespace support object always starts with a base context
166 * already in force: in this context, only the "xml" prefix is
169 * @see org.xml.sax.ContentHandler
172 public void pushContext ()
174 int max
= contexts
.length
;
176 contexts
[contextPos
].declsOK
= false;
179 // Extend the array if necessary
180 if (contextPos
>= max
) {
181 Context newContexts
[] = new Context
[max
*2];
182 System
.arraycopy(contexts
, 0, newContexts
, 0, max
);
184 contexts
= newContexts
;
187 // Allocate the context if necessary.
188 currentContext
= contexts
[contextPos
];
189 if (currentContext
== null) {
190 contexts
[contextPos
] = currentContext
= new Context();
193 // Set the parent, if any.
194 if (contextPos
> 0) {
195 currentContext
.setParent(contexts
[contextPos
- 1]);
201 * Revert to the previous Namespace context.
203 * <p>Normally, you should pop the context at the end of each
204 * XML element. After popping the context, all Namespace prefix
205 * mappings that were previously in force are restored.</p>
207 * <p>You must not attempt to declare additional Namespace
208 * prefixes after popping a context, unless you push another
213 public void popContext ()
215 contexts
[contextPos
].clear();
217 if (contextPos
< 0) {
218 throw new EmptyStackException();
220 currentContext
= contexts
[contextPos
];
225 ////////////////////////////////////////////////////////////////////
226 // Operations within a context.
227 ////////////////////////////////////////////////////////////////////
231 * Declare a Namespace prefix. All prefixes must be declared
232 * before they are referenced. For example, a SAX driver (parser)
233 * would scan an element's attributes
234 * in two passes: first for namespace declarations,
235 * then a second pass using {@link #processName processName()} to
236 * interpret prefixes against (potentially redefined) prefixes.
238 * <p>This method declares a prefix in the current Namespace
239 * context; the prefix will remain in force until this context
240 * is popped, unless it is shadowed in a descendant context.</p>
242 * <p>To declare the default element Namespace, use the empty string as
245 * <p>Note that you must <em>not</em> declare a prefix after
246 * you've pushed and popped another Namespace context, or
247 * treated the declarations phase as complete by processing
248 * a prefixed name.</p>
250 * <p>Note that there is an asymmetry in this library: {@link
251 * #getPrefix getPrefix} will not return the "" prefix,
252 * even if you have declared a default element namespace.
253 * To check for a default namespace,
254 * you have to look it up explicitly using {@link #getURI getURI}.
255 * This asymmetry exists to make it easier to look up prefixes
256 * for attribute names, where the default prefix is not allowed.</p>
258 * @param prefix The prefix to declare, or the empty string to
259 * indicate the default element namespace. This may never have
260 * the value "xml" or "xmlns".
261 * @param uri The Namespace URI to associate with the prefix.
262 * @return true if the prefix was legal, false otherwise
263 * @exception IllegalStateException when a prefix is declared
264 * after looking up a name in the context, or after pushing
265 * another context on top of it.
271 public boolean declarePrefix (String prefix
, String uri
)
273 if (prefix
.equals("xml") || prefix
.equals("xmlns")) {
276 currentContext
.declarePrefix(prefix
, uri
);
283 * Process a raw XML 1.0 name, after all declarations in the current
284 * context have been handled by {@link #declarePrefix declarePrefix()}.
286 * <p>This method processes a raw XML 1.0 name in the current
287 * context by removing the prefix and looking it up among the
288 * prefixes currently declared. The return value will be the
289 * array supplied by the caller, filled in as follows:</p>
293 * <dd>The Namespace URI, or an empty string if none is
296 * <dd>The local name (without prefix).</dd>
298 * <dd>The original raw name.</dd>
301 * <p>All of the strings in the array will be internalized. If
302 * the raw name has a prefix that has not been declared, then
303 * the return value will be null.</p>
305 * <p>Note that attribute names are processed differently than
306 * element names: an unprefixed element name will received the
307 * default Namespace (if any), while an unprefixed attribute name
310 * @param qName The raw XML 1.0 name to be processed.
311 * @param parts An array supplied by the caller, capable of
312 * holding at least three members.
313 * @param isAttribute A flag indicating whether this is an
314 * attribute name (true) or an element name (false).
315 * @return The supplied array holding three internalized strings
316 * representing the Namespace URI (or empty string), the
317 * local name, and the raw XML 1.0 name; or null if there
318 * is an undeclared prefix.
319 * @see #declarePrefix
320 * @see java.lang.String#intern */
321 public String
[] processName (String qName
, String parts
[],
324 String myParts
[] = currentContext
.processName(qName
, isAttribute
);
325 if (myParts
== null) {
328 parts
[0] = myParts
[0];
329 parts
[1] = myParts
[1];
330 parts
[2] = myParts
[2];
337 * Look up a prefix and get the currently-mapped Namespace URI.
339 * <p>This method looks up the prefix in the current context.
340 * Use the empty string ("") for the default Namespace.</p>
342 * @param prefix The prefix to look up.
343 * @return The associated Namespace URI, or null if the prefix
344 * is undeclared in this context.
348 public String
getURI (String prefix
)
350 return currentContext
.getURI(prefix
);
355 * Return an enumeration of all prefixes currently declared.
357 * <p><strong>Note:</strong> if there is a default prefix, it will not be
358 * returned in this enumeration; check for the default prefix
359 * using the {@link #getURI getURI} with an argument of "".</p>
361 * @return An enumeration of all prefixes declared in the
362 * current context except for the empty (default)
364 * @see #getDeclaredPrefixes
367 public Enumeration
getPrefixes ()
369 return currentContext
.getPrefixes();
374 * Return one of the prefixes mapped to a Namespace URI.
376 * <p>If more than one prefix is currently mapped to the same
377 * URI, this method will make an arbitrary selection; if you
378 * want all of the prefixes, use the {@link #getPrefixes}
379 * method instead.</p>
381 * <p><strong>Note:</strong> this will never return the empty (default) prefix;
382 * to check for a default prefix, use the {@link #getURI getURI}
383 * method with an argument of "".</p>
385 * @param uri The Namespace URI.
386 * @param isAttribute true if this prefix is for an attribute
387 * (and the default Namespace is not allowed).
388 * @return One of the prefixes currently mapped to the URI supplied,
389 * or null if none is mapped or if the URI is assigned to
390 * the default Namespace.
391 * @see #getPrefixes(java.lang.String)
394 public String
getPrefix (String uri
)
396 return currentContext
.getPrefix(uri
);
401 * Return an enumeration of all prefixes currently declared for a URI.
403 * <p>This method returns prefixes mapped to a specific Namespace
404 * URI. The xml: prefix will be included. If you want only one
405 * prefix that's mapped to the Namespace URI, and you don't care
406 * which one you get, use the {@link #getPrefix getPrefix}
407 * method instead.</p>
409 * <p><strong>Note:</strong> the empty (default) prefix is <em>never</em> included
410 * in this enumeration; to check for the presence of a default
411 * Namespace, use the {@link #getURI getURI} method with an
412 * argument of "".</p>
414 * @param uri The Namespace URI.
415 * @return An enumeration of all prefixes declared in the
418 * @see #getDeclaredPrefixes
421 public Enumeration
getPrefixes (String uri
)
423 Vector prefixes
= new Vector();
424 Enumeration allPrefixes
= getPrefixes();
425 while (allPrefixes
.hasMoreElements()) {
426 String prefix
= (String
)allPrefixes
.nextElement();
427 if (uri
.equals(getURI(prefix
))) {
428 prefixes
.addElement(prefix
);
431 return prefixes
.elements();
436 * Return an enumeration of all prefixes declared in this context.
438 * <p>The empty (default) prefix will be included in this
439 * enumeration; note that this behaviour differs from that of
440 * {@link #getPrefix} and {@link #getPrefixes}.</p>
442 * @return An enumeration of all prefixes declared in this
447 public Enumeration
getDeclaredPrefixes ()
449 return currentContext
.getDeclaredPrefixes();
454 ////////////////////////////////////////////////////////////////////
456 ////////////////////////////////////////////////////////////////////
458 private Context contexts
[];
459 private Context currentContext
;
460 private int contextPos
;
464 ////////////////////////////////////////////////////////////////////
466 ////////////////////////////////////////////////////////////////////
469 * Internal class for a single Namespace context.
471 * <p>This module caches and reuses Namespace contexts,
472 * so the number allocated
473 * will be equal to the element depth of the document, not to the total
474 * number of elements (i.e. 5-10 rather than tens of thousands).
475 * Also, data structures used to represent contexts are shared when
476 * possible (child contexts without declarations) to further reduce
477 * the amount of memory that's consumed.
480 final class Context
{
483 * Create the root-level Namespace context.
492 * (Re)set the parent of this Namespace context.
493 * The context must either have been freshly constructed,
494 * or must have been cleared.
496 * @param context The parent Namespace context object.
498 void setParent (Context parent
)
500 this.parent
= parent
;
502 prefixTable
= parent
.prefixTable
;
503 uriTable
= parent
.uriTable
;
504 elementNameTable
= parent
.elementNameTable
;
505 attributeNameTable
= parent
.attributeNameTable
;
506 defaultNS
= parent
.defaultNS
;
512 * Makes associated state become collectible,
513 * invalidating this context.
514 * {@link #setParent} must be called before
515 * this context may be used again.
522 elementNameTable
= null;
523 attributeNameTable
= null;
529 * Declare a Namespace prefix for this context.
531 * @param prefix The prefix to declare.
532 * @param uri The associated Namespace URI.
533 * @see org.xml.sax.helpers.NamespaceSupport#declarePrefix
535 void declarePrefix (String prefix
, String uri
)
537 // Lazy processing...
539 throw new IllegalStateException (
540 "can't declare any more prefixes in this context");
544 if (declarations
== null) {
545 declarations
= new Vector();
548 prefix
= prefix
.intern();
550 if ("".equals(prefix
)) {
551 if ("".equals(uri
)) {
557 prefixTable
.put(prefix
, uri
);
558 uriTable
.put(uri
, prefix
); // may wipe out another prefix
560 declarations
.addElement(prefix
);
565 * Process a raw XML 1.0 name in this context.
567 * @param qName The raw XML 1.0 name.
568 * @param isAttribute true if this is an attribute name.
569 * @return An array of three strings containing the
570 * URI part (or empty string), the local part,
571 * and the raw name, all internalized, or null
572 * if there is an undeclared prefix.
573 * @see org.xml.sax.helpers.NamespaceSupport#processName
575 String
[] processName (String qName
, boolean isAttribute
)
580 // detect errors in call sequence
583 // Select the appropriate table.
585 table
= attributeNameTable
;
587 table
= elementNameTable
;
590 // Start by looking in the cache, and
591 // return immediately if the name
592 // is already known in this content
593 name
= (String
[])table
.get(qName
);
598 // We haven't seen this name in this
599 // context before. Maybe in the parent
600 // context, but we can't assume prefix
601 // bindings are the same.
602 name
= new String
[3];
603 name
[2] = qName
.intern();
604 int index
= qName
.indexOf(':');
609 if (isAttribute
|| defaultNS
== null) {
619 String prefix
= qName
.substring(0, index
);
620 String local
= qName
.substring(index
+1);
622 if ("".equals(prefix
)) {
625 uri
= (String
)prefixTable
.get(prefix
);
631 name
[1] = local
.intern();
634 // Save in the cache for future use.
635 // (Could be shared with parent context...)
636 table
.put(name
[2], name
);
642 * Look up the URI associated with a prefix in this context.
644 * @param prefix The prefix to look up.
645 * @return The associated Namespace URI, or null if none is
647 * @see org.xml.sax.helpers.NamespaceSupport#getURI
649 String
getURI (String prefix
)
651 if ("".equals(prefix
)) {
653 } else if (prefixTable
== null) {
656 return (String
)prefixTable
.get(prefix
);
662 * Look up one of the prefixes associated with a URI in this context.
664 * <p>Since many prefixes may be mapped to the same URI,
665 * the return value may be unreliable.</p>
667 * @param uri The URI to look up.
668 * @return The associated prefix, or null if none is declared.
669 * @see org.xml.sax.helpers.NamespaceSupport#getPrefix
671 String
getPrefix (String uri
)
673 if (uriTable
== null) {
676 return (String
)uriTable
.get(uri
);
682 * Return an enumeration of prefixes declared in this context.
684 * @return An enumeration of prefixes (possibly empty).
685 * @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes
687 Enumeration
getDeclaredPrefixes ()
689 if (declarations
== null) {
690 return EMPTY_ENUMERATION
;
692 return declarations
.elements();
698 * Return an enumeration of all prefixes currently in force.
700 * <p>The default prefix, if in force, is <em>not</em>
701 * returned, and will have to be checked for separately.</p>
703 * @return An enumeration of prefixes (never empty).
704 * @see org.xml.sax.helpers.NamespaceSupport#getPrefixes
706 Enumeration
getPrefixes ()
708 if (prefixTable
== null) {
709 return EMPTY_ENUMERATION
;
711 return prefixTable
.keys();
717 ////////////////////////////////////////////////////////////////
719 ////////////////////////////////////////////////////////////////
723 * Copy on write for the internal tables in this context.
725 * <p>This class is optimized for the normal case where most
726 * elements do not contain Namespace declarations.</p>
728 private void copyTables ()
730 if (prefixTable
!= null) {
731 prefixTable
= (Hashtable
)prefixTable
.clone();
733 prefixTable
= new Hashtable();
735 if (uriTable
!= null) {
736 uriTable
= (Hashtable
)uriTable
.clone();
738 uriTable
= new Hashtable();
740 elementNameTable
= new Hashtable();
741 attributeNameTable
= new Hashtable();
747 ////////////////////////////////////////////////////////////////
749 ////////////////////////////////////////////////////////////////
751 Hashtable prefixTable
;
753 Hashtable elementNameTable
;
754 Hashtable attributeNameTable
;
755 String defaultNS
= null;
756 boolean declsOK
= true;
760 ////////////////////////////////////////////////////////////////
762 ////////////////////////////////////////////////////////////////
764 private Vector declarations
= null;
765 private boolean declSeen
= false;
766 private Context parent
= null;
770 // end of NamespaceSupport.java