View Javadoc

1   package net.sourceforge.jeuclid.elements.support;
2   
3   import java.util.Collections;
4   import java.util.Iterator;
5   
6   import javax.annotation.Nonnull;
7   import javax.annotation.Nullable;
8   import javax.xml.XMLConstants;
9   import javax.xml.namespace.NamespaceContext;
10  
11  /**
12   * Chainable implementation of a {@link NamespaceContext}.
13   *
14   * @version $Revision: f5d68b2c52ae $
15   */
16  public class NamespaceContextAdder implements NamespaceContext {
17  
18      private final String namespacePrefix;
19      private final String namespaceURI;
20      private final NamespaceContext delegateContext;
21  
22      /**
23       * Create a new NamespaceAdder. The delegate context will be called if the
24       * namespace to be checked is not the namespace given in this adder. If the
25       * delegate is null, default values will be returned.
26       *
27       * @param ns
28       *            namespace prefix.
29       * @param nsuri
30       *            namespace URI
31       * @param delegate
32       *            delegate {@link NamespaceContext}
33       */
34      public NamespaceContextAdder(@Nonnull final String ns,
35              @Nonnull final String nsuri,
36              @Nullable final NamespaceContext delegate) {
37          this.namespacePrefix = ns;
38          this.namespaceURI = nsuri;
39          this.delegateContext = delegate;
40      }
41  
42      /** {@inheritDoc} */
43      public String getNamespaceURI(final String prefix) {
44          String retVal;
45          if (this.namespacePrefix.equals(prefix)) {
46              retVal = this.namespaceURI;
47          } else if (this.delegateContext == null) {
48              retVal = XMLConstants.NULL_NS_URI;
49          } else {
50              retVal = this.delegateContext.getNamespaceURI(prefix);
51          }
52          return retVal;
53      }
54  
55      /** {@inheritDoc} */
56      public String getPrefix(final String uri) {
57          String retVal;
58          if (this.namespaceURI.equals(uri)) {
59              retVal = this.namespacePrefix;
60          } else if (this.delegateContext == null) {
61              retVal = "";
62          } else {
63              retVal = this.delegateContext.getPrefix(uri);
64          }
65          return retVal;
66      }
67  
68      /** {@inheritDoc} */
69      @SuppressWarnings("unchecked")
70      public Iterator<String> getPrefixes(final String uri) {
71          Iterator<String> retVal;
72          if (this.namespaceURI.equals(uri)) {
73              retVal = Collections.singleton(this.namespacePrefix).iterator();
74          } else if (this.delegateContext == null) {
75              retVal = Collections.EMPTY_LIST.iterator();
76          } else {
77              retVal = this.delegateContext.getPrefixes(uri);
78          }
79          return retVal;
80      }
81  
82  }