1
2
3
4
5
6
7 package org.xml.sax.helpers;
8
9 import java.util.EmptyStackException;
10 import java.util.Enumeration;
11 import java.util.Hashtable;
12 import java.util.Vector;
13
14
15 /***
16 * Encapsulate Namespace logic for use by applications using SAX,
17 * or internally by SAX drivers.
18 *
19 * <blockquote>
20 * <em>This module, both source code and documentation, is in the
21 * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
22 * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
23 * for further information.
24 * </blockquote>
25 *
26 * <p>This class encapsulates the logic of Namespace processing: it
27 * tracks the declarations currently in force for each context and
28 * automatically processes qualified XML names into their Namespace
29 * parts; it can also be used in reverse for generating XML qnames
30 * from Namespaces.</p>
31 *
32 * <p>Namespace support objects are reusable, but the reset method
33 * must be invoked between each session.</p>
34 *
35 * <p>Here is a simple session:</p>
36 *
37 * <pre>
38 * String parts[] = new String[3];
39 * NamespaceSupport support = new NamespaceSupport();
40 *
41 * support.pushContext();
42 * support.declarePrefix("", "http://www.w3.org/1999/xhtml");
43 * support.declarePrefix("dc", "http://www.purl.org/dc#");
44 *
45 * parts = support.processName("p", parts, false);
46 * System.out.println("Namespace URI: " + parts[0]);
47 * System.out.println("Local name: " + parts[1]);
48 * System.out.println("Raw name: " + parts[2]);
49 *
50 * parts = support.processName("dc:title", parts, false);
51 * System.out.println("Namespace URI: " + parts[0]);
52 * System.out.println("Local name: " + parts[1]);
53 * System.out.println("Raw name: " + parts[2]);
54 *
55 * support.popContext();
56 * </pre>
57 *
58 * <p>Note that this class is optimized for the use case where most
59 * elements do not contain Namespace declarations: if the same
60 * prefix/URI mapping is repeated for each context (for example), this
61 * class will be somewhat less efficient.</p>
62 *
63 * <p>Although SAX drivers (parsers) may choose to use this class to
64 * implement namespace handling, they are not required to do so.
65 * Applications must track namespace information themselves if they
66 * want to use namespace information.
67 *
68 * @since SAX 2.0
69 * @author David Megginson
70 * @version 2.0.1 (sax2r2)
71 */
72 public class NamespaceSupport
73 {
74
75
76
77
78
79
80
81 /***
82 * The XML Namespace URI as a constant.
83 * The value is <code>http://www.w3.org/XML/1998/namespace</code>
84 * as defined in the "Namespaces in XML" * recommendation.
85 *
86 * <p>This is the Namespace URI that is automatically mapped
87 * to the "xml" prefix.</p>
88 */
89 public final static String XMLNS =
90 "http://www.w3.org/XML/1998/namespace";
91
92
93 /***
94 * The namespace declaration URI as a constant.
95 * The value is <code>http://www.w3.org/xmlns/2000/</code>, as defined
96 * in a backwards-incompatible erratum to the "Namespaces in XML"
97 * recommendation. Because that erratum postdated SAX2, SAX2 defaults
98 * to the original recommendation, and does not normally use this URI.
99 *
100 *
101 * <p>This is the Namespace URI that is optionally applied to
102 * <em>xmlns</em> and <em>xmlns:*</em> attributes, which are used to
103 * declare namespaces. </p>
104 *
105 * @since SAX 2.1alpha
106 * @see #setNamespaceDeclUris
107 * @see #isNamespaceDeclUris
108 */
109 public final static String NSDECL =
110 "http://www.w3.org/xmlns/2000/";
111
112
113 /***
114 * An empty enumeration.
115 */
116 private final static Enumeration EMPTY_ENUMERATION =
117 new Vector().elements();
118
119
120
121
122
123
124
125 /***
126 * Create a new Namespace support object.
127 */
128 public NamespaceSupport ()
129 {
130 reset();
131 }
132
133
134
135
136
137
138
139
140 /***
141 * Reset this Namespace support object for reuse.
142 *
143 * <p>It is necessary to invoke this method before reusing the
144 * Namespace support object for a new session. If namespace
145 * declaration URIs are to be supported, that flag must also
146 * be set to a non-default value.
147 * </p>
148 *
149 * @see #setNamespaceDeclUris
150 */
151 public void reset ()
152 {
153 contexts = new Context[32];
154 namespaceDeclUris = false;
155 contextPos = 0;
156 contexts[contextPos] = currentContext = new Context();
157 currentContext.declarePrefix("xml", XMLNS);
158 }
159
160
161 /***
162 * Start a new Namespace context.
163 * The new context will automatically inherit
164 * the declarations of its parent context, but it will also keep
165 * track of which declarations were made within this context.
166 *
167 * <p>Event callback code should start a new context once per element.
168 * This means being ready to call this in either of two places.
169 * For elements that don't include namespace declarations, the
170 * <em>ContentHandler.startElement()</em> callback is the right place.
171 * For elements with such a declaration, it'd done in the first
172 * <em>ContentHandler.startPrefixMapping()</em> callback.
173 * A boolean flag can be used to
174 * track whether a context has been started yet. When either of
175 * those methods is called, it checks the flag to see if a new context
176 * needs to be started. If so, it starts the context and sets the
177 * flag. After <em>ContentHandler.startElement()</em>
178 * does that, it always clears the flag.
179 *
180 * <p>Normally, SAX drivers would push a new context at the beginning
181 * of each XML element. Then they perform a first pass over the
182 * attributes to process all namespace declarations, making
183 * <em>ContentHandler.startPrefixMapping()</em> callbacks.
184 * Then a second pass is made, to determine the namespace-qualified
185 * names for all attributes and for the element name.
186 * Finally all the information for the
187 * <em>ContentHandler.startElement()</em> callback is available,
188 * so it can then be made.
189 *
190 * <p>The Namespace support object always starts with a base context
191 * already in force: in this context, only the "xml" prefix is
192 * declared.</p>
193 *
194 * @see org.xml.sax.ContentHandler
195 * @see #popContext
196 */
197 public void pushContext ()
198 {
199 int max = contexts.length;
200
201 contexts [contextPos].declsOK = false;
202 contextPos++;
203
204
205 if (contextPos >= max) {
206 Context newContexts[] = new Context[max*2];
207 System.arraycopy(contexts, 0, newContexts, 0, max);
208 max *= 2;
209 contexts = newContexts;
210 }
211
212
213 currentContext = contexts[contextPos];
214 if (currentContext == null) {
215 contexts[contextPos] = currentContext = new Context();
216 }
217
218
219 if (contextPos > 0) {
220 currentContext.setParent(contexts[contextPos - 1]);
221 }
222 }
223
224
225 /***
226 * Revert to the previous Namespace context.
227 *
228 * <p>Normally, you should pop the context at the end of each
229 * XML element. After popping the context, all Namespace prefix
230 * mappings that were previously in force are restored.</p>
231 *
232 * <p>You must not attempt to declare additional Namespace
233 * prefixes after popping a context, unless you push another
234 * context first.</p>
235 *
236 * @see #pushContext
237 */
238 public void popContext ()
239 {
240 contexts[contextPos].clear();
241 contextPos--;
242 if (contextPos < 0) {
243 throw new EmptyStackException();
244 }
245 currentContext = contexts[contextPos];
246 }
247
248
249
250
251
252
253
254
255 /***
256 * Declare a Namespace prefix. All prefixes must be declared
257 * before they are referenced. For example, a SAX driver (parser)
258 * would scan an element's attributes
259 * in two passes: first for namespace declarations,
260 * then a second pass using {@link #processName processName()} to
261 * interpret prefixes against (potentially redefined) prefixes.
262 *
263 * <p>This method declares a prefix in the current Namespace
264 * context; the prefix will remain in force until this context
265 * is popped, unless it is shadowed in a descendant context.</p>
266 *
267 * <p>To declare the default element Namespace, use the empty string as
268 * the prefix.</p>
269 *
270 * <p>Note that you must <em>not</em> declare a prefix after
271 * you've pushed and popped another Namespace context, or
272 * treated the declarations phase as complete by processing
273 * a prefixed name.</p>
274 *
275 * <p>Note that there is an asymmetry in this library: {@link
276 * #getPrefix getPrefix} will not return the "" prefix,
277 * even if you have declared a default element namespace.
278 * To check for a default namespace,
279 * you have to look it up explicitly using {@link #getURI getURI}.
280 * This asymmetry exists to make it easier to look up prefixes
281 * for attribute names, where the default prefix is not allowed.</p>
282 *
283 * @param prefix The prefix to declare, or the empty string to
284 * indicate the default element namespace. This may never have
285 * the value "xml" or "xmlns".
286 * @param uri The Namespace URI to associate with the prefix.
287 * @return true if the prefix was legal, false otherwise
288 * @exception IllegalStateException when a prefix is declared
289 * after looking up a name in the context, or after pushing
290 * another context on top of it.
291 *
292 * @see #processName
293 * @see #getURI
294 * @see #getPrefix
295 */
296 public boolean declarePrefix (String prefix, String uri)
297 {
298 if (prefix.equals("xml") || prefix.equals("xmlns")) {
299 return false;
300 } else {
301 currentContext.declarePrefix(prefix, uri);
302 return true;
303 }
304 }
305
306
307 /***
308 * Process a raw XML qualified name, after all declarations in the
309 * current context have been handled by {@link #declarePrefix
310 * declarePrefix()}.
311 *
312 * <p>This method processes a raw XML qualified name in the
313 * current context by removing the prefix and looking it up among
314 * the prefixes currently declared. The return value will be the
315 * array supplied by the caller, filled in as follows:</p>
316 *
317 * <dl>
318 * <dt>parts[0]</dt>
319 * <dd>The Namespace URI, or an empty string if none is
320 * in use.</dd>
321 * <dt>parts[1]</dt>
322 * <dd>The local name (without prefix).</dd>
323 * <dt>parts[2]</dt>
324 * <dd>The original raw name.</dd>
325 * </dl>
326 *
327 * <p>All of the strings in the array will be internalized. If
328 * the raw name has a prefix that has not been declared, then
329 * the return value will be null.</p>
330 *
331 * <p>Note that attribute names are processed differently than
332 * element names: an unprefixed element name will receive the
333 * default Namespace (if any), while an unprefixed attribute name
334 * will not.</p>
335 *
336 * @param qName The XML qualified name to be processed.
337 * @param parts An array supplied by the caller, capable of
338 * holding at least three members.
339 * @param isAttribute A flag indicating whether this is an
340 * attribute name (true) or an element name (false).
341 * @return The supplied array holding three internalized strings
342 * representing the Namespace URI (or empty string), the
343 * local name, and the XML qualified name; or null if there
344 * is an undeclared prefix.
345 * @see #declarePrefix
346 * @see java.lang.String#intern */
347 public String [] processName (String qName, String parts[],
348 boolean isAttribute)
349 {
350 String myParts[] = currentContext.processName(qName, isAttribute);
351 if (myParts == null) {
352 return null;
353 } else {
354 parts[0] = myParts[0];
355 parts[1] = myParts[1];
356 parts[2] = myParts[2];
357 return parts;
358 }
359 }
360
361
362 /***
363 * Look up a prefix and get the currently-mapped Namespace URI.
364 *
365 * <p>This method looks up the prefix in the current context.
366 * Use the empty string ("") for the default Namespace.</p>
367 *
368 * @param prefix The prefix to look up.
369 * @return The associated Namespace URI, or null if the prefix
370 * is undeclared in this context.
371 * @see #getPrefix
372 * @see #getPrefixes
373 */
374 public String getURI (String prefix)
375 {
376 return currentContext.getURI(prefix);
377 }
378
379
380 /***
381 * Return an enumeration of all prefixes whose declarations are
382 * active in the current context.
383 * This includes declarations from parent contexts that have
384 * not been overridden.
385 *
386 * <p><strong>Note:</strong> if there is a default prefix, it will not be
387 * returned in this enumeration; check for the default prefix
388 * using the {@link #getURI getURI} with an argument of "".</p>
389 *
390 * @return An enumeration of prefixes (never empty).
391 * @see #getDeclaredPrefixes
392 * @see #getURI
393 */
394 public Enumeration getPrefixes ()
395 {
396 return currentContext.getPrefixes();
397 }
398
399
400 /***
401 * Return one of the prefixes mapped to a Namespace URI.
402 *
403 * <p>If more than one prefix is currently mapped to the same
404 * URI, this method will make an arbitrary selection; if you
405 * want all of the prefixes, use the {@link #getPrefixes}
406 * method instead.</p>
407 *
408 * <p><strong>Note:</strong> this will never return the empty (default) prefix;
409 * to check for a default prefix, use the {@link #getURI getURI}
410 * method with an argument of "".</p>
411 *
412 * @param uri The Namespace URI.
413 * @param isAttribute true if this prefix is for an attribute
414 * (and the default Namespace is not allowed).
415 * @return One of the prefixes currently mapped to the URI supplied,
416 * or null if none is mapped or if the URI is assigned to
417 * the default Namespace.
418 * @see #getPrefixes(java.lang.String)
419 * @see #getURI
420 */
421 public String getPrefix (String uri)
422 {
423 return currentContext.getPrefix(uri);
424 }
425
426
427 /***
428 * Return an enumeration of all prefixes for a given URI whose
429 * declarations are active in the current context.
430 * This includes declarations from parent contexts that have
431 * not been overridden.
432 *
433 * <p>This method returns prefixes mapped to a specific Namespace
434 * URI. The xml: prefix will be included. If you want only one
435 * prefix that's mapped to the Namespace URI, and you don't care
436 * which one you get, use the {@link #getPrefix getPrefix}
437 * method instead.</p>
438 *
439 * <p><strong>Note:</strong> the empty (default) prefix is <em>never</em> included
440 * in this enumeration; to check for the presence of a default
441 * Namespace, use the {@link #getURI getURI} method with an
442 * argument of "".</p>
443 *
444 * @param uri The Namespace URI.
445 * @return An enumeration of prefixes (never empty).
446 * @see #getPrefix
447 * @see #getDeclaredPrefixes
448 * @see #getURI
449 */
450 public Enumeration getPrefixes (String uri)
451 {
452 Vector prefixes = new Vector();
453 Enumeration allPrefixes = getPrefixes();
454 while (allPrefixes.hasMoreElements()) {
455 String prefix = (String)allPrefixes.nextElement();
456 if (uri.equals(getURI(prefix))) {
457 prefixes.addElement(prefix);
458 }
459 }
460 return prefixes.elements();
461 }
462
463
464 /***
465 * Return an enumeration of all prefixes declared in this context.
466 *
467 * <p>The empty (default) prefix will be included in this
468 * enumeration; note that this behaviour differs from that of
469 * {@link #getPrefix} and {@link #getPrefixes}.</p>
470 *
471 * @return An enumeration of all prefixes declared in this
472 * context.
473 * @see #getPrefixes
474 * @see #getURI
475 */
476 public Enumeration getDeclaredPrefixes ()
477 {
478 return currentContext.getDeclaredPrefixes();
479 }
480
481 /***
482 * Controls whether namespace declaration attributes are placed
483 * into the {@link #NSDECL NSDECL} namespace
484 * by {@link #processName processName()}. This may only be
485 * changed before any contexts have been pushed.
486 *
487 * @since SAX 2.1alpha
488 *
489 * @exception IllegalStateException when attempting to set this
490 * after any context has been pushed.
491 */
492 public void setNamespaceDeclUris (boolean value)
493 {
494 if (contextPos != 0)
495 throw new IllegalStateException ();
496 if (value == namespaceDeclUris)
497 return;
498 namespaceDeclUris = value;
499 if (value)
500 currentContext.declarePrefix ("xmlns", NSDECL);
501 else {
502 contexts[contextPos] = currentContext = new Context();
503 currentContext.declarePrefix("xml", XMLNS);
504 }
505 }
506
507 /***
508 * Returns true if namespace declaration attributes are placed into
509 * a namespace. This behavior is not the default.
510 *
511 * @since SAX 2.1alpha
512 */
513 public boolean isNamespaceDeclUris ()
514 { return namespaceDeclUris; }
515
516
517
518
519
520
521
522 private Context contexts[];
523 private Context currentContext;
524 private int contextPos;
525 private boolean namespaceDeclUris;
526
527
528
529
530
531
532 /***
533 * Internal class for a single Namespace context.
534 *
535 * <p>This module caches and reuses Namespace contexts,
536 * so the number allocated
537 * will be equal to the element depth of the document, not to the total
538 * number of elements (i.e. 5-10 rather than tens of thousands).
539 * Also, data structures used to represent contexts are shared when
540 * possible (child contexts without declarations) to further reduce
541 * the amount of memory that's consumed.
542 * </p>
543 */
544 final class Context {
545
546 /***
547 * Create the root-level Namespace context.
548 */
549 Context ()
550 {
551 copyTables();
552 }
553
554
555 /***
556 * (Re)set the parent of this Namespace context.
557 * The context must either have been freshly constructed,
558 * or must have been cleared.
559 *
560 * @param context The parent Namespace context object.
561 */
562 void setParent (Context parent)
563 {
564 this.parent = parent;
565 declarations = null;
566 prefixTable = parent.prefixTable;
567 uriTable = parent.uriTable;
568 elementNameTable = parent.elementNameTable;
569 attributeNameTable = parent.attributeNameTable;
570 defaultNS = parent.defaultNS;
571 declSeen = false;
572 declsOK = true;
573 }
574
575 /***
576 * Makes associated state become collectible,
577 * invalidating this context.
578 * {@link #setParent} must be called before
579 * this context may be used again.
580 */
581 void clear ()
582 {
583 parent = null;
584 prefixTable = null;
585 uriTable = null;
586 elementNameTable = null;
587 attributeNameTable = null;
588 defaultNS = null;
589 }
590
591
592 /***
593 * Declare a Namespace prefix for this context.
594 *
595 * @param prefix The prefix to declare.
596 * @param uri The associated Namespace URI.
597 * @see org.xml.sax.helpers.NamespaceSupport#declarePrefix
598 */
599 void declarePrefix (String prefix, String uri)
600 {
601
602 if (!declsOK)
603 throw new IllegalStateException (
604 "can't declare any more prefixes in this context");
605 if (!declSeen) {
606 copyTables();
607 }
608 if (declarations == null) {
609 declarations = new Vector();
610 }
611
612 prefix = prefix.intern();
613 uri = uri.intern();
614 if ("".equals(prefix)) {
615 if ("".equals(uri)) {
616 defaultNS = null;
617 } else {
618 defaultNS = uri;
619 }
620 } else {
621 prefixTable.put(prefix, uri);
622 uriTable.put(uri, prefix);
623 }
624 declarations.addElement(prefix);
625 }
626
627
628 /***
629 * Process an XML qualified name in this context.
630 *
631 * @param qName The XML qualified name.
632 * @param isAttribute true if this is an attribute name.
633 * @return An array of three strings containing the
634 * URI part (or empty string), the local part,
635 * and the raw name, all internalized, or null
636 * if there is an undeclared prefix.
637 * @see org.xml.sax.helpers.NamespaceSupport#processName
638 */
639 String [] processName (String qName, boolean isAttribute)
640 {
641 String name[];
642 Hashtable table;
643
644
645 declsOK = false;
646
647
648 if (isAttribute) {
649 table = attributeNameTable;
650 } else {
651 table = elementNameTable;
652 }
653
654
655
656
657 name = (String[])table.get(qName);
658 if (name != null) {
659 return name;
660 }
661
662
663
664
665
666 name = new String[3];
667 name[2] = qName.intern();
668 int index = qName.indexOf(':');
669
670
671
672 if (index == -1) {
673 if (isAttribute) {
674 if (qName == "xmlns" && namespaceDeclUris)
675 name[0] = NSDECL;
676 else
677 name[0] = "";
678 } else if (defaultNS == null) {
679 name[0] = "";
680 } else {
681 name[0] = defaultNS;
682 }
683 name[1] = name[2];
684 }
685
686
687 else {
688 String prefix = qName.substring(0, index);
689 String local = qName.substring(index+1);
690 String uri;
691 if ("".equals(prefix)) {
692 uri = defaultNS;
693 } else {
694 uri = (String)prefixTable.get(prefix);
695 }
696 if (uri == null
697 || (!isAttribute && "xmlns".equals (prefix))) {
698 return null;
699 }
700 name[0] = uri;
701 name[1] = local.intern();
702 }
703
704
705
706 table.put(name[2], name);
707 return name;
708 }
709
710
711 /***
712 * Look up the URI associated with a prefix in this context.
713 *
714 * @param prefix The prefix to look up.
715 * @return The associated Namespace URI, or null if none is
716 * declared.
717 * @see org.xml.sax.helpers.NamespaceSupport#getURI
718 */
719 String getURI (String prefix)
720 {
721 if ("".equals(prefix)) {
722 return defaultNS;
723 } else if (prefixTable == null) {
724 return null;
725 } else {
726 return (String)prefixTable.get(prefix);
727 }
728 }
729
730
731 /***
732 * Look up one of the prefixes associated with a URI in this context.
733 *
734 * <p>Since many prefixes may be mapped to the same URI,
735 * the return value may be unreliable.</p>
736 *
737 * @param uri The URI to look up.
738 * @return The associated prefix, or null if none is declared.
739 * @see org.xml.sax.helpers.NamespaceSupport#getPrefix
740 */
741 String getPrefix (String uri)
742 {
743 if (uriTable == null) {
744 return null;
745 } else {
746 return (String)uriTable.get(uri);
747 }
748 }
749
750
751 /***
752 * Return an enumeration of prefixes declared in this context.
753 *
754 * @return An enumeration of prefixes (possibly empty).
755 * @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes
756 */
757 Enumeration getDeclaredPrefixes ()
758 {
759 if (declarations == null) {
760 return EMPTY_ENUMERATION;
761 } else {
762 return declarations.elements();
763 }
764 }
765
766
767 /***
768 * Return an enumeration of all prefixes currently in force.
769 *
770 * <p>The default prefix, if in force, is <em>not</em>
771 * returned, and will have to be checked for separately.</p>
772 *
773 * @return An enumeration of prefixes (never empty).
774 * @see org.xml.sax.helpers.NamespaceSupport#getPrefixes
775 */
776 Enumeration getPrefixes ()
777 {
778 if (prefixTable == null) {
779 return EMPTY_ENUMERATION;
780 } else {
781 return prefixTable.keys();
782 }
783 }
784
785
786
787
788
789
790
791
792 /***
793 * Copy on write for the internal tables in this context.
794 *
795 * <p>This class is optimized for the normal case where most
796 * elements do not contain Namespace declarations.</p>
797 */
798 private void copyTables ()
799 {
800 if (prefixTable != null) {
801 prefixTable = (Hashtable)prefixTable.clone();
802 } else {
803 prefixTable = new Hashtable();
804 }
805 if (uriTable != null) {
806 uriTable = (Hashtable)uriTable.clone();
807 } else {
808 uriTable = new Hashtable();
809 }
810 elementNameTable = new Hashtable();
811 attributeNameTable = new Hashtable();
812 declSeen = true;
813 }
814
815
816
817
818
819
820
821 Hashtable prefixTable;
822 Hashtable uriTable;
823 Hashtable elementNameTable;
824 Hashtable attributeNameTable;
825 String defaultNS = null;
826 boolean declsOK = true;
827
828
829
830
831
832
833
834 private Vector declarations = null;
835 private boolean declSeen = false;
836 private Context parent = null;
837 }
838 }
839
840