1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /*
  17. * $Id: NamespaceSupport2.java,v 1.9 2004/02/17 04:21:14 minchau Exp $
  18. */
  19. package com.sun.org.apache.xml.internal.utils;
  20. import java.util.EmptyStackException;
  21. import java.util.Enumeration;
  22. import java.util.Hashtable;
  23. import java.util.Vector;
  24. /**
  25. * Encapsulate Namespace tracking logic for use by SAX drivers.
  26. *
  27. * <p>This class is an attempt to rewrite the SAX NamespaceSupport
  28. * "helper" class for improved efficiency. It can be used to track the
  29. * namespace declarations currently in scope, providing lookup
  30. * routines to map prefixes to URIs and vice versa.</p>
  31. *
  32. * <p>ISSUE: For testing purposes, I've extended NamespaceSupport even
  33. * though I'm completely reasserting all behaviors and fields.
  34. * Wasteful.... But SAX did not put an interface under that object and
  35. * we seem to have written that SAX class into our APIs... and I don't
  36. * want to argue with it right now. </p>
  37. *
  38. * @see org.xml.sax.helpers.NamespaceSupport
  39. * */
  40. public class NamespaceSupport2
  41. extends org.xml.sax.helpers.NamespaceSupport
  42. {
  43. ////////////////////////////////////////////////////////////////////
  44. // Internal state.
  45. ////////////////////////////////////////////////////////////////////
  46. private Context2 currentContext; // Current point on the double-linked stack
  47. ////////////////////////////////////////////////////////////////////
  48. // Constants.
  49. ////////////////////////////////////////////////////////////////////
  50. /**
  51. * The XML Namespace as a constant.
  52. *
  53. * <p>This is the Namespace URI that is automatically mapped
  54. * to the "xml" prefix.</p>
  55. */
  56. public final static String XMLNS =
  57. "http://www.w3.org/XML/1998/namespace";
  58. ////////////////////////////////////////////////////////////////////
  59. // Constructor.
  60. ////////////////////////////////////////////////////////////////////
  61. /**
  62. * Create a new Namespace support object.
  63. */
  64. public NamespaceSupport2 ()
  65. {
  66. reset();
  67. }
  68. ////////////////////////////////////////////////////////////////////
  69. // Context management.
  70. ////////////////////////////////////////////////////////////////////
  71. /**
  72. * Reset this Namespace support object for reuse.
  73. *
  74. * <p>It is necessary to invoke this method before reusing the
  75. * Namespace support object for a new session.</p>
  76. */
  77. public void reset ()
  78. {
  79. // Discarding the whole stack doesn't save us a lot versus
  80. // creating a new NamespaceSupport. Do we care, or should we
  81. // change this to just reset the root context?
  82. currentContext = new Context2(null);
  83. currentContext.declarePrefix("xml", XMLNS);
  84. }
  85. /**
  86. * Start a new Namespace context.
  87. *
  88. * <p>Normally, you should push a new context at the beginning
  89. * of each XML element: the new context will automatically inherit
  90. * the declarations of its parent context, but it will also keep
  91. * track of which declarations were made within this context.</p>
  92. *
  93. * <p>The Namespace support object always starts with a base context
  94. * already in force: in this context, only the "xml" prefix is
  95. * declared.</p>
  96. *
  97. * @see #popContext
  98. */
  99. public void pushContext ()
  100. {
  101. // JJK: Context has a parent pointer.
  102. // That means we don't need a stack to pop.
  103. // We may want to retain for reuse, but that can be done via
  104. // a child pointer.
  105. Context2 parentContext=currentContext;
  106. currentContext = parentContext.getChild();
  107. if (currentContext == null){
  108. currentContext = new Context2(parentContext);
  109. }
  110. else{
  111. // JJK: This will wipe out any leftover data
  112. // if we're reusing a previously allocated Context.
  113. currentContext.setParent(parentContext);
  114. }
  115. }
  116. /**
  117. * Revert to the previous Namespace context.
  118. *
  119. * <p>Normally, you should pop the context at the end of each
  120. * XML element. After popping the context, all Namespace prefix
  121. * mappings that were previously in force are restored.</p>
  122. *
  123. * <p>You must not attempt to declare additional Namespace
  124. * prefixes after popping a context, unless you push another
  125. * context first.</p>
  126. *
  127. * @see #pushContext
  128. */
  129. public void popContext ()
  130. {
  131. Context2 parentContext=currentContext.getParent();
  132. if(parentContext==null)
  133. throw new EmptyStackException();
  134. else
  135. currentContext = parentContext;
  136. }
  137. ////////////////////////////////////////////////////////////////////
  138. // Operations within a context.
  139. ////////////////////////////////////////////////////////////////////
  140. /**
  141. * Declare a Namespace prefix.
  142. *
  143. * <p>This method declares a prefix in the current Namespace
  144. * context; the prefix will remain in force until this context
  145. * is popped, unless it is shadowed in a descendant context.</p>
  146. *
  147. * <p>To declare a default Namespace, use the empty string. The
  148. * prefix must not be "xml" or "xmlns".</p>
  149. *
  150. * <p>Note that you must <em>not</em> declare a prefix after
  151. * you've pushed and popped another Namespace.</p>
  152. *
  153. * <p>Note that there is an asymmetry in this library: while {@link
  154. * #getPrefix getPrefix} will not return the default "" prefix,
  155. * even if you have declared one; to check for a default prefix,
  156. * you have to look it up explicitly using {@link #getURI getURI}.
  157. * This asymmetry exists to make it easier to look up prefixes
  158. * for attribute names, where the default prefix is not allowed.</p>
  159. *
  160. * @param prefix The prefix to declare, or null for the empty
  161. * string.
  162. * @param uri The Namespace URI to associate with the prefix.
  163. * @return true if the prefix was legal, false otherwise
  164. * @see #processName
  165. * @see #getURI
  166. * @see #getPrefix
  167. */
  168. public boolean declarePrefix (String prefix, String uri)
  169. {
  170. if (prefix.equals("xml") || prefix.equals("xmlns")) {
  171. return false;
  172. } else {
  173. currentContext.declarePrefix(prefix, uri);
  174. return true;
  175. }
  176. }
  177. /**
  178. * Process a raw XML 1.0 name.
  179. *
  180. * <p>This method processes a raw XML 1.0 name in the current
  181. * context by removing the prefix and looking it up among the
  182. * prefixes currently declared. The return value will be the
  183. * array supplied by the caller, filled in as follows:</p>
  184. *
  185. * <dl>
  186. * <dt>parts[0]</dt>
  187. * <dd>The Namespace URI, or an empty string if none is
  188. * in use.</dd>
  189. * <dt>parts[1]</dt>
  190. * <dd>The local name (without prefix).</dd>
  191. * <dt>parts[2]</dt>
  192. * <dd>The original raw name.</dd>
  193. * </dl>
  194. *
  195. * <p>All of the strings in the array will be internalized. If
  196. * the raw name has a prefix that has not been declared, then
  197. * the return value will be null.</p>
  198. *
  199. * <p>Note that attribute names are processed differently than
  200. * element names: an unprefixed element name will received the
  201. * default Namespace (if any), while an unprefixed element name
  202. * will not.</p>
  203. *
  204. * @param qName The raw XML 1.0 name to be processed.
  205. * @param parts A string array supplied by the caller, capable of
  206. * holding at least three members.
  207. * @param isAttribute A flag indicating whether this is an
  208. * attribute name (true) or an element name (false).
  209. * @return The supplied array holding three internalized strings
  210. * representing the Namespace URI (or empty string), the
  211. * local name, and the raw XML 1.0 name; or null if there
  212. * is an undeclared prefix.
  213. * @see #declarePrefix
  214. * @see java.lang.String#intern */
  215. public String [] processName (String qName, String[] parts,
  216. boolean isAttribute)
  217. {
  218. String[] name=currentContext.processName(qName, isAttribute);
  219. if(name==null)
  220. return null;
  221. // JJK: This recopying is required because processName may return
  222. // a cached result. I Don't Like It. *****
  223. System.arraycopy(name,0,parts,0,3);
  224. return parts;
  225. }
  226. /**
  227. * Look up a prefix and get the currently-mapped Namespace URI.
  228. *
  229. * <p>This method looks up the prefix in the current context.
  230. * Use the empty string ("") for the default Namespace.</p>
  231. *
  232. * @param prefix The prefix to look up.
  233. * @return The associated Namespace URI, or null if the prefix
  234. * is undeclared in this context.
  235. * @see #getPrefix
  236. * @see #getPrefixes
  237. */
  238. public String getURI (String prefix)
  239. {
  240. return currentContext.getURI(prefix);
  241. }
  242. /**
  243. * Return an enumeration of all prefixes currently declared.
  244. *
  245. * <p><strong>Note:</strong> if there is a default prefix, it will not be
  246. * returned in this enumeration; check for the default prefix
  247. * using the {@link #getURI getURI} with an argument of "".</p>
  248. *
  249. * @return An enumeration of all prefixes declared in the
  250. * current context except for the empty (default)
  251. * prefix.
  252. * @see #getDeclaredPrefixes
  253. * @see #getURI
  254. */
  255. public Enumeration getPrefixes ()
  256. {
  257. return currentContext.getPrefixes();
  258. }
  259. /**
  260. * Return one of the prefixes mapped to a Namespace URI.
  261. *
  262. * <p>If more than one prefix is currently mapped to the same
  263. * URI, this method will make an arbitrary selection; if you
  264. * want all of the prefixes, use the {@link #getPrefixes}
  265. * method instead.</p>
  266. *
  267. * <p><strong>Note:</strong> this will never return the empty
  268. * (default) prefix; to check for a default prefix, use the {@link
  269. * #getURI getURI} method with an argument of "".</p>
  270. *
  271. * @param uri The Namespace URI.
  272. * @return One of the prefixes currently mapped to the URI supplied,
  273. * or null if none is mapped or if the URI is assigned to
  274. * the default Namespace.
  275. * @see #getPrefixes(java.lang.String)
  276. * @see #getURI */
  277. public String getPrefix (String uri)
  278. {
  279. return currentContext.getPrefix(uri);
  280. }
  281. /**
  282. * Return an enumeration of all prefixes currently declared for a URI.
  283. *
  284. * <p>This method returns prefixes mapped to a specific Namespace
  285. * URI. The xml: prefix will be included. If you want only one
  286. * prefix that's mapped to the Namespace URI, and you don't care
  287. * which one you get, use the {@link #getPrefix getPrefix}
  288. * method instead.</p>
  289. *
  290. * <p><strong>Note:</strong> the empty (default) prefix is
  291. * <em>never</em> included in this enumeration; to check for the
  292. * presence of a default Namespace, use the {@link #getURI getURI}
  293. * method with an argument of "".</p>
  294. *
  295. * @param uri The Namespace URI.
  296. * @return An enumeration of all prefixes declared in the
  297. * current context.
  298. * @see #getPrefix
  299. * @see #getDeclaredPrefixes
  300. * @see #getURI */
  301. public Enumeration getPrefixes (String uri)
  302. {
  303. // JJK: The old code involved creating a vector, filling it
  304. // with all the matching prefixes, and then getting its
  305. // elements enumerator. Wastes storage, wastes cycles if we
  306. // don't actually need them all. Better to either implement
  307. // a specific enumerator for these prefixes... or a filter
  308. // around the all-prefixes enumerator, which comes out to
  309. // roughly the same thing.
  310. //
  311. // **** Currently a filter. That may not be most efficient
  312. // when I'm done restructuring storage!
  313. return new PrefixForUriEnumerator(this,uri,getPrefixes());
  314. }
  315. /**
  316. * Return an enumeration of all prefixes declared in this context.
  317. *
  318. * <p>The empty (default) prefix will be included in this
  319. * enumeration; note that this behaviour differs from that of
  320. * {@link #getPrefix} and {@link #getPrefixes}.</p>
  321. *
  322. * @return An enumeration of all prefixes declared in this
  323. * context.
  324. * @see #getPrefixes
  325. * @see #getURI
  326. */
  327. public Enumeration getDeclaredPrefixes ()
  328. {
  329. return currentContext.getDeclaredPrefixes();
  330. }
  331. }
  332. ////////////////////////////////////////////////////////////////////
  333. // Local classes.
  334. // These were _internal_ classes... but in fact they don't have to be,
  335. // and may be more efficient if they aren't.
  336. ////////////////////////////////////////////////////////////////////
  337. /**
  338. * Implementation of Enumeration filter, wrapped
  339. * aroung the get-all-prefixes version of the operation. This is NOT
  340. * necessarily the most efficient approach; finding the URI and then asking
  341. * what prefixes apply to it might make much more sense.
  342. */
  343. class PrefixForUriEnumerator implements Enumeration
  344. {
  345. private Enumeration allPrefixes;
  346. private String uri;
  347. private String lookahead=null;
  348. private NamespaceSupport2 nsup;
  349. // Kluge: Since one can't do a constructor on an
  350. // anonymous class (as far as I know)...
  351. PrefixForUriEnumerator(NamespaceSupport2 nsup,String uri, Enumeration allPrefixes)
  352. {
  353. this.nsup=nsup;
  354. this.uri=uri;
  355. this.allPrefixes=allPrefixes;
  356. }
  357. public boolean hasMoreElements()
  358. {
  359. if(lookahead!=null)
  360. return true;
  361. while(allPrefixes.hasMoreElements())
  362. {
  363. String prefix=(String)allPrefixes.nextElement();
  364. if(uri.equals(nsup.getURI(prefix)))
  365. {
  366. lookahead=prefix;
  367. return true;
  368. }
  369. }
  370. return false;
  371. }
  372. public Object nextElement()
  373. {
  374. if(hasMoreElements())
  375. {
  376. String tmp=lookahead;
  377. lookahead=null;
  378. return tmp;
  379. }
  380. else
  381. throw new java.util.NoSuchElementException();
  382. }
  383. }
  384. /**
  385. * Internal class for a single Namespace context.
  386. *
  387. * <p>This module caches and reuses Namespace contexts, so the number allocated
  388. * will be equal to the element depth of the document, not to the total
  389. * number of elements (i.e. 5-10 rather than tens of thousands).</p>
  390. */
  391. final class Context2 {
  392. ////////////////////////////////////////////////////////////////
  393. // Manefest Constants
  394. ////////////////////////////////////////////////////////////////
  395. /**
  396. * An empty enumeration.
  397. */
  398. private final static Enumeration EMPTY_ENUMERATION =
  399. new Vector().elements();
  400. ////////////////////////////////////////////////////////////////
  401. // Protected state.
  402. ////////////////////////////////////////////////////////////////
  403. Hashtable prefixTable;
  404. Hashtable uriTable;
  405. Hashtable elementNameTable;
  406. Hashtable attributeNameTable;
  407. String defaultNS = null;
  408. ////////////////////////////////////////////////////////////////
  409. // Internal state.
  410. ////////////////////////////////////////////////////////////////
  411. private Vector declarations = null;
  412. private boolean tablesDirty = false;
  413. private Context2 parent = null;
  414. private Context2 child = null;
  415. /**
  416. * Create a new Namespace context.
  417. */
  418. Context2 (Context2 parent)
  419. {
  420. if(parent==null)
  421. {
  422. prefixTable = new Hashtable();
  423. uriTable = new Hashtable();
  424. elementNameTable=null;
  425. attributeNameTable=null;
  426. }
  427. else
  428. setParent(parent);
  429. }
  430. /**
  431. * @returns The child Namespace context object, or null if this
  432. * is the last currently on the chain.
  433. */
  434. Context2 getChild()
  435. {
  436. return child;
  437. }
  438. /**
  439. * @returns The parent Namespace context object, or null if this
  440. * is the root.
  441. */
  442. Context2 getParent()
  443. {
  444. return parent;
  445. }
  446. /**
  447. * (Re)set the parent of this Namespace context.
  448. * This is separate from the c'tor because it's re-applied
  449. * when a Context2 is reused by push-after-pop.
  450. *
  451. * @param context The parent Namespace context object.
  452. */
  453. void setParent (Context2 parent)
  454. {
  455. this.parent = parent;
  456. parent.child = this; // JJK: Doubly-linked
  457. declarations = null;
  458. prefixTable = parent.prefixTable;
  459. uriTable = parent.uriTable;
  460. elementNameTable = parent.elementNameTable;
  461. attributeNameTable = parent.attributeNameTable;
  462. defaultNS = parent.defaultNS;
  463. tablesDirty = false;
  464. }
  465. /**
  466. * Declare a Namespace prefix for this context.
  467. *
  468. * @param prefix The prefix to declare.
  469. * @param uri The associated Namespace URI.
  470. * @see org.xml.sax.helpers.NamespaceSupport2#declarePrefix
  471. */
  472. void declarePrefix (String prefix, String uri)
  473. {
  474. // Lazy processing...
  475. if (!tablesDirty) {
  476. copyTables();
  477. }
  478. if (declarations == null) {
  479. declarations = new Vector();
  480. }
  481. prefix = prefix.intern();
  482. uri = uri.intern();
  483. if ("".equals(prefix)) {
  484. if ("".equals(uri)) {
  485. defaultNS = null;
  486. } else {
  487. defaultNS = uri;
  488. }
  489. } else {
  490. prefixTable.put(prefix, uri);
  491. uriTable.put(uri, prefix); // may wipe out another prefix
  492. }
  493. declarations.addElement(prefix);
  494. }
  495. /**
  496. * Process a raw XML 1.0 name in this context.
  497. *
  498. * @param qName The raw XML 1.0 name.
  499. * @param isAttribute true if this is an attribute name.
  500. * @return An array of three strings containing the
  501. * URI part (or empty string), the local part,
  502. * and the raw name, all internalized, or null
  503. * if there is an undeclared prefix.
  504. * @see org.xml.sax.helpers.NamespaceSupport2#processName
  505. */
  506. String [] processName (String qName, boolean isAttribute)
  507. {
  508. String name[];
  509. Hashtable table;
  510. // Select the appropriate table.
  511. if (isAttribute) {
  512. if(elementNameTable==null)
  513. elementNameTable=new Hashtable();
  514. table = elementNameTable;
  515. } else {
  516. if(attributeNameTable==null)
  517. attributeNameTable=new Hashtable();
  518. table = attributeNameTable;
  519. }
  520. // Start by looking in the cache, and
  521. // return immediately if the name
  522. // is already known in this content
  523. name = (String[])table.get(qName);
  524. if (name != null) {
  525. return name;
  526. }
  527. // We haven't seen this name in this
  528. // context before.
  529. name = new String[3];
  530. int index = qName.indexOf(':');
  531. // No prefix.
  532. if (index == -1) {
  533. if (isAttribute || defaultNS == null) {
  534. name[0] = "";
  535. } else {
  536. name[0] = defaultNS;
  537. }
  538. name[1] = qName.intern();
  539. name[2] = name[1];
  540. }
  541. // Prefix
  542. else {
  543. String prefix = qName.substring(0, index);
  544. String local = qName.substring(index+1);
  545. String uri;
  546. if ("".equals(prefix)) {
  547. uri = defaultNS;
  548. } else {
  549. uri = (String)prefixTable.get(prefix);
  550. }
  551. if (uri == null) {
  552. return null;
  553. }
  554. name[0] = uri;
  555. name[1] = local.intern();
  556. name[2] = qName.intern();
  557. }
  558. // Save in the cache for future use.
  559. table.put(name[2], name);
  560. tablesDirty = true;
  561. return name;
  562. }
  563. /**
  564. * Look up the URI associated with a prefix in this context.
  565. *
  566. * @param prefix The prefix to look up.
  567. * @return The associated Namespace URI, or null if none is
  568. * declared.
  569. * @see org.xml.sax.helpers.NamespaceSupport2#getURI
  570. */
  571. String getURI (String prefix)
  572. {
  573. if ("".equals(prefix)) {
  574. return defaultNS;
  575. } else if (prefixTable == null) {
  576. return null;
  577. } else {
  578. return (String)prefixTable.get(prefix);
  579. }
  580. }
  581. /**
  582. * Look up one of the prefixes associated with a URI in this context.
  583. *
  584. * <p>Since many prefixes may be mapped to the same URI,
  585. * the return value may be unreliable.</p>
  586. *
  587. * @param uri The URI to look up.
  588. * @return The associated prefix, or null if none is declared.
  589. * @see org.xml.sax.helpers.NamespaceSupport2#getPrefix
  590. */
  591. String getPrefix (String uri)
  592. {
  593. if (uriTable == null) {
  594. return null;
  595. } else {
  596. return (String)uriTable.get(uri);
  597. }
  598. }
  599. /**
  600. * Return an enumeration of prefixes declared in this context.
  601. *
  602. * @return An enumeration of prefixes (possibly empty).
  603. * @see org.xml.sax.helpers.NamespaceSupport2#getDeclaredPrefixes
  604. */
  605. Enumeration getDeclaredPrefixes ()
  606. {
  607. if (declarations == null) {
  608. return EMPTY_ENUMERATION;
  609. } else {
  610. return declarations.elements();
  611. }
  612. }
  613. /**
  614. * Return an enumeration of all prefixes currently in force.
  615. *
  616. * <p>The default prefix, if in force, is <em>not</em>
  617. * returned, and will have to be checked for separately.</p>
  618. *
  619. * @return An enumeration of prefixes (never empty).
  620. * @see org.xml.sax.helpers.NamespaceSupport2#getPrefixes
  621. */
  622. Enumeration getPrefixes ()
  623. {
  624. if (prefixTable == null) {
  625. return EMPTY_ENUMERATION;
  626. } else {
  627. return prefixTable.keys();
  628. }
  629. }
  630. ////////////////////////////////////////////////////////////////
  631. // Internal methods.
  632. ////////////////////////////////////////////////////////////////
  633. /**
  634. * Copy on write for the internal tables in this context.
  635. *
  636. * <p>This class is optimized for the normal case where most
  637. * elements do not contain Namespace declarations. In that case,
  638. * the Context2 will share data structures with its parent.
  639. * New tables are obtained only when new declarations are issued,
  640. * so they can be popped off the stack.</p>
  641. *
  642. * <p> JJK: **** Alternative: each Context2 might declare
  643. * _only_ its local bindings, and delegate upward if not found.</p>
  644. */
  645. private void copyTables ()
  646. {
  647. // Start by copying our parent's bindings
  648. prefixTable = (Hashtable)prefixTable.clone();
  649. uriTable = (Hashtable)uriTable.clone();
  650. // Replace the caches with empty ones, rather than
  651. // trying to determine which bindings should be flushed.
  652. // As far as I can tell, these caches are never actually
  653. // used in Xalan... More efficient to remove the whole
  654. // cache system? ****
  655. if(elementNameTable!=null)
  656. elementNameTable=new Hashtable();
  657. if(attributeNameTable!=null)
  658. attributeNameTable=new Hashtable();
  659. tablesDirty = true;
  660. }
  661. }
  662. // end of NamespaceSupport2.java