Thu, 31 Aug 2017 15:18:52 +0800
merge
1 /*
2 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.xml.internal.ws.util;
28 import java.util.ArrayList;
29 import java.util.EmptyStackException;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
35 import com.sun.xml.internal.ws.encoding.soap.streaming.SOAPNamespaceConstants;
37 /**
38 * Encapsulate Namespace logic for use by SAX drivers.
39 *
40 * <blockquote>
41 * <em>This module, both source code and documentation, is in the
42 * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
43 * </blockquote>
44 *
45 * <p>This class encapsulates the logic of Namespace processing:
46 * it tracks the declarations currently in force for each context
47 * and automatically processes qualified XML 1.0 names into their
48 * Namespace parts; it can also be used in reverse for generating
49 * XML 1.0 from Namespaces.</p>
50 *
51 * <p>Namespace support objects are reusable, but the reset method
52 * must be invoked between each session.</p>
53 *
54 * <p>Here is a simple session:</p>
55 *
56 * <pre>
57 * String parts[] = new String[3];
58 * NamespaceSupport support = new NamespaceSupport();
59 *
60 * support.pushContext();
61 * support.declarePrefix("", "http://www.w3.org/1999/xhtml");
62 * support.declarePrefix("dc", "http://www.purl.org/dc#");
63 *
64 * String parts[] = support.processName("p", parts, false);
65 * System.out.println("Namespace URI: " + parts[0]);
66 * System.out.println("Local name: " + parts[1]);
67 * System.out.println("Raw name: " + parts[2]);
69 * String parts[] = support.processName("dc:title", parts, false);
70 * System.out.println("Namespace URI: " + parts[0]);
71 * System.out.println("Local name: " + parts[1]);
72 * System.out.println("Raw name: " + parts[2]);
74 * support.popContext();
75 * </pre>
76 *
77 * <p>Note that this class is optimized for the use case where most
78 * elements do not contain Namespace declarations: if the same
79 * prefix/URI mapping is repeated for each context (for example), this
80 * class will be somewhat less efficient.</p>
81 *
82 * @author David Megginson
83 * @author WS Development Team
84 */
85 public final class NamespaceSupport {
87 /* added two new methods, slideContextUp() and slideContextDown()
88 * needed to implement the revised streaming parser class (Parser2)
89 */
91 ////////////////////////////////////////////////////////////////////
92 // Constants.
93 ////////////////////////////////////////////////////////////////////
95 /**
96 * The XML Namespace as a constant.
97 *
98 * <p>This is the Namespace URI that is automatically mapped
99 * to the "xml" prefix.</p>
100 */
101 public final static String XMLNS = "http://www.w3.org/XML/1998/namespace";
103 /**
104 * An empty enumeration.
105 */
106 private final static Iterable<String> EMPTY_ENUMERATION =
107 new ArrayList<String>();
109 ////////////////////////////////////////////////////////////////////
110 // Constructor.
111 ////////////////////////////////////////////////////////////////////
113 /**
114 * Create a new Namespace support object.
115 */
116 public NamespaceSupport() {
117 reset();
118 }
120 // PBG May 6 2002 added a copy constructor to support recording
121 public NamespaceSupport(NamespaceSupport that) {
122 contexts = new Context[that.contexts.length];
123 currentContext = null;
124 contextPos = that.contextPos;
126 Context currentParent = null;
128 for (int i = 0; i < that.contexts.length; i++) {
129 Context thatContext = that.contexts[i];
131 if (thatContext == null) {
132 contexts[i] = null;
133 continue;
134 }
136 Context thisContext = new Context(thatContext, currentParent);
137 contexts[i] = thisContext;
138 if (that.currentContext == thatContext) {
139 currentContext = thisContext;
140 }
142 currentParent = thisContext;
143 }
144 }
146 ////////////////////////////////////////////////////////////////////
147 // Context management.
148 ////////////////////////////////////////////////////////////////////
150 /**
151 * Reset this Namespace support object for reuse.
152 *
153 * <p>It is necessary to invoke this method before reusing the
154 * Namespace support object for a new session.</p>
155 */
156 public void reset() {
157 contexts = new Context[32];
158 contextPos = 0;
159 contexts[contextPos] = currentContext = new Context();
160 currentContext.declarePrefix("xml", XMLNS);
161 }
163 /**
164 * Start a new Namespace context.
165 *
166 * <p>Normally, you should push a new context at the beginning
167 * of each XML element: the new context will automatically inherit
168 * the declarations of its parent context, but it will also keep
169 * track of which declarations were made within this context.</p>
170 *
171 * <p>The Namespace support object always starts with a base context
172 * already in force: in this context, only the "xml" prefix is
173 * declared.</p>
174 *
175 * @see #popContext
176 */
177 public void pushContext() {
178 int max = contexts.length;
179 contextPos++;
181 // Extend the array if necessary
182 if (contextPos >= max) {
183 Context newContexts[] = new Context[max * 2];
184 System.arraycopy(contexts, 0, newContexts, 0, max);
185 contexts = newContexts;
186 }
188 // Allocate the context if necessary.
189 currentContext = contexts[contextPos];
190 if (currentContext == null) {
191 contexts[contextPos] = currentContext = new Context();
192 }
194 // Set the parent, if any.
195 if (contextPos > 0) {
196 currentContext.setParent(contexts[contextPos - 1]);
197 }
198 }
200 /**
201 * Revert to the previous Namespace context.
202 *
203 * <p>Normally, you should pop the context at the end of each
204 * XML element. After popping the context, all Namespace prefix
205 * mappings that were previously in force are restored.</p>
206 *
207 * <p>You must not attempt to declare additional Namespace
208 * prefixes after popping a context, unless you push another
209 * context first.</p>
210 *
211 * @see #pushContext
212 */
213 public void popContext() {
214 contextPos--;
215 if (contextPos < 0) {
216 throw new EmptyStackException();
217 }
218 currentContext = contexts[contextPos];
219 }
221 /*
222 * added for the revised streaming parser class (Parser2)
223 * Move the context artificially up one level (i.e. contracting it).
224 */
225 public void slideContextUp() {
226 contextPos--;
227 currentContext = contexts[contextPos];
228 }
230 /*
231 * added for the revised streaming parser class (Parser2)
232 * Move the context artificially down one level (i.e. expanding it).
233 */
234 public void slideContextDown() {
235 contextPos++;
237 if (contexts[contextPos] == null) {
238 // trying to slide to a context that was never created
239 contexts[contextPos] = contexts[contextPos - 1];
240 }
242 currentContext = contexts[contextPos];
243 }
245 ////////////////////////////////////////////////////////////////////
246 // Operations within a context.
247 ////////////////////////////////////////////////////////////////////
249 /**
250 * Declare a Namespace prefix.
251 *
252 * <p>This method declares a prefix in the current Namespace
253 * context; the prefix will remain in force until this context
254 * is popped, unless it is shadowed in a descendant context.</p>
255 *
256 * <p>To declare a default Namespace, use the empty string. The
257 * prefix must not be "xml" or "xmlns".</p>
258 *
259 * <p>Note that you must <em>not</em> declare a prefix after
260 * you've pushed and popped another Namespace.</p>
261 *
262 * <p>Note that there is an asymmetry in this library: while {@link
263 * #getPrefix getPrefix} will not return the default "" prefix,
264 * even if you have declared one; to check for a default prefix,
265 * you have to look it up explicitly using {@link #getURI getURI}.
266 * This asymmetry exists to make it easier to look up prefixes
267 * for attribute names, where the default prefix is not allowed.</p>
268 *
269 * @param prefix The prefix to declare, or null for the empty
270 * string.
271 * @param uri The Namespace URI to associate with the prefix.
272 * @return true if the prefix was legal, false otherwise
273 * @see #processName
274 * @see #getURI
275 * @see #getPrefix
276 */
277 public boolean declarePrefix(String prefix, String uri) {
278 // bugfix#: 4989753
279 if ((prefix.equals("xml") && !uri.equals(SOAPNamespaceConstants.XMLNS))
280 || prefix.equals("xmlns")) {
281 return false;
282 } else {
283 currentContext.declarePrefix(prefix, uri);
284 return true;
285 }
286 }
288 /**
289 * Process a raw XML 1.0 name.
290 *
291 * <p>This method processes a raw XML 1.0 name in the current
292 * context by removing the prefix and looking it up among the
293 * prefixes currently declared. The return value will be the
294 * array supplied by the caller, filled in as follows:</p>
295 *
296 * <dl>
297 * <dt>parts[0]</dt>
298 * <dd>The Namespace URI, or an empty string if none is
299 * in use.</dd>
300 * <dt>parts[1]</dt>
301 * <dd>The local name (without prefix).</dd>
302 * <dt>parts[2]</dt>
303 * <dd>The original raw name.</dd>
304 * </dl>
305 *
306 * <p>All of the strings in the array will be internalized. If
307 * the raw name has a prefix that has not been declared, then
308 * the return value will be null.</p>
309 *
310 * <p>Note that attribute names are processed differently than
311 * element names: an unprefixed element name will received the
312 * default Namespace (if any), while an unprefixed element name
313 * will not.</p>
314 *
315 * @param qName The raw XML 1.0 name to be processed.
316 * @param parts An array supplied by the caller, capable of
317 * holding at least three members.
318 * @param isAttribute A flag indicating whether this is an
319 * attribute name (true) or an element name (false).
320 * @return The supplied array holding three internalized strings
321 * representing the Namespace URI (or empty string), the
322 * local name, and the raw XML 1.0 name; or null if there
323 * is an undeclared prefix.
324 * @see #declarePrefix
325 * @see java.lang.String#intern */
326 public String[] processName(
327 String qName,
328 String parts[],
329 boolean isAttribute) {
330 String myParts[] = currentContext.processName(qName, isAttribute);
331 if (myParts == null) {
332 return null;
333 } else {
334 parts[0] = myParts[0];
335 parts[1] = myParts[1];
336 parts[2] = myParts[2];
337 return parts;
338 }
339 }
341 /**
342 * Look up a prefix and get the currently-mapped Namespace URI.
343 *
344 * <p>This method looks up the prefix in the current context.
345 * Use the empty string ("") for the default Namespace.</p>
346 *
347 * @param prefix The prefix to look up.
348 * @return The associated Namespace URI, or null if the prefix
349 * is undeclared in this context.
350 * @see #getPrefix
351 * @see #getPrefixes
352 */
353 public String getURI(String prefix) {
354 return currentContext.getURI(prefix);
355 }
357 /**
358 * Return an enumeration of all prefixes currently declared.
359 *
360 * <p><strong>Note:</strong> if there is a default prefix, it will not be
361 * returned in this enumeration; check for the default prefix
362 * using the {@link #getURI getURI} with an argument of "".</p>
363 *
364 * @return An enumeration of all prefixes declared in the
365 * current context except for the empty (default)
366 * prefix.
367 * @see #getDeclaredPrefixes
368 * @see #getURI
369 */
370 public Iterable<String> getPrefixes() {
371 return currentContext.getPrefixes();
372 }
374 /**
375 * Return one of the prefixes mapped to a Namespace URI.
376 *
377 * <p>If more than one prefix is currently mapped to the same
378 * URI, this method will make an arbitrary selection; if you
379 * want all of the prefixes, use the {@link #getPrefixes}
380 * method instead.</p>
381 *
382 * <p><strong>Note:</strong> this will never return the empty (default) prefix;
383 * to check for a default prefix, use the {@link #getURI getURI}
384 * method with an argument of "".</p>
385 *
386 * @param uri The Namespace URI.
387 * @return One of the prefixes currently mapped to the URI supplied,
388 * or null if none is mapped or if the URI is assigned to
389 * the default Namespace.
390 * @see #getPrefixes(java.lang.String)
391 * @see #getURI
392 */
393 public String getPrefix(String uri) {
394 return currentContext.getPrefix(uri);
395 }
397 /**
398 * Return an enumeration of all prefixes currently declared for a URI.
399 *
400 * <p>This method returns prefixes mapped to a specific Namespace
401 * URI. The xml: prefix will be included. If you want only one
402 * prefix that's mapped to the Namespace URI, and you don't care
403 * which one you get, use the {@link #getPrefix getPrefix}
404 * method instead.</p>
405 *
406 * <p><strong>Note:</strong> the empty (default) prefix is <em>never</em> included
407 * in this enumeration; to check for the presence of a default
408 * Namespace, use the {@link #getURI getURI} method with an
409 * argument of "".</p>
410 *
411 * @param uri The Namespace URI.
412 * @return An enumeration of all prefixes declared in the
413 * current context.
414 * @see #getPrefix
415 * @see #getDeclaredPrefixes
416 * @see #getURI
417 */
418 public Iterator getPrefixes(String uri) {
419 List prefixes = new ArrayList();
420 for (String prefix: getPrefixes()) {
421 if (uri.equals(getURI(prefix))) {
422 prefixes.add(prefix);
423 }
424 }
425 return prefixes.iterator();
426 }
428 /**
429 * Return an enumeration of all prefixes declared in this context.
430 *
431 * <p>The empty (default) prefix will be included in this
432 * enumeration; note that this behaviour differs from that of
433 * {@link #getPrefix} and {@link #getPrefixes}.</p>
434 *
435 * @return An enumeration of all prefixes declared in this
436 * context.
437 * @see #getPrefixes
438 * @see #getURI
439 */
440 public Iterable<String> getDeclaredPrefixes() {
441 return currentContext.getDeclaredPrefixes();
442 }
444 ////////////////////////////////////////////////////////////////////
445 // Internal state.
446 ////////////////////////////////////////////////////////////////////
448 private Context contexts[];
449 private Context currentContext;
450 private int contextPos;
452 ////////////////////////////////////////////////////////////////////
453 // Internal classes.
454 ////////////////////////////////////////////////////////////////////
456 /**
457 * Internal class for a single Namespace context.
458 *
459 * <p>This module caches and reuses Namespace contexts, so the number
460 * allocated will be equal to the element depth of the document, not to the
461 * total number of elements (i.e. 5-10 rather than tens of thousands).</p>
462 */
463 final static class Context {
465 /**
466 * Create the root-level Namespace context.
467 */
468 Context() {
469 copyTables();
470 }
471 // PGB May 6 2002 added copy constructor
472 Context(Context that, Context newParent) {
473 if (that == null) {
474 copyTables();
475 return;
476 }
478 if (newParent != null && !that.tablesDirty) {
479 prefixTable =
480 that.prefixTable == that.parent.prefixTable
481 ? newParent.prefixTable
482 : (HashMap) that.prefixTable.clone();
484 uriTable =
485 that.uriTable == that.parent.uriTable
486 ? newParent.uriTable
487 : (HashMap) that.uriTable.clone();
488 elementNameTable =
489 that.elementNameTable == that.parent.elementNameTable
490 ? newParent.elementNameTable
491 : (HashMap) that.elementNameTable.clone();
492 attributeNameTable =
493 that.attributeNameTable == that.parent.attributeNameTable
494 ? newParent.attributeNameTable
495 : (HashMap) that.attributeNameTable.clone();
496 defaultNS =
497 that.defaultNS == that.parent.defaultNS
498 ? newParent.defaultNS
499 : that.defaultNS;
500 } else {
501 prefixTable = (HashMap) that.prefixTable.clone();
502 uriTable = (HashMap) that.uriTable.clone();
503 elementNameTable = (HashMap) that.elementNameTable.clone();
504 attributeNameTable = (HashMap) that.attributeNameTable.clone();
505 defaultNS = that.defaultNS;
506 }
508 tablesDirty = that.tablesDirty;
509 parent = newParent;
510 declarations =
511 that.declarations == null
512 ? null
513 : (ArrayList) that.declarations.clone();
514 }
516 /**
517 * (Re)set the parent of this Namespace context.
518 *
519 * @param parent The parent Namespace context object.
520 */
521 void setParent(Context parent) {
522 this.parent = parent;
523 declarations = null;
524 prefixTable = parent.prefixTable;
525 uriTable = parent.uriTable;
526 elementNameTable = parent.elementNameTable;
527 attributeNameTable = parent.attributeNameTable;
528 defaultNS = parent.defaultNS;
529 tablesDirty = false;
530 }
532 /**
533 * Declare a Namespace prefix for this context.
534 *
535 * @param prefix The prefix to declare.
536 * @param uri The associated Namespace URI.
537 * @see org.xml.sax.helpers.NamespaceSupport#declarePrefix
538 */
539 void declarePrefix(String prefix, String uri) {
540 // Lazy processing...
541 if (!tablesDirty) {
542 copyTables();
543 }
544 if (declarations == null) {
545 declarations = new ArrayList();
546 }
548 prefix = prefix.intern();
549 uri = uri.intern();
550 if ("".equals(prefix)) {
551 if ("".equals(uri)) {
552 defaultNS = null;
553 } else {
554 defaultNS = uri;
555 }
556 } else {
557 prefixTable.put(prefix, uri);
558 uriTable.put(uri, prefix); // may wipe out another prefix
559 }
560 declarations.add(prefix);
561 }
563 /**
564 * Process a raw XML 1.0 name in this context.
565 *
566 * @param qName The raw XML 1.0 name.
567 * @param isAttribute true if this is an attribute name.
568 * @return An array of three strings containing the
569 * URI part (or empty string), the local part,
570 * and the raw name, all internalized, or null
571 * if there is an undeclared prefix.
572 * @see org.xml.sax.helpers.NamespaceSupport#processName
573 */
574 String[] processName(String qName, boolean isAttribute) {
575 String name[];
576 Map table;
578 // Select the appropriate table.
579 if (isAttribute) {
580 table = elementNameTable;
581 } else {
582 table = attributeNameTable;
583 }
585 // Start by looking in the cache, and
586 // return immediately if the name
587 // is already known in this content
588 name = (String[]) table.get(qName);
589 if (name != null) {
590 return name;
591 }
593 // We haven't seen this name in this
594 // context before.
595 name = new String[3];
596 int index = qName.indexOf(':');
598 // No prefix.
599 if (index == -1) {
600 if (isAttribute || defaultNS == null) {
601 name[0] = "";
602 } else {
603 name[0] = defaultNS;
604 }
605 name[1] = qName.intern();
606 name[2] = name[1];
607 }
609 // Prefix
610 else {
611 String prefix = qName.substring(0, index);
612 String local = qName.substring(index + 1);
613 String uri;
614 if ("".equals(prefix)) {
615 uri = defaultNS;
616 } else {
617 uri = (String) prefixTable.get(prefix);
618 }
619 if (uri == null) {
620 return null;
621 }
622 name[0] = uri;
623 name[1] = local.intern();
624 name[2] = qName.intern();
625 }
627 // Save in the cache for future use.
628 table.put(name[2], name);
629 tablesDirty = true;
630 return name;
631 }
633 /**
634 * Look up the URI associated with a prefix in this context.
635 *
636 * @param prefix The prefix to look up.
637 * @return The associated Namespace URI, or null if none is
638 * declared.
639 * @see org.xml.sax.helpers.NamespaceSupport#getURI
640 */
641 String getURI(String prefix) {
642 if ("".equals(prefix)) {
643 return defaultNS;
644 } else if (prefixTable == null) {
645 return null;
646 } else {
647 return (String) prefixTable.get(prefix);
648 }
649 }
651 /**
652 * Look up one of the prefixes associated with a URI in this context.
653 *
654 * <p>Since many prefixes may be mapped to the same URI,
655 * the return value may be unreliable.</p>
656 *
657 * @param uri The URI to look up.
658 * @return The associated prefix, or null if none is declared.
659 * @see org.xml.sax.helpers.NamespaceSupport#getPrefix
660 */
661 String getPrefix(String uri) {
662 if (uriTable == null) {
663 return null;
664 } else {
665 return (String) uriTable.get(uri);
666 }
667 }
669 /**
670 * Return an enumeration of prefixes declared in this context.
671 *
672 * @return An enumeration of prefixes (possibly empty).
673 * @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes
674 */
675 Iterable<String> getDeclaredPrefixes() {
676 if (declarations == null) {
677 return EMPTY_ENUMERATION;
678 } else {
679 return declarations;
680 }
681 }
683 /**
684 * Return an enumeration of all prefixes currently in force.
685 *
686 * <p>The default prefix, if in force, is <em>not</em>
687 * returned, and will have to be checked for separately.</p>
688 *
689 * @return An enumeration of prefixes (never empty).
690 * @see org.xml.sax.helpers.NamespaceSupport#getPrefixes
691 */
692 Iterable<String> getPrefixes() {
693 if (prefixTable == null) {
694 return EMPTY_ENUMERATION;
695 } else {
696 return prefixTable.keySet();
697 }
698 }
700 ////////////////////////////////////////////////////////////////
701 // Internal methods.
702 ////////////////////////////////////////////////////////////////
704 /**
705 * Copy on write for the internal tables in this context.
706 *
707 * <p>This class is optimized for the normal case where most
708 * elements do not contain Namespace declarations.</p>
709 */
710 private void copyTables() {
711 if (prefixTable != null) {
712 prefixTable = (HashMap) prefixTable.clone();
713 } else {
714 prefixTable = new HashMap();
715 }
716 if (uriTable != null) {
717 uriTable = (HashMap) uriTable.clone();
718 } else {
719 uriTable = new HashMap();
720 }
721 elementNameTable = new HashMap();
722 attributeNameTable = new HashMap();
723 tablesDirty = true;
724 }
726 ////////////////////////////////////////////////////////////////
727 // Protected state.
728 ////////////////////////////////////////////////////////////////
730 HashMap prefixTable;
731 HashMap uriTable;
732 // PBG May 6 2002 changed these two from Map to HashMap
733 HashMap elementNameTable;
734 HashMap attributeNameTable;
735 String defaultNS = null;
737 ////////////////////////////////////////////////////////////////
738 // Internal state.
739 ////////////////////////////////////////////////////////////////
741 // PBG May 6 2002 changed this from List to ArrayList
742 private ArrayList declarations = null;
743 private boolean tablesDirty = false;
744 private Context parent = null;
745 }
746 }