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! 5 6 // $Id: NamespaceSupport.java 119 2004-10-05 20:38:42Z oyvind $ 7 8 package org.xml.sax.helpers; 9 10 import java.util.EmptyStackException; 11 import java.util.Enumeration; 12 import java.util.Hashtable; 13 import java.util.Vector; 14 15 16 /** 17 * Encapsulate Namespace logic for use by applications using SAX, 18 * or internally by SAX drivers. 19 * 20 * <blockquote> 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. 25 * </blockquote> 26 * 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> 32 * 33 * <p>Namespace support objects are reusable, but the reset method 34 * must be invoked between each session.</p> 35 * 36 * <p>Here is a simple session:</p> 37 * 38 * <pre> 39 * String parts[] = new String[3]; 40 * NamespaceSupport support = new NamespaceSupport(); 41 * 42 * support.pushContext(); 43 * support.declarePrefix("", "http://www.w3.org/1999/xhtml"); 44 * support.declarePrefix("dc", "http://www.purl.org/dc#"); 45 * 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]); 50 * 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]); 55 * 56 * support.popContext(); 57 * </pre> 58 * 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> 63 * 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. 68 * 69 * @since SAX 2.0 70 * @author David Megginson 71 * @version 2.0.1 (sax2r2) 72 */ 73 public class NamespaceSupport 74 { 75 76 77 //////////////////////////////////////////////////////////////////// 78 // Constants. 79 //////////////////////////////////////////////////////////////////// 80 81 82 /** 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. 86 * 87 * <p>This is the Namespace URI that is automatically mapped 88 * to the "xml" prefix.</p> 89 */ 90 public final static String XMLNS = 91 "http://www.w3.org/XML/1998/namespace"; 92 93 94 /** 95 * An empty enumeration. 96 */ 97 private final static Enumeration EMPTY_ENUMERATION = 98 new Vector().elements(); 99 100 101 //////////////////////////////////////////////////////////////////// 102 // Constructor. 103 //////////////////////////////////////////////////////////////////// 104 105 106 /** 107 * Create a new Namespace support object. 108 */ NamespaceSupport()109 public NamespaceSupport () 110 { 111 reset(); 112 } 113 114 115 116 //////////////////////////////////////////////////////////////////// 117 // Context management. 118 //////////////////////////////////////////////////////////////////// 119 120 121 /** 122 * Reset this Namespace support object for reuse. 123 * 124 * <p>It is necessary to invoke this method before reusing the 125 * Namespace support object for a new session.</p> 126 */ reset()127 public void reset () 128 { 129 contexts = new Context[32]; 130 contextPos = 0; 131 contexts[contextPos] = currentContext = new Context(); 132 currentContext.declarePrefix("xml", XMLNS); 133 } 134 135 136 /** 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. 141 * 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. 154 * 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. 164 * 165 * <p>The Namespace support object always starts with a base context 166 * already in force: in this context, only the "xml" prefix is 167 * declared.</p> 168 * 169 * @see org.xml.sax.ContentHandler 170 * @see #popContext 171 */ pushContext()172 public void pushContext () 173 { 174 int max = contexts.length; 175 176 contexts [contextPos].declsOK = false; 177 contextPos++; 178 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); 183 max *= 2; 184 contexts = newContexts; 185 } 186 187 // Allocate the context if necessary. 188 currentContext = contexts[contextPos]; 189 if (currentContext == null) { 190 contexts[contextPos] = currentContext = new Context(); 191 } 192 193 // Set the parent, if any. 194 if (contextPos > 0) { 195 currentContext.setParent(contexts[contextPos - 1]); 196 } 197 } 198 199 200 /** 201 * Revert to the previous Namespace context. 202 * 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> 206 * 207 * <p>You must not attempt to declare additional Namespace 208 * prefixes after popping a context, unless you push another 209 * context first.</p> 210 * 211 * @see #pushContext 212 */ popContext()213 public void popContext () 214 { 215 contexts[contextPos].clear(); 216 contextPos--; 217 if (contextPos < 0) { 218 throw new EmptyStackException(); 219 } 220 currentContext = contexts[contextPos]; 221 } 222 223 224 225 //////////////////////////////////////////////////////////////////// 226 // Operations within a context. 227 //////////////////////////////////////////////////////////////////// 228 229 230 /** 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. 237 * 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> 241 * 242 * <p>To declare the default element Namespace, use the empty string as 243 * the prefix.</p> 244 * 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> 249 * 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> 257 * 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. 266 * 267 * @see #processName 268 * @see #getURI 269 * @see #getPrefix 270 */ declarePrefix(String prefix, String uri)271 public boolean declarePrefix (String prefix, String uri) 272 { 273 if (prefix.equals("xml") || prefix.equals("xmlns")) { 274 return false; 275 } else { 276 currentContext.declarePrefix(prefix, uri); 277 return true; 278 } 279 } 280 281 282 /** 283 * Process a raw XML 1.0 name, after all declarations in the current 284 * context have been handled by {@link #declarePrefix declarePrefix()}. 285 * 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> 290 * 291 * <dl> 292 * <dt>parts[0]</dt> 293 * <dd>The Namespace URI, or an empty string if none is 294 * in use.</dd> 295 * <dt>parts[1]</dt> 296 * <dd>The local name (without prefix).</dd> 297 * <dt>parts[2]</dt> 298 * <dd>The original raw name.</dd> 299 * </dl> 300 * 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> 304 * 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 308 * will not.</p> 309 * 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 */ processName(String qName, String parts[], boolean isAttribute)321 public String [] processName (String qName, String parts[], 322 boolean isAttribute) 323 { 324 String myParts[] = currentContext.processName(qName, isAttribute); 325 if (myParts == null) { 326 return null; 327 } else { 328 parts[0] = myParts[0]; 329 parts[1] = myParts[1]; 330 parts[2] = myParts[2]; 331 return parts; 332 } 333 } 334 335 336 /** 337 * Look up a prefix and get the currently-mapped Namespace URI. 338 * 339 * <p>This method looks up the prefix in the current context. 340 * Use the empty string ("") for the default Namespace.</p> 341 * 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. 345 * @see #getPrefix 346 * @see #getPrefixes 347 */ getURI(String prefix)348 public String getURI (String prefix) 349 { 350 return currentContext.getURI(prefix); 351 } 352 353 354 /** 355 * Return an enumeration of all prefixes currently declared. 356 * 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> 360 * 361 * @return An enumeration of all prefixes declared in the 362 * current context except for the empty (default) 363 * prefix. 364 * @see #getDeclaredPrefixes 365 * @see #getURI 366 */ getPrefixes()367 public Enumeration getPrefixes () 368 { 369 return currentContext.getPrefixes(); 370 } 371 372 373 /** 374 * Return one of the prefixes mapped to a Namespace URI. 375 * 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> 380 * 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> 384 * 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) 392 * @see #getURI 393 */ getPrefix(String uri)394 public String getPrefix (String uri) 395 { 396 return currentContext.getPrefix(uri); 397 } 398 399 400 /** 401 * Return an enumeration of all prefixes currently declared for a URI. 402 * 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> 408 * 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> 413 * 414 * @param uri The Namespace URI. 415 * @return An enumeration of all prefixes declared in the 416 * current context. 417 * @see #getPrefix 418 * @see #getDeclaredPrefixes 419 * @see #getURI 420 */ getPrefixes(String uri)421 public Enumeration getPrefixes (String uri) 422 { 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); 429 } 430 } 431 return prefixes.elements(); 432 } 433 434 435 /** 436 * Return an enumeration of all prefixes declared in this context. 437 * 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> 441 * 442 * @return An enumeration of all prefixes declared in this 443 * context. 444 * @see #getPrefixes 445 * @see #getURI 446 */ getDeclaredPrefixes()447 public Enumeration getDeclaredPrefixes () 448 { 449 return currentContext.getDeclaredPrefixes(); 450 } 451 452 453 454 //////////////////////////////////////////////////////////////////// 455 // Internal state. 456 //////////////////////////////////////////////////////////////////// 457 458 private Context contexts[]; 459 private Context currentContext; 460 private int contextPos; 461 462 463 464 //////////////////////////////////////////////////////////////////// 465 // Internal classes. 466 //////////////////////////////////////////////////////////////////// 467 468 /** 469 * Internal class for a single Namespace context. 470 * 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. 478 * </p> 479 */ 480 final class Context { 481 482 /** 483 * Create the root-level Namespace context. 484 */ Context()485 Context () 486 { 487 copyTables(); 488 } 489 490 491 /** 492 * (Re)set the parent of this Namespace context. 493 * The context must either have been freshly constructed, 494 * or must have been cleared. 495 * 496 * @param context The parent Namespace context object. 497 */ setParent(Context parent)498 void setParent (Context parent) 499 { 500 this.parent = parent; 501 declarations = null; 502 prefixTable = parent.prefixTable; 503 uriTable = parent.uriTable; 504 elementNameTable = parent.elementNameTable; 505 attributeNameTable = parent.attributeNameTable; 506 defaultNS = parent.defaultNS; 507 declSeen = false; 508 declsOK = true; 509 } 510 511 /** 512 * Makes associated state become collectible, 513 * invalidating this context. 514 * {@link #setParent} must be called before 515 * this context may be used again. 516 */ clear()517 void clear () 518 { 519 parent = null; 520 prefixTable = null; 521 uriTable = null; 522 elementNameTable = null; 523 attributeNameTable = null; 524 defaultNS = null; 525 } 526 527 528 /** 529 * Declare a Namespace prefix for this context. 530 * 531 * @param prefix The prefix to declare. 532 * @param uri The associated Namespace URI. 533 * @see org.xml.sax.helpers.NamespaceSupport#declarePrefix 534 */ declarePrefix(String prefix, String uri)535 void declarePrefix (String prefix, String uri) 536 { 537 // Lazy processing... 538 if (!declsOK) 539 throw new IllegalStateException ( 540 "can't declare any more prefixes in this context"); 541 if (!declSeen) { 542 copyTables(); 543 } 544 if (declarations == null) { 545 declarations = new Vector(); 546 } 547 548 prefix = prefix.intern(); 549 uri = uri.intern(); 550 if ("".equals(prefix)) { 551 if ("".equals(uri)) { 552 defaultNS = null; 553 } else { 554 defaultNS = uri; 555 } 556 } else { 557 prefixTable.put(prefix, uri); 558 uriTable.put(uri, prefix); // may wipe out another prefix 559 } 560 declarations.addElement(prefix); 561 } 562 563 564 /** 565 * Process a raw XML 1.0 name in this context. 566 * 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 574 */ processName(String qName, boolean isAttribute)575 String [] processName (String qName, boolean isAttribute) 576 { 577 String name[]; 578 Hashtable table; 579 580 // detect errors in call sequence 581 declsOK = false; 582 583 // Select the appropriate table. 584 if (isAttribute) { 585 table = attributeNameTable; 586 } else { 587 table = elementNameTable; 588 } 589 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); 594 if (name != null) { 595 return name; 596 } 597 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(':'); 605 606 607 // No prefix. 608 if (index == -1) { 609 if (isAttribute || defaultNS == null) { 610 name[0] = ""; 611 } else { 612 name[0] = defaultNS; 613 } 614 name[1] = name[2]; 615 } 616 617 // Prefix 618 else { 619 String prefix = qName.substring(0, index); 620 String local = qName.substring(index+1); 621 String uri; 622 if ("".equals(prefix)) { 623 uri = defaultNS; 624 } else { 625 uri = (String)prefixTable.get(prefix); 626 } 627 if (uri == null) { 628 return null; 629 } 630 name[0] = uri; 631 name[1] = local.intern(); 632 } 633 634 // Save in the cache for future use. 635 // (Could be shared with parent context...) 636 table.put(name[2], name); 637 return name; 638 } 639 640 641 /** 642 * Look up the URI associated with a prefix in this context. 643 * 644 * @param prefix The prefix to look up. 645 * @return The associated Namespace URI, or null if none is 646 * declared. 647 * @see org.xml.sax.helpers.NamespaceSupport#getURI 648 */ getURI(String prefix)649 String getURI (String prefix) 650 { 651 if ("".equals(prefix)) { 652 return defaultNS; 653 } else if (prefixTable == null) { 654 return null; 655 } else { 656 return (String)prefixTable.get(prefix); 657 } 658 } 659 660 661 /** 662 * Look up one of the prefixes associated with a URI in this context. 663 * 664 * <p>Since many prefixes may be mapped to the same URI, 665 * the return value may be unreliable.</p> 666 * 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 670 */ getPrefix(String uri)671 String getPrefix (String uri) 672 { 673 if (uriTable == null) { 674 return null; 675 } else { 676 return (String)uriTable.get(uri); 677 } 678 } 679 680 681 /** 682 * Return an enumeration of prefixes declared in this context. 683 * 684 * @return An enumeration of prefixes (possibly empty). 685 * @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes 686 */ getDeclaredPrefixes()687 Enumeration getDeclaredPrefixes () 688 { 689 if (declarations == null) { 690 return EMPTY_ENUMERATION; 691 } else { 692 return declarations.elements(); 693 } 694 } 695 696 697 /** 698 * Return an enumeration of all prefixes currently in force. 699 * 700 * <p>The default prefix, if in force, is <em>not</em> 701 * returned, and will have to be checked for separately.</p> 702 * 703 * @return An enumeration of prefixes (never empty). 704 * @see org.xml.sax.helpers.NamespaceSupport#getPrefixes 705 */ getPrefixes()706 Enumeration getPrefixes () 707 { 708 if (prefixTable == null) { 709 return EMPTY_ENUMERATION; 710 } else { 711 return prefixTable.keys(); 712 } 713 } 714 715 716 717 //////////////////////////////////////////////////////////////// 718 // Internal methods. 719 //////////////////////////////////////////////////////////////// 720 721 722 /** 723 * Copy on write for the internal tables in this context. 724 * 725 * <p>This class is optimized for the normal case where most 726 * elements do not contain Namespace declarations.</p> 727 */ copyTables()728 private void copyTables () 729 { 730 if (prefixTable != null) { 731 prefixTable = (Hashtable)prefixTable.clone(); 732 } else { 733 prefixTable = new Hashtable(); 734 } 735 if (uriTable != null) { 736 uriTable = (Hashtable)uriTable.clone(); 737 } else { 738 uriTable = new Hashtable(); 739 } 740 elementNameTable = new Hashtable(); 741 attributeNameTable = new Hashtable(); 742 declSeen = true; 743 } 744 745 746 747 //////////////////////////////////////////////////////////////// 748 // Protected state. 749 //////////////////////////////////////////////////////////////// 750 751 Hashtable prefixTable; 752 Hashtable uriTable; 753 Hashtable elementNameTable; 754 Hashtable attributeNameTable; 755 String defaultNS = null; 756 boolean declsOK = true; 757 758 759 760 //////////////////////////////////////////////////////////////// 761 // Internal state. 762 //////////////////////////////////////////////////////////////// 763 764 private Vector declarations = null; 765 private boolean declSeen = false; 766 private Context parent = null; 767 } 768 } 769 770 // end of NamespaceSupport.java 771