1. // NamespaceSupport.java - generic Namespace support for SAX.
  2. // Written by David Megginson, sax@megginson.com
  3. // This class is in the Public Domain. NO WARRANTY!
  4. // $Id: NamespaceSupport.java,v 1.1 2001/05/20 03:12:58 curcuru Exp $
  5. package org.xml.sax.helpers;
  6. import java.util.EmptyStackException;
  7. import java.util.Enumeration;
  8. import java.util.Hashtable;
  9. import java.util.Vector;
  10. /**
  11. * Encapsulate Namespace logic for use by SAX drivers.
  12. *
  13. * <blockquote>
  14. * <em>This module, both source code and documentation, is in the
  15. * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
  16. * </blockquote>
  17. *
  18. * <p>This class encapsulates the logic of Namespace processing:
  19. * it tracks the declarations currently in force for each context
  20. * and automatically processes qualified XML 1.0 names into their
  21. * Namespace parts; it can also be used in reverse for generating
  22. * XML 1.0 from Namespaces.</p>
  23. *
  24. * <p>Namespace support objects are reusable, but the reset method
  25. * must be invoked between each session.</p>
  26. *
  27. * <p>Here is a simple session:</p>
  28. *
  29. * <pre>
  30. * String parts[] = new String[3];
  31. * NamespaceSupport support = new NamespaceSupport();
  32. *
  33. * support.pushContext();
  34. * support.declarePrefix("", "http://www.w3.org/1999/xhtml");
  35. * support.declarePrefix("dc", "http://www.purl.org/dc#");
  36. *
  37. * String parts[] = support.processName("p", parts, false);
  38. * System.out.println("Namespace URI: " + parts[0]);
  39. * System.out.println("Local name: " + parts[1]);
  40. * System.out.println("Raw name: " + parts[2]);
  41. * String parts[] = support.processName("dc:title", parts, false);
  42. * System.out.println("Namespace URI: " + parts[0]);
  43. * System.out.println("Local name: " + parts[1]);
  44. * System.out.println("Raw name: " + parts[2]);
  45. * support.popContext();
  46. * </pre>
  47. *
  48. * <p>Note that this class is optimized for the use case where most
  49. * elements do not contain Namespace declarations: if the same
  50. * prefix/URI mapping is repeated for each context (for example), this
  51. * class will be somewhat less efficient.</p>
  52. *
  53. * @since SAX 2.0
  54. * @author David Megginson,
  55. * <a href="mailto:sax@megginson.com">sax@megginson.com</a>
  56. * @version 2.0r2pre
  57. */
  58. public class NamespaceSupport
  59. {
  60. ////////////////////////////////////////////////////////////////////
  61. // Constants.
  62. ////////////////////////////////////////////////////////////////////
  63. /**
  64. * The XML Namespace as a constant.
  65. *
  66. * <p>This is the Namespace URI that is automatically mapped
  67. * to the "xml" prefix.</p>
  68. */
  69. public final static String XMLNS =
  70. "http://www.w3.org/XML/1998/namespace";
  71. /**
  72. * An empty enumeration.
  73. */
  74. private final static Enumeration EMPTY_ENUMERATION =
  75. new Vector().elements();
  76. ////////////////////////////////////////////////////////////////////
  77. // Constructor.
  78. ////////////////////////////////////////////////////////////////////
  79. /**
  80. * Create a new Namespace support object.
  81. */
  82. public NamespaceSupport ()
  83. {
  84. reset();
  85. }
  86. ////////////////////////////////////////////////////////////////////
  87. // Context management.
  88. ////////////////////////////////////////////////////////////////////
  89. /**
  90. * Reset this Namespace support object for reuse.
  91. *
  92. * <p>It is necessary to invoke this method before reusing the
  93. * Namespace support object for a new session.</p>
  94. */
  95. public void reset ()
  96. {
  97. contexts = new Context[32];
  98. contextPos = 0;
  99. contexts[contextPos] = currentContext = new Context();
  100. currentContext.declarePrefix("xml", XMLNS);
  101. }
  102. /**
  103. * Start a new Namespace context.
  104. *
  105. * <p>Normally, you should push a new context at the beginning
  106. * of each XML element: the new context will automatically inherit
  107. * the declarations of its parent context, but it will also keep
  108. * track of which declarations were made within this context.</p>
  109. *
  110. * <p>The Namespace support object always starts with a base context
  111. * already in force: in this context, only the "xml" prefix is
  112. * declared.</p>
  113. *
  114. * @see #popContext
  115. */
  116. public void pushContext ()
  117. {
  118. int max = contexts.length;
  119. contextPos++;
  120. // Extend the array if necessary
  121. if (contextPos >= max) {
  122. Context newContexts[] = new Context[max*2];
  123. System.arraycopy(contexts, 0, newContexts, 0, max);
  124. max *= 2;
  125. contexts = newContexts;
  126. }
  127. // Allocate the context if necessary.
  128. currentContext = contexts[contextPos];
  129. if (currentContext == null) {
  130. contexts[contextPos] = currentContext = new Context();
  131. }
  132. // Set the parent, if any.
  133. if (contextPos > 0) {
  134. currentContext.setParent(contexts[contextPos - 1]);
  135. }
  136. }
  137. /**
  138. * Revert to the previous Namespace context.
  139. *
  140. * <p>Normally, you should pop the context at the end of each
  141. * XML element. After popping the context, all Namespace prefix
  142. * mappings that were previously in force are restored.</p>
  143. *
  144. * <p>You must not attempt to declare additional Namespace
  145. * prefixes after popping a context, unless you push another
  146. * context first.</p>
  147. *
  148. * @see #pushContext
  149. */
  150. public void popContext ()
  151. {
  152. contextPos--;
  153. if (contextPos < 0) {
  154. throw new EmptyStackException();
  155. }
  156. currentContext = contexts[contextPos];
  157. }
  158. ////////////////////////////////////////////////////////////////////
  159. // Operations within a context.
  160. ////////////////////////////////////////////////////////////////////
  161. /**
  162. * Declare a Namespace prefix.
  163. *
  164. * <p>This method declares a prefix in the current Namespace
  165. * context; the prefix will remain in force until this context
  166. * is popped, unless it is shadowed in a descendant context.</p>
  167. *
  168. * <p>To declare a default Namespace, use the empty string. The
  169. * prefix must not be "xml" or "xmlns".</p>
  170. *
  171. * <p>Note that you must <em>not</em> declare a prefix after
  172. * you've pushed and popped another Namespace.</p>
  173. *
  174. * <p>Note that there is an asymmetry in this library: while {@link
  175. * #getPrefix getPrefix} will not return the default "" prefix,
  176. * even if you have declared one; to check for a default prefix,
  177. * you have to look it up explicitly using {@link #getURI getURI}.
  178. * This asymmetry exists to make it easier to look up prefixes
  179. * for attribute names, where the default prefix is not allowed.</p>
  180. *
  181. * @param prefix The prefix to declare, or null for the empty
  182. * string.
  183. * @param uri The Namespace URI to associate with the prefix.
  184. * @return true if the prefix was legal, false otherwise
  185. * @see #processName
  186. * @see #getURI
  187. * @see #getPrefix
  188. */
  189. public boolean declarePrefix (String prefix, String uri)
  190. {
  191. if (prefix.equals("xml") || prefix.equals("xmlns")) {
  192. return false;
  193. } else {
  194. currentContext.declarePrefix(prefix, uri);
  195. return true;
  196. }
  197. }
  198. /**
  199. * Process a raw XML 1.0 name.
  200. *
  201. * <p>This method processes a raw XML 1.0 name in the current
  202. * context by removing the prefix and looking it up among the
  203. * prefixes currently declared. The return value will be the
  204. * array supplied by the caller, filled in as follows:</p>
  205. *
  206. * <dl>
  207. * <dt>parts[0]</dt>
  208. * <dd>The Namespace URI, or an empty string if none is
  209. * in use.</dd>
  210. * <dt>parts[1]</dt>
  211. * <dd>The local name (without prefix).</dd>
  212. * <dt>parts[2]</dt>
  213. * <dd>The original raw name.</dd>
  214. * </dl>
  215. *
  216. * <p>All of the strings in the array will be internalized. If
  217. * the raw name has a prefix that has not been declared, then
  218. * the return value will be null.</p>
  219. *
  220. * <p>Note that attribute names are processed differently than
  221. * element names: an unprefixed element name will received the
  222. * default Namespace (if any), while an unprefixed element name
  223. * will not.</p>
  224. *
  225. * @param qName The raw XML 1.0 name to be processed.
  226. * @param parts An array supplied by the caller, capable of
  227. * holding at least three members.
  228. * @param isAttribute A flag indicating whether this is an
  229. * attribute name (true) or an element name (false).
  230. * @return The supplied array holding three internalized strings
  231. * representing the Namespace URI (or empty string), the
  232. * local name, and the raw XML 1.0 name; or null if there
  233. * is an undeclared prefix.
  234. * @see #declarePrefix
  235. * @see java.lang.String#intern */
  236. public String [] processName (String qName, String parts[],
  237. boolean isAttribute)
  238. {
  239. String myParts[] = currentContext.processName(qName, isAttribute);
  240. if (myParts == null) {
  241. return null;
  242. } else {
  243. parts[0] = myParts[0];
  244. parts[1] = myParts[1];
  245. parts[2] = myParts[2];
  246. return parts;
  247. }
  248. }
  249. /**
  250. * Look up a prefix and get the currently-mapped Namespace URI.
  251. *
  252. * <p>This method looks up the prefix in the current context.
  253. * Use the empty string ("") for the default Namespace.</p>
  254. *
  255. * @param prefix The prefix to look up.
  256. * @return The associated Namespace URI, or null if the prefix
  257. * is undeclared in this context.
  258. * @see #getPrefix
  259. * @see #getPrefixes
  260. */
  261. public String getURI (String prefix)
  262. {
  263. return currentContext.getURI(prefix);
  264. }
  265. /**
  266. * Return an enumeration of all prefixes currently declared.
  267. *
  268. * <p><strong>Note:</strong> if there is a default prefix, it will not be
  269. * returned in this enumeration; check for the default prefix
  270. * using the {@link #getURI getURI} with an argument of "".</p>
  271. *
  272. * @return An enumeration of all prefixes declared in the
  273. * current context except for the empty (default)
  274. * prefix.
  275. * @see #getDeclaredPrefixes
  276. * @see #getURI
  277. */
  278. public Enumeration getPrefixes ()
  279. {
  280. return currentContext.getPrefixes();
  281. }
  282. /**
  283. * Return one of the prefixes mapped to a Namespace URI.
  284. *
  285. * <p>If more than one prefix is currently mapped to the same
  286. * URI, this method will make an arbitrary selection; if you
  287. * want all of the prefixes, use the {@link #getPrefixes}
  288. * method instead.</p>
  289. *
  290. * <p><strong>Note:</strong> this will never return the empty (default) prefix;
  291. * to check for a default prefix, use the {@link #getURI getURI}
  292. * method with an argument of "".</p>
  293. *
  294. * @param uri The Namespace URI.
  295. * @param isAttribute true if this prefix is for an attribute
  296. * (and the default Namespace is not allowed).
  297. * @return One of the prefixes currently mapped to the URI supplied,
  298. * or null if none is mapped or if the URI is assigned to
  299. * the default Namespace.
  300. * @see #getPrefixes(java.lang.String)
  301. * @see #getURI
  302. */
  303. public String getPrefix (String uri)
  304. {
  305. return currentContext.getPrefix(uri);
  306. }
  307. /**
  308. * Return an enumeration of all prefixes currently declared for a URI.
  309. *
  310. * <p>This method returns prefixes mapped to a specific Namespace
  311. * URI. The xml: prefix will be included. If you want only one
  312. * prefix that's mapped to the Namespace URI, and you don't care
  313. * which one you get, use the {@link #getPrefix getPrefix}
  314. * method instead.</p>
  315. *
  316. * <p><strong>Note:</strong> the empty (default) prefix is <em>never</em> included
  317. * in this enumeration; to check for the presence of a default
  318. * Namespace, use the {@link #getURI getURI} method with an
  319. * argument of "".</p>
  320. *
  321. * @param uri The Namespace URI.
  322. * @return An enumeration of all prefixes declared in the
  323. * current context.
  324. * @see #getPrefix
  325. * @see #getDeclaredPrefixes
  326. * @see #getURI
  327. */
  328. public Enumeration getPrefixes (String uri)
  329. {
  330. Vector prefixes = new Vector();
  331. Enumeration allPrefixes = getPrefixes();
  332. while (allPrefixes.hasMoreElements()) {
  333. String prefix = (String)allPrefixes.nextElement();
  334. if (uri.equals(getURI(prefix))) {
  335. prefixes.addElement(prefix);
  336. }
  337. }
  338. return prefixes.elements();
  339. }
  340. /**
  341. * Return an enumeration of all prefixes declared in this context.
  342. *
  343. * <p>The empty (default) prefix will be included in this
  344. * enumeration; note that this behaviour differs from that of
  345. * {@link #getPrefix} and {@link #getPrefixes}.</p>
  346. *
  347. * @return An enumeration of all prefixes declared in this
  348. * context.
  349. * @see #getPrefixes
  350. * @see #getURI
  351. */
  352. public Enumeration getDeclaredPrefixes ()
  353. {
  354. return currentContext.getDeclaredPrefixes();
  355. }
  356. ////////////////////////////////////////////////////////////////////
  357. // Internal state.
  358. ////////////////////////////////////////////////////////////////////
  359. private Context contexts[];
  360. private Context currentContext;
  361. private int contextPos;
  362. ////////////////////////////////////////////////////////////////////
  363. // Internal classes.
  364. ////////////////////////////////////////////////////////////////////
  365. /**
  366. * Internal class for a single Namespace context.
  367. *
  368. * <p>This module caches and reuses Namespace contexts, so the number allocated
  369. * will be equal to the element depth of the document, not to the total
  370. * number of elements (i.e. 5-10 rather than tens of thousands).</p>
  371. */
  372. final class Context {
  373. /**
  374. * Create the root-level Namespace context.
  375. */
  376. Context ()
  377. {
  378. copyTables();
  379. }
  380. /**
  381. * (Re)set the parent of this Namespace context.
  382. *
  383. * @param context The parent Namespace context object.
  384. */
  385. void setParent (Context parent)
  386. {
  387. this.parent = parent;
  388. declarations = null;
  389. prefixTable = parent.prefixTable;
  390. uriTable = parent.uriTable;
  391. elementNameTable = parent.elementNameTable;
  392. attributeNameTable = parent.attributeNameTable;
  393. defaultNS = parent.defaultNS;
  394. tablesDirty = false;
  395. }
  396. /**
  397. * Declare a Namespace prefix for this context.
  398. *
  399. * @param prefix The prefix to declare.
  400. * @param uri The associated Namespace URI.
  401. * @see org.xml.sax.helpers.NamespaceSupport#declarePrefix
  402. */
  403. void declarePrefix (String prefix, String uri)
  404. {
  405. // Lazy processing...
  406. if (!tablesDirty) {
  407. copyTables();
  408. }
  409. if (declarations == null) {
  410. declarations = new Vector();
  411. }
  412. prefix = prefix.intern();
  413. uri = uri.intern();
  414. if ("".equals(prefix)) {
  415. if ("".equals(uri)) {
  416. defaultNS = null;
  417. } else {
  418. defaultNS = uri;
  419. }
  420. } else {
  421. prefixTable.put(prefix, uri);
  422. uriTable.put(uri, prefix); // may wipe out another prefix
  423. }
  424. declarations.addElement(prefix);
  425. }
  426. /**
  427. * Process a raw XML 1.0 name in this context.
  428. *
  429. * @param qName The raw XML 1.0 name.
  430. * @param isAttribute true if this is an attribute name.
  431. * @return An array of three strings containing the
  432. * URI part (or empty string), the local part,
  433. * and the raw name, all internalized, or null
  434. * if there is an undeclared prefix.
  435. * @see org.xml.sax.helpers.NamespaceSupport#processName
  436. */
  437. String [] processName (String qName, boolean isAttribute)
  438. {
  439. String name[];
  440. Hashtable table;
  441. // Select the appropriate table.
  442. if (isAttribute) {
  443. table = elementNameTable;
  444. } else {
  445. table = attributeNameTable;
  446. }
  447. // Start by looking in the cache, and
  448. // return immediately if the name
  449. // is already known in this content
  450. name = (String[])table.get(qName);
  451. if (name != null) {
  452. return name;
  453. }
  454. // We haven't seen this name in this
  455. // context before.
  456. name = new String[3];
  457. int index = qName.indexOf(':');
  458. // No prefix.
  459. if (index == -1) {
  460. if (isAttribute || defaultNS == null) {
  461. name[0] = "";
  462. } else {
  463. name[0] = defaultNS;
  464. }
  465. name[1] = qName.intern();
  466. name[2] = name[1];
  467. }
  468. // Prefix
  469. else {
  470. String prefix = qName.substring(0, index);
  471. String local = qName.substring(index+1);
  472. String uri;
  473. if ("".equals(prefix)) {
  474. uri = defaultNS;
  475. } else {
  476. uri = (String)prefixTable.get(prefix);
  477. }
  478. if (uri == null) {
  479. return null;
  480. }
  481. name[0] = uri;
  482. name[1] = local.intern();
  483. name[2] = qName.intern();
  484. }
  485. // Save in the cache for future use.
  486. table.put(name[2], name);
  487. tablesDirty = true;
  488. return name;
  489. }
  490. /**
  491. * Look up the URI associated with a prefix in this context.
  492. *
  493. * @param prefix The prefix to look up.
  494. * @return The associated Namespace URI, or null if none is
  495. * declared.
  496. * @see org.xml.sax.helpers.NamespaceSupport#getURI
  497. */
  498. String getURI (String prefix)
  499. {
  500. if ("".equals(prefix)) {
  501. return defaultNS;
  502. } else if (prefixTable == null) {
  503. return null;
  504. } else {
  505. return (String)prefixTable.get(prefix);
  506. }
  507. }
  508. /**
  509. * Look up one of the prefixes associated with a URI in this context.
  510. *
  511. * <p>Since many prefixes may be mapped to the same URI,
  512. * the return value may be unreliable.</p>
  513. *
  514. * @param uri The URI to look up.
  515. * @return The associated prefix, or null if none is declared.
  516. * @see org.xml.sax.helpers.NamespaceSupport#getPrefix
  517. */
  518. String getPrefix (String uri)
  519. {
  520. if (uriTable == null) {
  521. return null;
  522. } else {
  523. return (String)uriTable.get(uri);
  524. }
  525. }
  526. /**
  527. * Return an enumeration of prefixes declared in this context.
  528. *
  529. * @return An enumeration of prefixes (possibly empty).
  530. * @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes
  531. */
  532. Enumeration getDeclaredPrefixes ()
  533. {
  534. if (declarations == null) {
  535. return EMPTY_ENUMERATION;
  536. } else {
  537. return declarations.elements();
  538. }
  539. }
  540. /**
  541. * Return an enumeration of all prefixes currently in force.
  542. *
  543. * <p>The default prefix, if in force, is <em>not</em>
  544. * returned, and will have to be checked for separately.</p>
  545. *
  546. * @return An enumeration of prefixes (never empty).
  547. * @see org.xml.sax.helpers.NamespaceSupport#getPrefixes
  548. */
  549. Enumeration getPrefixes ()
  550. {
  551. if (prefixTable == null) {
  552. return EMPTY_ENUMERATION;
  553. } else {
  554. return prefixTable.keys();
  555. }
  556. }
  557. ////////////////////////////////////////////////////////////////
  558. // Internal methods.
  559. ////////////////////////////////////////////////////////////////
  560. /**
  561. * Copy on write for the internal tables in this context.
  562. *
  563. * <p>This class is optimized for the normal case where most
  564. * elements do not contain Namespace declarations.</p>
  565. */
  566. private void copyTables ()
  567. {
  568. if (prefixTable != null) {
  569. prefixTable = (Hashtable)prefixTable.clone();
  570. } else {
  571. prefixTable = new Hashtable();
  572. }
  573. if (uriTable != null) {
  574. uriTable = (Hashtable)uriTable.clone();
  575. } else {
  576. uriTable = new Hashtable();
  577. }
  578. elementNameTable = new Hashtable();
  579. attributeNameTable = new Hashtable();
  580. tablesDirty = true;
  581. }
  582. ////////////////////////////////////////////////////////////////
  583. // Protected state.
  584. ////////////////////////////////////////////////////////////////
  585. Hashtable prefixTable;
  586. Hashtable uriTable;
  587. Hashtable elementNameTable;
  588. Hashtable attributeNameTable;
  589. String defaultNS = null;
  590. ////////////////////////////////////////////////////////////////
  591. // Internal state.
  592. ////////////////////////////////////////////////////////////////
  593. private Vector declarations = null;
  594. private boolean tablesDirty = false;
  595. private Context parent = null;
  596. }
  597. }
  598. // end of NamespaceSupport.java