001 /**
002 * Copyright 2005-2011 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package org.kuali.rice.ken.util;
017
018 import java.util.ArrayList;
019 import java.util.Iterator;
020 import java.util.List;
021
022 import javax.xml.namespace.NamespaceContext;
023
024 import org.apache.log4j.Logger;
025 import org.w3c.dom.Document;
026
027 /**
028 * XPath NamespaceContext implementation that delegates all lookups to a DOM Document,
029 * which supplies all prefix/NS mappings defined in the doc.
030 * @author Kuali Rice Team (rice.collab@kuali.org)
031 */
032 public class DocumentNamespaceContext implements NamespaceContext {
033 private static final Logger LOG = Logger.getLogger(DocumentNamespaceContext.class);
034
035 // the DOM Document
036 private final Document doc;
037
038 /**
039 * Constructs a DocumentNamespaceContext.java.
040 * @param doc
041 */
042 public DocumentNamespaceContext(Document doc) {
043 this.doc = doc;
044 }
045
046 /**
047 * @see javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String)
048 */
049 public String getNamespaceURI(String prefix) {
050 LOG.debug("getNamespaceURI(" + prefix + ")");
051 if (prefix == null) {
052 throw new IllegalArgumentException("The prefix cannot be null.");
053 }
054 if (prefix.length() == 0) {
055 return doc.lookupNamespaceURI(null);
056 }
057 return doc.lookupNamespaceURI(prefix);
058 }
059
060 /**
061 * @see javax.xml.namespace.NamespaceContext#getPrefix(java.lang.String)
062 */
063 public String getPrefix(String namespaceURI) {
064 LOG.debug("getPrefix(" + namespaceURI + ")");
065 if (namespaceURI == null) {
066 throw new IllegalArgumentException("The namespace uri cannot be null.");
067 }
068 return doc.lookupPrefix(namespaceURI);
069 }
070
071 /**
072 * @see javax.xml.namespace.NamespaceContext#getPrefixes(java.lang.String)
073 */
074 public Iterator getPrefixes(String namespaceURI) {
075 LOG.debug("getPrefixes(" + namespaceURI + ")");
076 if (namespaceURI == null) {
077 throw new IllegalArgumentException("The namespace uri cannot be null.");
078 }
079 List<String> list = new ArrayList<String>(1);
080 String s = getPrefix(namespaceURI);
081 if (s != null) {
082 list.add(s);
083 }
084 return list.iterator();
085 }
086 }