001 package net.sourceforge.jeuclid.elements.support; 002 003 import java.util.Collections; 004 import java.util.Iterator; 005 006 import javax.annotation.Nonnull; 007 import javax.annotation.Nullable; 008 import javax.xml.XMLConstants; 009 import javax.xml.namespace.NamespaceContext; 010 011 /** 012 * Chainable implementation of a {@link NamespaceContext}. 013 * 014 * @version $Revision: f5d68b2c52ae $ 015 */ 016 public class NamespaceContextAdder implements NamespaceContext { 017 018 private final String namespacePrefix; 019 private final String namespaceURI; 020 private final NamespaceContext delegateContext; 021 022 /** 023 * Create a new NamespaceAdder. The delegate context will be called if the 024 * namespace to be checked is not the namespace given in this adder. If the 025 * delegate is null, default values will be returned. 026 * 027 * @param ns 028 * namespace prefix. 029 * @param nsuri 030 * namespace URI 031 * @param delegate 032 * delegate {@link NamespaceContext} 033 */ 034 public NamespaceContextAdder(@Nonnull final String ns, 035 @Nonnull final String nsuri, 036 @Nullable final NamespaceContext delegate) { 037 this.namespacePrefix = ns; 038 this.namespaceURI = nsuri; 039 this.delegateContext = delegate; 040 } 041 042 /** {@inheritDoc} */ 043 public String getNamespaceURI(final String prefix) { 044 String retVal; 045 if (this.namespacePrefix.equals(prefix)) { 046 retVal = this.namespaceURI; 047 } else if (this.delegateContext == null) { 048 retVal = XMLConstants.NULL_NS_URI; 049 } else { 050 retVal = this.delegateContext.getNamespaceURI(prefix); 051 } 052 return retVal; 053 } 054 055 /** {@inheritDoc} */ 056 public String getPrefix(final String uri) { 057 String retVal; 058 if (this.namespaceURI.equals(uri)) { 059 retVal = this.namespacePrefix; 060 } else if (this.delegateContext == null) { 061 retVal = ""; 062 } else { 063 retVal = this.delegateContext.getPrefix(uri); 064 } 065 return retVal; 066 } 067 068 /** {@inheritDoc} */ 069 @SuppressWarnings("unchecked") 070 public Iterator<String> getPrefixes(final String uri) { 071 Iterator<String> retVal; 072 if (this.namespaceURI.equals(uri)) { 073 retVal = Collections.singleton(this.namespacePrefix).iterator(); 074 } else if (this.delegateContext == null) { 075 retVal = Collections.EMPTY_LIST.iterator(); 076 } else { 077 retVal = this.delegateContext.getPrefixes(uri); 078 } 079 return retVal; 080 } 081 082 }