KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xml > internal > utils > NamespaceSupport2


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
21 import java.util.EmptyStackException JavaDoc;
22 import java.util.Enumeration JavaDoc;
23 import java.util.Hashtable JavaDoc;
24 import java.util.Vector JavaDoc;
25
26 /**
27  * Encapsulate Namespace tracking logic for use by SAX drivers.
28  *
29  * <p>This class is an attempt to rewrite the SAX NamespaceSupport
30  * "helper" class for improved efficiency. It can be used to track the
31  * namespace declarations currently in scope, providing lookup
32  * routines to map prefixes to URIs and vice versa.</p>
33  *
34  * <p>ISSUE: For testing purposes, I've extended NamespaceSupport even
35  * though I'm completely reasserting all behaviors and fields.
36  * Wasteful.... But SAX did not put an interface under that object and
37  * we seem to have written that SAX class into our APIs... and I don't
38  * want to argue with it right now. </p>
39  *
40  * @see org.xml.sax.helpers.NamespaceSupport
41  * */

42 public class NamespaceSupport2
43     extends org.xml.sax.helpers.NamespaceSupport JavaDoc
44 {
45     ////////////////////////////////////////////////////////////////////
46
// Internal state.
47
////////////////////////////////////////////////////////////////////
48

49     private Context2 currentContext; // Current point on the double-linked stack
50

51
52     ////////////////////////////////////////////////////////////////////
53
// Constants.
54
////////////////////////////////////////////////////////////////////
55

56
57     /**
58      * The XML Namespace as a constant.
59      *
60      * <p>This is the Namespace URI that is automatically mapped
61      * to the "xml" prefix.</p>
62      */

63     public final static String JavaDoc XMLNS =
64         "http://www.w3.org/XML/1998/namespace";
65
66
67     ////////////////////////////////////////////////////////////////////
68
// Constructor.
69
////////////////////////////////////////////////////////////////////
70

71
72     /**
73      * Create a new Namespace support object.
74      */

75     public NamespaceSupport2 ()
76     {
77         reset();
78     }
79
80
81     ////////////////////////////////////////////////////////////////////
82
// Context management.
83
////////////////////////////////////////////////////////////////////
84

85
86     /**
87      * Reset this Namespace support object for reuse.
88      *
89      * <p>It is necessary to invoke this method before reusing the
90      * Namespace support object for a new session.</p>
91      */

92     public void reset ()
93     {
94         // Discarding the whole stack doesn't save us a lot versus
95
// creating a new NamespaceSupport. Do we care, or should we
96
// change this to just reset the root context?
97
currentContext = new Context2(null);
98         currentContext.declarePrefix("xml", XMLNS);
99     }
100
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         // JJK: Context has a parent pointer.
119
// That means we don't need a stack to pop.
120
// We may want to retain for reuse, but that can be done via
121
// a child pointer.
122

123         Context2 parentContext=currentContext;
124         currentContext = parentContext.getChild();
125         if (currentContext == null){
126                 currentContext = new Context2(parentContext);
127             }
128         else{
129             // JJK: This will wipe out any leftover data
130
// if we're reusing a previously allocated Context.
131
currentContext.setParent(parentContext);
132         }
133     }
134
135
136     /**
137      * Revert to the previous Namespace context.
138      *
139      * <p>Normally, you should pop the context at the end of each
140      * XML element. After popping the context, all Namespace prefix
141      * mappings that were previously in force are restored.</p>
142      *
143      * <p>You must not attempt to declare additional Namespace
144      * prefixes after popping a context, unless you push another
145      * context first.</p>
146      *
147      * @see #pushContext
148      */

149     public void popContext ()
150     {
151         Context2 parentContext=currentContext.getParent();
152         if(parentContext==null)
153             throw new EmptyStackException JavaDoc();
154         else
155             currentContext = parentContext;
156     }
157
158
159
160     ////////////////////////////////////////////////////////////////////
161
// Operations within a context.
162
////////////////////////////////////////////////////////////////////
163

164
165     /**
166      * Declare a Namespace prefix.
167      *
168      * <p>This method declares a prefix in the current Namespace
169      * context; the prefix will remain in force until this context
170      * is popped, unless it is shadowed in a descendant context.</p>
171      *
172      * <p>To declare a default Namespace, use the empty string. The
173      * prefix must not be "xml" or "xmlns".</p>
174      *
175      * <p>Note that you must <em>not</em> declare a prefix after
176      * you've pushed and popped another Namespace.</p>
177      *
178      * <p>Note that there is an asymmetry in this library: while {@link
179      * #getPrefix getPrefix} will not return the default "" prefix,
180      * even if you have declared one; to check for a default prefix,
181      * you have to look it up explicitly using {@link #getURI getURI}.
182      * This asymmetry exists to make it easier to look up prefixes
183      * for attribute names, where the default prefix is not allowed.</p>
184      *
185      * @param prefix The prefix to declare, or null for the empty
186      * string.
187      * @param uri The Namespace URI to associate with the prefix.
188      * @return true if the prefix was legal, false otherwise
189      * @see #processName
190      * @see #getURI
191      * @see #getPrefix
192      */

193     public boolean declarePrefix (String JavaDoc prefix, String JavaDoc uri)
194     {
195         if (prefix.equals("xml") || prefix.equals("xmlns")) {
196             return false;
197         } else {
198             currentContext.declarePrefix(prefix, uri);
199             return true;
200         }
201     }
202
203
204     /**
205      * Process a raw XML 1.0 name.
206      *
207      * <p>This method processes a raw XML 1.0 name in the current
208      * context by removing the prefix and looking it up among the
209      * prefixes currently declared. The return value will be the
210      * array supplied by the caller, filled in as follows:</p>
211      *
212      * <dl>
213      * <dt>parts[0]</dt>
214      * <dd>The Namespace URI, or an empty string if none is
215      * in use.</dd>
216      * <dt>parts[1]</dt>
217      * <dd>The local name (without prefix).</dd>
218      * <dt>parts[2]</dt>
219      * <dd>The original raw name.</dd>
220      * </dl>
221      *
222      * <p>All of the strings in the array will be internalized. If
223      * the raw name has a prefix that has not been declared, then
224      * the return value will be null.</p>
225      *
226      * <p>Note that attribute names are processed differently than
227      * element names: an unprefixed element name will received the
228      * default Namespace (if any), while an unprefixed element name
229      * will not.</p>
230      *
231      * @param qName The raw XML 1.0 name to be processed.
232      * @param parts A string array supplied by the caller, capable of
233      * holding at least three members.
234      * @param isAttribute A flag indicating whether this is an
235      * attribute name (true) or an element name (false).
236      * @return The supplied array holding three internalized strings
237      * representing the Namespace URI (or empty string), the
238      * local name, and the raw XML 1.0 name; or null if there
239      * is an undeclared prefix.
240      * @see #declarePrefix
241      * @see java.lang.String#intern */

242     public String JavaDoc [] processName (String JavaDoc qName, String JavaDoc[] parts,
243                                   boolean isAttribute)
244     {
245         String JavaDoc[] name=currentContext.processName(qName, isAttribute);
246         if(name==null)
247             return null;
248
249         // JJK: This recopying is required because processName may return
250
// a cached result. I Don't Like It. *****
251
System.arraycopy(name,0,parts,0,3);
252         return parts;
253     }
254
255
256     /**
257      * Look up a prefix and get the currently-mapped Namespace URI.
258      *
259      * <p>This method looks up the prefix in the current context.
260      * Use the empty string ("") for the default Namespace.</p>
261      *
262      * @param prefix The prefix to look up.
263      * @return The associated Namespace URI, or null if the prefix
264      * is undeclared in this context.
265      * @see #getPrefix
266      * @see #getPrefixes
267      */

268     public String JavaDoc getURI (String JavaDoc prefix)
269     {
270         return currentContext.getURI(prefix);
271     }
272
273
274     /**
275      * Return an enumeration of all prefixes currently declared.
276      *
277      * <p><strong>Note:</strong> if there is a default prefix, it will not be
278      * returned in this enumeration; check for the default prefix
279      * using the {@link #getURI getURI} with an argument of "".</p>
280      *
281      * @return An enumeration of all prefixes declared in the
282      * current context except for the empty (default)
283      * prefix.
284      * @see #getDeclaredPrefixes
285      * @see #getURI
286      */

287     public Enumeration JavaDoc getPrefixes ()
288     {
289         return currentContext.getPrefixes();
290     }
291
292
293     /**
294      * Return one of the prefixes mapped to a Namespace URI.
295      *
296      * <p>If more than one prefix is currently mapped to the same
297      * URI, this method will make an arbitrary selection; if you
298      * want all of the prefixes, use the {@link #getPrefixes}
299      * method instead.</p>
300      *
301      * <p><strong>Note:</strong> this will never return the empty
302      * (default) prefix; to check for a default prefix, use the {@link
303      * #getURI getURI} method with an argument of "".</p>
304      *
305      * @param uri The Namespace URI.
306      * @return One of the prefixes currently mapped to the URI supplied,
307      * or null if none is mapped or if the URI is assigned to
308      * the default Namespace.
309      * @see #getPrefixes(java.lang.String)
310      * @see #getURI */

311     public String JavaDoc getPrefix (String JavaDoc uri)
312     {
313         return currentContext.getPrefix(uri);
314     }
315
316
317     /**
318      * Return an enumeration of all prefixes currently declared for a URI.
319      *
320      * <p>This method returns prefixes mapped to a specific Namespace
321      * URI. The xml: prefix will be included. If you want only one
322      * prefix that's mapped to the Namespace URI, and you don't care
323      * which one you get, use the {@link #getPrefix getPrefix}
324      * method instead.</p>
325      *
326      * <p><strong>Note:</strong> the empty (default) prefix is
327      * <em>never</em> included in this enumeration; to check for the
328      * presence of a default Namespace, use the {@link #getURI getURI}
329      * method with an argument of "".</p>
330      *
331      * @param uri The Namespace URI.
332      * @return An enumeration of all prefixes declared in the
333      * current context.
334      * @see #getPrefix
335      * @see #getDeclaredPrefixes
336      * @see #getURI */

337     public Enumeration JavaDoc getPrefixes (String JavaDoc uri)
338     {
339         // JJK: The old code involved creating a vector, filling it
340
// with all the matching prefixes, and then getting its
341
// elements enumerator. Wastes storage, wastes cycles if we
342
// don't actually need them all. Better to either implement
343
// a specific enumerator for these prefixes... or a filter
344
// around the all-prefixes enumerator, which comes out to
345
// roughly the same thing.
346
//
347
// **** Currently a filter. That may not be most efficient
348
// when I'm done restructuring storage!
349
return new PrefixForUriEnumerator(this,uri,getPrefixes());
350     }
351     
352
353     /**
354      * Return an enumeration of all prefixes declared in this context.
355      *
356      * <p>The empty (default) prefix will be included in this
357      * enumeration; note that this behaviour differs from that of
358      * {@link #getPrefix} and {@link #getPrefixes}.</p>
359      *
360      * @return An enumeration of all prefixes declared in this
361      * context.
362      * @see #getPrefixes
363      * @see #getURI
364      */

365     public Enumeration JavaDoc getDeclaredPrefixes ()
366     {
367         return currentContext.getDeclaredPrefixes();
368     }
369
370
371
372 }
373
374 ////////////////////////////////////////////////////////////////////
375
// Local classes.
376
// These were _internal_ classes... but in fact they don't have to be,
377
// and may be more efficient if they aren't.
378
////////////////////////////////////////////////////////////////////
379

380 /**
381  * Implementation of Enumeration filter, wrapped
382  * aroung the get-all-prefixes version of the operation. This is NOT
383  * necessarily the most efficient approach; finding the URI and then asking
384  * what prefixes apply to it might make much more sense.
385  */

386 class PrefixForUriEnumerator implements Enumeration JavaDoc
387 {
388     private Enumeration JavaDoc allPrefixes;
389     private String JavaDoc uri;
390     private String JavaDoc lookahead=null;
391     private NamespaceSupport2 nsup;
392      
393     // Kluge: Since one can't do a constructor on an
394
// anonymous class (as far as I know)...
395
PrefixForUriEnumerator(NamespaceSupport2 nsup,String JavaDoc uri, Enumeration JavaDoc allPrefixes)
396     {
397     this.nsup=nsup;
398         this.uri=uri;
399         this.allPrefixes=allPrefixes;
400     }
401         
402     public boolean hasMoreElements()
403     {
404         if(lookahead!=null)
405             return true;
406             
407         while(allPrefixes.hasMoreElements())
408             {
409                 String JavaDoc prefix=(String JavaDoc)allPrefixes.nextElement();
410                 if(uri.equals(nsup.getURI(prefix)))
411                     {
412                         lookahead=prefix;
413                         return true;
414                     }
415             }
416         return false;
417     }
418         
419     public Object JavaDoc nextElement()
420     {
421         if(hasMoreElements())
422             {
423                 String JavaDoc tmp=lookahead;
424                 lookahead=null;
425                 return tmp;
426             }
427         else
428             throw new java.util.NoSuchElementException JavaDoc();
429     }
430 }
431
432 /**
433  * Internal class for a single Namespace context.
434  *
435  * <p>This module caches and reuses Namespace contexts, so the number allocated
436  * will be equal to the element depth of the document, not to the total
437  * number of elements (i.e. 5-10 rather than tens of thousands).</p>
438  */

439 final class Context2 {
440
441     ////////////////////////////////////////////////////////////////
442
// Manefest Constants
443
////////////////////////////////////////////////////////////////
444

445     /**
446      * An empty enumeration.
447      */

448     private final static Enumeration JavaDoc EMPTY_ENUMERATION =
449         new Vector JavaDoc().elements();
450
451     ////////////////////////////////////////////////////////////////
452
// Protected state.
453
////////////////////////////////////////////////////////////////
454

455     Hashtable JavaDoc prefixTable;
456     Hashtable JavaDoc uriTable;
457     Hashtable JavaDoc elementNameTable;
458     Hashtable JavaDoc attributeNameTable;
459     String JavaDoc defaultNS = null;
460
461     ////////////////////////////////////////////////////////////////
462
// Internal state.
463
////////////////////////////////////////////////////////////////
464

465     private Vector JavaDoc declarations = null;
466     private boolean tablesDirty = false;
467     private Context2 parent = null;
468     private Context2 child = null;
469
470     /**
471      * Create a new Namespace context.
472      */

473     Context2 (Context2 parent)
474     {
475         if(parent==null)
476             {
477                 prefixTable = new Hashtable JavaDoc();
478                 uriTable = new Hashtable JavaDoc();
479                 elementNameTable=null;
480                 attributeNameTable=null;
481             }
482         else
483             setParent(parent);
484     }
485
486         
487     /**
488      * @returns The child Namespace context object, or null if this
489      * is the last currently on the chain.
490      */

491     Context2 getChild()
492     {
493         return child;
494     }
495         
496     /**
497      * @returns The parent Namespace context object, or null if this
498      * is the root.
499      */

500     Context2 getParent()
501     {
502         return parent;
503     }
504         
505     /**
506      * (Re)set the parent of this Namespace context.
507      * This is separate from the c'tor because it's re-applied
508      * when a Context2 is reused by push-after-pop.
509      *
510      * @param context The parent Namespace context object.
511      */

512     void setParent (Context2 parent)
513     {
514         this.parent = parent;
515         parent.child = this; // JJK: Doubly-linked
516
declarations = null;
517         prefixTable = parent.prefixTable;
518         uriTable = parent.uriTable;
519         elementNameTable = parent.elementNameTable;
520         attributeNameTable = parent.attributeNameTable;
521         defaultNS = parent.defaultNS;
522         tablesDirty = false;
523     }
524         
525         
526     /**
527      * Declare a Namespace prefix for this context.
528      *
529      * @param prefix The prefix to declare.
530      * @param uri The associated Namespace URI.
531      * @see org.xml.sax.helpers.NamespaceSupport2#declarePrefix
532      */

533     void declarePrefix (String JavaDoc prefix, String JavaDoc uri)
534     {
535                                 // Lazy processing...
536
if (!tablesDirty) {
537             copyTables();
538         }
539         if (declarations == null) {
540             declarations = new Vector JavaDoc();
541         }
542             
543         prefix = prefix.intern();
544         uri = uri.intern();
545         if ("".equals(prefix)) {
546             if ("".equals(uri)) {
547                 defaultNS = null;
548             } else {
549                 defaultNS = uri;
550             }
551         } else {
552             prefixTable.put(prefix, uri);
553             uriTable.put(uri, prefix); // may wipe out another prefix
554
}
555         declarations.addElement(prefix);
556     }
557
558
559     /**
560      * Process a raw XML 1.0 name in this context.
561      *
562      * @param qName The raw XML 1.0 name.
563      * @param isAttribute true if this is an attribute name.
564      * @return An array of three strings containing the
565      * URI part (or empty string), the local part,
566      * and the raw name, all internalized, or null
567      * if there is an undeclared prefix.
568      * @see org.xml.sax.helpers.NamespaceSupport2#processName
569      */

570     String JavaDoc [] processName (String JavaDoc qName, boolean isAttribute)
571     {
572         String JavaDoc name[];
573         Hashtable JavaDoc table;
574             
575                                 // Select the appropriate table.
576
if (isAttribute) {
577             if(elementNameTable==null)
578                 elementNameTable=new Hashtable JavaDoc();
579             table = elementNameTable;
580         } else {
581             if(attributeNameTable==null)
582                 attributeNameTable=new Hashtable JavaDoc();
583             table = attributeNameTable;
584         }
585             
586                                 // Start by looking in the cache, and
587
// return immediately if the name
588
// is already known in this content
589
name = (String JavaDoc[])table.get(qName);
590         if (name != null) {
591             return name;
592         }
593             
594                                 // We haven't seen this name in this
595
// context before.
596
name = new String JavaDoc[3];
597         int index = qName.indexOf(':');
598             
599             
600                                 // No prefix.
601
if (index == -1) {
602             if (isAttribute || defaultNS == null) {
603                 name[0] = "";
604             } else {
605                 name[0] = defaultNS;
606             }
607             name[1] = qName.intern();
608             name[2] = name[1];
609         }
610             
611                                 // Prefix
612
else {
613             String JavaDoc prefix = qName.substring(0, index);
614             String JavaDoc local = qName.substring(index+1);
615             String JavaDoc uri;
616             if ("".equals(prefix)) {
617                 uri = defaultNS;
618             } else {
619                 uri = (String JavaDoc)prefixTable.get(prefix);
620             }
621             if (uri == null) {
622                 return null;
623             }
624             name[0] = uri;
625             name[1] = local.intern();
626             name[2] = qName.intern();
627         }
628             
629                                 // Save in the cache for future use.
630
table.put(name[2], name);
631         tablesDirty = true;
632         return name;
633     }
634         
635
636     /**
637      * Look up the URI associated with a prefix in this context.
638      *
639      * @param prefix The prefix to look up.
640      * @return The associated Namespace URI, or null if none is
641      * declared.
642      * @see org.xml.sax.helpers.NamespaceSupport2#getURI
643      */

644     String JavaDoc getURI (String JavaDoc prefix)
645     {
646         if ("".equals(prefix)) {
647             return defaultNS;
648         } else if (prefixTable == null) {
649             return null;
650         } else {
651             return (String JavaDoc)prefixTable.get(prefix);
652         }
653     }
654
655
656     /**
657      * Look up one of the prefixes associated with a URI in this context.
658      *
659      * <p>Since many prefixes may be mapped to the same URI,
660      * the return value may be unreliable.</p>
661      *
662      * @param uri The URI to look up.
663      * @return The associated prefix, or null if none is declared.
664      * @see org.xml.sax.helpers.NamespaceSupport2#getPrefix
665      */

666     String JavaDoc getPrefix (String JavaDoc uri)
667     {
668         if (uriTable == null) {
669             return null;
670         } else {
671             return (String JavaDoc)uriTable.get(uri);
672         }
673     }
674         
675         
676     /**
677      * Return an enumeration of prefixes declared in this context.
678      *
679      * @return An enumeration of prefixes (possibly empty).
680      * @see org.xml.sax.helpers.NamespaceSupport2#getDeclaredPrefixes
681      */

682     Enumeration JavaDoc getDeclaredPrefixes ()
683     {
684         if (declarations == null) {
685             return EMPTY_ENUMERATION;
686         } else {
687             return declarations.elements();
688         }
689     }
690         
691         
692     /**
693      * Return an enumeration of all prefixes currently in force.
694      *
695      * <p>The default prefix, if in force, is <em>not</em>
696      * returned, and will have to be checked for separately.</p>
697      *
698      * @return An enumeration of prefixes (never empty).
699      * @see org.xml.sax.helpers.NamespaceSupport2#getPrefixes
700      */

701     Enumeration JavaDoc getPrefixes ()
702     {
703         if (prefixTable == null) {
704             return EMPTY_ENUMERATION;
705         } else {
706             return prefixTable.keys();
707         }
708     }
709         
710     ////////////////////////////////////////////////////////////////
711
// Internal methods.
712
////////////////////////////////////////////////////////////////
713

714     /**
715      * Copy on write for the internal tables in this context.
716      *
717      * <p>This class is optimized for the normal case where most
718      * elements do not contain Namespace declarations. In that case,
719      * the Context2 will share data structures with its parent.
720      * New tables are obtained only when new declarations are issued,
721      * so they can be popped off the stack.</p>
722      *
723      * <p> JJK: **** Alternative: each Context2 might declare
724      * _only_ its local bindings, and delegate upward if not found.</p>
725      */

726     private void copyTables ()
727     {
728         // Start by copying our parent's bindings
729
prefixTable = (Hashtable JavaDoc)prefixTable.clone();
730         uriTable = (Hashtable JavaDoc)uriTable.clone();
731
732         // Replace the caches with empty ones, rather than
733
// trying to determine which bindings should be flushed.
734
// As far as I can tell, these caches are never actually
735
// used in Xalan... More efficient to remove the whole
736
// cache system? ****
737
if(elementNameTable!=null)
738             elementNameTable=new Hashtable JavaDoc();
739         if(attributeNameTable!=null)
740             attributeNameTable=new Hashtable JavaDoc();
741         tablesDirty = true;
742     }
743
744 }
745
746
747 // end of NamespaceSupport2.java
748
Popular Tags