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