001: // NamespaceSupport.java - generic Namespace support for SAX.
002: // http://www.saxproject.org
003: // Written by David Megginson
004: // This class is in the Public Domain. NO WARRANTY!
005:
006: // $Id: NamespaceSupport.java,v 1.1.1.1 2002/05/03 23:29:42 yuvalo Exp $
007:
008: package org.xml.sax.helpers;
009:
010: import java.util.EmptyStackException;
011: import java.util.Enumeration;
012: import java.util.Hashtable;
013: import java.util.Vector;
014:
015: /**
016: * Encapsulate Namespace logic for use by applications using SAX,
017: * or internally by SAX drivers.
018: *
019: * <blockquote>
020: * <em>This module, both source code and documentation, is in the
021: * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
022: * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
023: * for further information.
024: * </blockquote>
025: *
026: * <p>This class encapsulates the logic of Namespace processing:
027: * it tracks the declarations currently in force for each context
028: * and automatically processes qualified XML 1.0 names into their
029: * Namespace parts; it can also be used in reverse for generating
030: * XML 1.0 from Namespaces.</p>
031: *
032: * <p>Namespace support objects are reusable, but the reset method
033: * must be invoked between each session.</p>
034: *
035: * <p>Here is a simple session:</p>
036: *
037: * <pre>
038: * String parts[] = new String[3];
039: * NamespaceSupport support = new NamespaceSupport();
040: *
041: * support.pushContext();
042: * support.declarePrefix("", "http://www.w3.org/1999/xhtml");
043: * support.declarePrefix("dc", "http://www.purl.org/dc#");
044: *
045: * parts = support.processName("p", parts, false);
046: * System.out.println("Namespace URI: " + parts[0]);
047: * System.out.println("Local name: " + parts[1]);
048: * System.out.println("Raw name: " + parts[2]);
049: *
050: * parts = support.processName("dc:title", parts, false);
051: * System.out.println("Namespace URI: " + parts[0]);
052: * System.out.println("Local name: " + parts[1]);
053: * System.out.println("Raw name: " + parts[2]);
054: *
055: * support.popContext();
056: * </pre>
057: *
058: * <p>Note that this class is optimized for the use case where most
059: * elements do not contain Namespace declarations: if the same
060: * prefix/URI mapping is repeated for each context (for example), this
061: * class will be somewhat less efficient.</p>
062: *
063: * <p>Although SAX drivers (parsers) may choose to use this class to
064: * implement namespace handling, they are not required to do so.
065: * Applications must track namespace information themselves if they
066: * want to use namespace information.
067: *
068: * @since SAX 2.0
069: * @author David Megginson
070: * @version 2.0.1 (sax2r2)
071: */
072: public class NamespaceSupport {
073:
074: ////////////////////////////////////////////////////////////////////
075: // Constants.
076: ////////////////////////////////////////////////////////////////////
077:
078: /**
079: * The XML Namespace URI as a constant.
080: * The value is <code>http://www.w3.org/XML/1998/namespace</code>
081: * as defined in the XML Namespaces specification.
082: *
083: * <p>This is the Namespace URI that is automatically mapped
084: * to the "xml" prefix.</p>
085: */
086: public final static String XMLNS = "http://www.w3.org/XML/1998/namespace";
087:
088: /**
089: * An empty enumeration.
090: */
091: private final static Enumeration EMPTY_ENUMERATION = new Vector()
092: .elements();
093:
094: ////////////////////////////////////////////////////////////////////
095: // Constructor.
096: ////////////////////////////////////////////////////////////////////
097:
098: /**
099: * Create a new Namespace support object.
100: */
101: public NamespaceSupport() {
102: reset();
103: }
104:
105: ////////////////////////////////////////////////////////////////////
106: // Context management.
107: ////////////////////////////////////////////////////////////////////
108:
109: /**
110: * Reset this Namespace support object for reuse.
111: *
112: * <p>It is necessary to invoke this method before reusing the
113: * Namespace support object for a new session.</p>
114: */
115: public void reset() {
116: contexts = new Context[32];
117: contextPos = 0;
118: contexts[contextPos] = currentContext = new Context();
119: currentContext.declarePrefix("xml", XMLNS);
120: }
121:
122: /**
123: * Start a new Namespace context.
124: * The new context will automatically inherit
125: * the declarations of its parent context, but it will also keep
126: * track of which declarations were made within this context.
127: *
128: * <p>Event callback code should start a new context once per element.
129: * This means being ready to call this in either of two places.
130: * For elements that don't include namespace declarations, the
131: * <em>ContentHandler.startElement()</em> callback is the right place.
132: * For elements with such a declaration, it'd done in the first
133: * <em>ContentHandler.startPrefixMapping()</em> callback.
134: * A boolean flag can be used to
135: * track whether a context has been started yet. When either of
136: * those methods is called, it checks the flag to see if a new context
137: * needs to be started. If so, it starts the context and sets the
138: * flag. After <em>ContentHandler.startElement()</em>
139: * does that, it always clears the flag.
140: *
141: * <p>Normally, SAX drivers would push a new context at the beginning
142: * of each XML element. Then they perform a first pass over the
143: * attributes to process all namespace declarations, making
144: * <em>ContentHandler.startPrefixMapping()</em> callbacks.
145: * Then a second pass is made, to determine the namespace-qualified
146: * names for all attributes and for the element name.
147: * Finally all the information for the
148: * <em>ContentHandler.startElement()</em> callback is available,
149: * so it can then be made.
150: *
151: * <p>The Namespace support object always starts with a base context
152: * already in force: in this context, only the "xml" prefix is
153: * declared.</p>
154: *
155: * @see org.xml.sax.ContentHandler
156: * @see #popContext
157: */
158: public void pushContext() {
159: int max = contexts.length;
160:
161: contexts[contextPos].declsOK = false;
162: contextPos++;
163:
164: // Extend the array if necessary
165: if (contextPos >= max) {
166: Context newContexts[] = new Context[max * 2];
167: System.arraycopy(contexts, 0, newContexts, 0, max);
168: max *= 2;
169: contexts = newContexts;
170: }
171:
172: // Allocate the context if necessary.
173: currentContext = contexts[contextPos];
174: if (currentContext == null) {
175: contexts[contextPos] = currentContext = new Context();
176: }
177:
178: // Set the parent, if any.
179: if (contextPos > 0) {
180: currentContext.setParent(contexts[contextPos - 1]);
181: }
182: }
183:
184: /**
185: * Revert to the previous Namespace context.
186: *
187: * <p>Normally, you should pop the context at the end of each
188: * XML element. After popping the context, all Namespace prefix
189: * mappings that were previously in force are restored.</p>
190: *
191: * <p>You must not attempt to declare additional Namespace
192: * prefixes after popping a context, unless you push another
193: * context first.</p>
194: *
195: * @see #pushContext
196: */
197: public void popContext() {
198: contexts[contextPos].clear();
199: contextPos--;
200: if (contextPos < 0) {
201: throw new EmptyStackException();
202: }
203: currentContext = contexts[contextPos];
204: }
205:
206: ////////////////////////////////////////////////////////////////////
207: // Operations within a context.
208: ////////////////////////////////////////////////////////////////////
209:
210: /**
211: * Declare a Namespace prefix. All prefixes must be declared
212: * before they are referenced. For example, a SAX driver (parser)
213: * would scan an element's attributes
214: * in two passes: first for namespace declarations,
215: * then a second pass using {@link #processName processName()} to
216: * interpret prefixes against (potentially redefined) prefixes.
217: *
218: * <p>This method declares a prefix in the current Namespace
219: * context; the prefix will remain in force until this context
220: * is popped, unless it is shadowed in a descendant context.</p>
221: *
222: * <p>To declare the default element Namespace, use the empty string as
223: * the prefix.</p>
224: *
225: * <p>Note that you must <em>not</em> declare a prefix after
226: * you've pushed and popped another Namespace context, or
227: * treated the declarations phase as complete by processing
228: * a prefixed name.</p>
229: *
230: * <p>Note that there is an asymmetry in this library: {@link
231: * #getPrefix getPrefix} will not return the "" prefix,
232: * even if you have declared a default element namespace.
233: * To check for a default namespace,
234: * you have to look it up explicitly using {@link #getURI getURI}.
235: * This asymmetry exists to make it easier to look up prefixes
236: * for attribute names, where the default prefix is not allowed.</p>
237: *
238: * @param prefix The prefix to declare, or the empty string to
239: * indicate the default element namespace. This may never have
240: * the value "xml" or "xmlns".
241: * @param uri The Namespace URI to associate with the prefix.
242: * @return true if the prefix was legal, false otherwise
243: * @exception IllegalStateException when a prefix is declared
244: * after looking up a name in the context, or after pushing
245: * another context on top of it.
246: *
247: * @see #processName
248: * @see #getURI
249: * @see #getPrefix
250: */
251: public boolean declarePrefix(String prefix, String uri) {
252: if (prefix.equals("xml") || prefix.equals("xmlns")) {
253: return false;
254: } else {
255: currentContext.declarePrefix(prefix, uri);
256: return true;
257: }
258: }
259:
260: /**
261: * Process a raw XML 1.0 name, after all declarations in the current
262: * context have been handled by {@link #declarePrefix declarePrefix()}.
263: *
264: * <p>This method processes a raw XML 1.0 name in the current
265: * context by removing the prefix and looking it up among the
266: * prefixes currently declared. The return value will be the
267: * array supplied by the caller, filled in as follows:</p>
268: *
269: * <dl>
270: * <dt>parts[0]</dt>
271: * <dd>The Namespace URI, or an empty string if none is
272: * in use.</dd>
273: * <dt>parts[1]</dt>
274: * <dd>The local name (without prefix).</dd>
275: * <dt>parts[2]</dt>
276: * <dd>The original raw name.</dd>
277: * </dl>
278: *
279: * <p>All of the strings in the array will be internalized. If
280: * the raw name has a prefix that has not been declared, then
281: * the return value will be null.</p>
282: *
283: * <p>Note that attribute names are processed differently than
284: * element names: an unprefixed element name will received the
285: * default Namespace (if any), while an unprefixed attribute name
286: * will not.</p>
287: *
288: * @param qName The raw XML 1.0 name to be processed.
289: * @param parts An array supplied by the caller, capable of
290: * holding at least three members.
291: * @param isAttribute A flag indicating whether this is an
292: * attribute name (true) or an element name (false).
293: * @return The supplied array holding three internalized strings
294: * representing the Namespace URI (or empty string), the
295: * local name, and the raw XML 1.0 name; or null if there
296: * is an undeclared prefix.
297: * @see #declarePrefix
298: * @see java.lang.String#intern */
299: public String[] processName(String qName, String parts[],
300: boolean isAttribute) {
301: String myParts[] = currentContext.processName(qName,
302: isAttribute);
303: if (myParts == null) {
304: return null;
305: } else {
306: parts[0] = myParts[0];
307: parts[1] = myParts[1];
308: parts[2] = myParts[2];
309: return parts;
310: }
311: }
312:
313: /**
314: * Look up a prefix and get the currently-mapped Namespace URI.
315: *
316: * <p>This method looks up the prefix in the current context.
317: * Use the empty string ("") for the default Namespace.</p>
318: *
319: * @param prefix The prefix to look up.
320: * @return The associated Namespace URI, or null if the prefix
321: * is undeclared in this context.
322: * @see #getPrefix
323: * @see #getPrefixes
324: */
325: public String getURI(String prefix) {
326: return currentContext.getURI(prefix);
327: }
328:
329: /**
330: * Return an enumeration of all prefixes currently declared.
331: *
332: * <p><strong>Note:</strong> if there is a default prefix, it will not be
333: * returned in this enumeration; check for the default prefix
334: * using the {@link #getURI getURI} with an argument of "".</p>
335: *
336: * @return An enumeration of all prefixes declared in the
337: * current context except for the empty (default)
338: * prefix.
339: * @see #getDeclaredPrefixes
340: * @see #getURI
341: */
342: public Enumeration getPrefixes() {
343: return currentContext.getPrefixes();
344: }
345:
346: /**
347: * Return one of the prefixes mapped to a Namespace URI.
348: *
349: * <p>If more than one prefix is currently mapped to the same
350: * URI, this method will make an arbitrary selection; if you
351: * want all of the prefixes, use the {@link #getPrefixes}
352: * method instead.</p>
353: *
354: * <p><strong>Note:</strong> this will never return the empty (default) prefix;
355: * to check for a default prefix, use the {@link #getURI getURI}
356: * method with an argument of "".</p>
357: *
358: * @param uri The Namespace URI.
359: * @param isAttribute true if this prefix is for an attribute
360: * (and the default Namespace is not allowed).
361: * @return One of the prefixes currently mapped to the URI supplied,
362: * or null if none is mapped or if the URI is assigned to
363: * the default Namespace.
364: * @see #getPrefixes(java.lang.String)
365: * @see #getURI
366: */
367: public String getPrefix(String uri) {
368: return currentContext.getPrefix(uri);
369: }
370:
371: /**
372: * Return an enumeration of all prefixes currently declared for a URI.
373: *
374: * <p>This method returns prefixes mapped to a specific Namespace
375: * URI. The xml: prefix will be included. If you want only one
376: * prefix that's mapped to the Namespace URI, and you don't care
377: * which one you get, use the {@link #getPrefix getPrefix}
378: * method instead.</p>
379: *
380: * <p><strong>Note:</strong> the empty (default) prefix is <em>never</em> included
381: * in this enumeration; to check for the presence of a default
382: * Namespace, use the {@link #getURI getURI} method with an
383: * argument of "".</p>
384: *
385: * @param uri The Namespace URI.
386: * @return An enumeration of all prefixes declared in the
387: * current context.
388: * @see #getPrefix
389: * @see #getDeclaredPrefixes
390: * @see #getURI
391: */
392: public Enumeration getPrefixes(String uri) {
393: Vector prefixes = new Vector();
394: Enumeration allPrefixes = getPrefixes();
395: while (allPrefixes.hasMoreElements()) {
396: String prefix = (String) allPrefixes.nextElement();
397: if (uri.equals(getURI(prefix))) {
398: prefixes.addElement(prefix);
399: }
400: }
401: return prefixes.elements();
402: }
403:
404: /**
405: * Return an enumeration of all prefixes declared in this context.
406: *
407: * <p>The empty (default) prefix will be included in this
408: * enumeration; note that this behaviour differs from that of
409: * {@link #getPrefix} and {@link #getPrefixes}.</p>
410: *
411: * @return An enumeration of all prefixes declared in this
412: * context.
413: * @see #getPrefixes
414: * @see #getURI
415: */
416: public Enumeration getDeclaredPrefixes() {
417: return currentContext.getDeclaredPrefixes();
418: }
419:
420: ////////////////////////////////////////////////////////////////////
421: // Internal state.
422: ////////////////////////////////////////////////////////////////////
423:
424: private Context contexts[];
425: private Context currentContext;
426: private int contextPos;
427:
428: ////////////////////////////////////////////////////////////////////
429: // Internal classes.
430: ////////////////////////////////////////////////////////////////////
431:
432: /**
433: * Internal class for a single Namespace context.
434: *
435: * <p>This module caches and reuses Namespace contexts,
436: * so the number allocated
437: * will be equal to the element depth of the document, not to the total
438: * number of elements (i.e. 5-10 rather than tens of thousands).
439: * Also, data structures used to represent contexts are shared when
440: * possible (child contexts without declarations) to further reduce
441: * the amount of memory that's consumed.
442: * </p>
443: */
444: final class Context {
445:
446: /**
447: * Create the root-level Namespace context.
448: */
449: Context() {
450: copyTables();
451: }
452:
453: /**
454: * (Re)set the parent of this Namespace context.
455: * The context must either have been freshly constructed,
456: * or must have been cleared.
457: *
458: * @param context The parent Namespace context object.
459: */
460: void setParent(Context parent) {
461: this .parent = parent;
462: declarations = null;
463: prefixTable = parent.prefixTable;
464: uriTable = parent.uriTable;
465: elementNameTable = parent.elementNameTable;
466: attributeNameTable = parent.attributeNameTable;
467: defaultNS = parent.defaultNS;
468: declSeen = false;
469: declsOK = true;
470: }
471:
472: /**
473: * Makes associated state become collectible,
474: * invalidating this context.
475: * {@link #setParent} must be called before
476: * this context may be used again.
477: */
478: void clear() {
479: parent = null;
480: prefixTable = null;
481: uriTable = null;
482: elementNameTable = null;
483: attributeNameTable = null;
484: defaultNS = null;
485: }
486:
487: /**
488: * Declare a Namespace prefix for this context.
489: *
490: * @param prefix The prefix to declare.
491: * @param uri The associated Namespace URI.
492: * @see org.xml.sax.helpers.NamespaceSupport#declarePrefix
493: */
494: void declarePrefix(String prefix, String uri) {
495: // Lazy processing...
496: if (!declsOK)
497: throw new IllegalStateException(
498: "can't declare any more prefixes in this context");
499: if (!declSeen) {
500: copyTables();
501: }
502: if (declarations == null) {
503: declarations = new Vector();
504: }
505:
506: prefix = prefix.intern();
507: uri = uri.intern();
508: if ("".equals(prefix)) {
509: if ("".equals(uri)) {
510: defaultNS = null;
511: } else {
512: defaultNS = uri;
513: }
514: } else {
515: prefixTable.put(prefix, uri);
516: uriTable.put(uri, prefix); // may wipe out another prefix
517: }
518: declarations.addElement(prefix);
519: }
520:
521: /**
522: * Process a raw XML 1.0 name in this context.
523: *
524: * @param qName The raw XML 1.0 name.
525: * @param isAttribute true if this is an attribute name.
526: * @return An array of three strings containing the
527: * URI part (or empty string), the local part,
528: * and the raw name, all internalized, or null
529: * if there is an undeclared prefix.
530: * @see org.xml.sax.helpers.NamespaceSupport#processName
531: */
532: String[] processName(String qName, boolean isAttribute) {
533: String name[];
534: Hashtable table;
535:
536: // detect errors in call sequence
537: declsOK = false;
538:
539: // Select the appropriate table.
540: if (isAttribute) {
541: table = attributeNameTable;
542: } else {
543: table = elementNameTable;
544: }
545:
546: // Start by looking in the cache, and
547: // return immediately if the name
548: // is already known in this content
549: name = (String[]) table.get(qName);
550: if (name != null) {
551: return name;
552: }
553:
554: // We haven't seen this name in this
555: // context before. Maybe in the parent
556: // context, but we can't assume prefix
557: // bindings are the same.
558: name = new String[3];
559: name[2] = qName.intern();
560: int index = qName.indexOf(':');
561:
562: // No prefix.
563: if (index == -1) {
564: if (isAttribute || defaultNS == null) {
565: name[0] = "";
566: } else {
567: name[0] = defaultNS;
568: }
569: name[1] = name[2];
570: }
571:
572: // Prefix
573: else {
574: String prefix = qName.substring(0, index);
575: String local = qName.substring(index + 1);
576: String uri;
577: if ("".equals(prefix)) {
578: uri = defaultNS;
579: } else {
580: uri = (String) prefixTable.get(prefix);
581: }
582: if (uri == null) {
583: return null;
584: }
585: name[0] = uri;
586: name[1] = local.intern();
587: }
588:
589: // Save in the cache for future use.
590: // (Could be shared with parent context...)
591: table.put(name[2], name);
592: return name;
593: }
594:
595: /**
596: * Look up the URI associated with a prefix in this context.
597: *
598: * @param prefix The prefix to look up.
599: * @return The associated Namespace URI, or null if none is
600: * declared.
601: * @see org.xml.sax.helpers.NamespaceSupport#getURI
602: */
603: String getURI(String prefix) {
604: if ("".equals(prefix)) {
605: return defaultNS;
606: } else if (prefixTable == null) {
607: return null;
608: } else {
609: return (String) prefixTable.get(prefix);
610: }
611: }
612:
613: /**
614: * Look up one of the prefixes associated with a URI in this context.
615: *
616: * <p>Since many prefixes may be mapped to the same URI,
617: * the return value may be unreliable.</p>
618: *
619: * @param uri The URI to look up.
620: * @return The associated prefix, or null if none is declared.
621: * @see org.xml.sax.helpers.NamespaceSupport#getPrefix
622: */
623: String getPrefix(String uri) {
624: if (uriTable == null) {
625: return null;
626: } else {
627: return (String) uriTable.get(uri);
628: }
629: }
630:
631: /**
632: * Return an enumeration of prefixes declared in this context.
633: *
634: * @return An enumeration of prefixes (possibly empty).
635: * @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes
636: */
637: Enumeration getDeclaredPrefixes() {
638: if (declarations == null) {
639: return EMPTY_ENUMERATION;
640: } else {
641: return declarations.elements();
642: }
643: }
644:
645: /**
646: * Return an enumeration of all prefixes currently in force.
647: *
648: * <p>The default prefix, if in force, is <em>not</em>
649: * returned, and will have to be checked for separately.</p>
650: *
651: * @return An enumeration of prefixes (never empty).
652: * @see org.xml.sax.helpers.NamespaceSupport#getPrefixes
653: */
654: Enumeration getPrefixes() {
655: if (prefixTable == null) {
656: return EMPTY_ENUMERATION;
657: } else {
658: return prefixTable.keys();
659: }
660: }
661:
662: ////////////////////////////////////////////////////////////////
663: // Internal methods.
664: ////////////////////////////////////////////////////////////////
665:
666: /**
667: * Copy on write for the internal tables in this context.
668: *
669: * <p>This class is optimized for the normal case where most
670: * elements do not contain Namespace declarations.</p>
671: */
672: private void copyTables() {
673: if (prefixTable != null) {
674: prefixTable = (Hashtable) prefixTable.clone();
675: } else {
676: prefixTable = new Hashtable();
677: }
678: if (uriTable != null) {
679: uriTable = (Hashtable) uriTable.clone();
680: } else {
681: uriTable = new Hashtable();
682: }
683: elementNameTable = new Hashtable();
684: attributeNameTable = new Hashtable();
685: declSeen = true;
686: }
687:
688: ////////////////////////////////////////////////////////////////
689: // Protected state.
690: ////////////////////////////////////////////////////////////////
691:
692: Hashtable prefixTable;
693: Hashtable uriTable;
694: Hashtable elementNameTable;
695: Hashtable attributeNameTable;
696: String defaultNS = null;
697: boolean declsOK = true;
698:
699: ////////////////////////////////////////////////////////////////
700: // Internal state.
701: ////////////////////////////////////////////////////////////////
702:
703: private Vector declarations = null;
704: private boolean declSeen = false;
705: private Context parent = null;
706: }
707: }
708:
709: // end of NamespaceSupport.java
|