View Javadoc

1   /*
2    * Copyright 2005 the original author or authors.
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  package org.springframework.xml.namespace;
18  
19  import javax.xml.namespace.QName;
20  
21  import org.springframework.util.Assert;
22  import org.springframework.util.StringUtils;
23  import org.w3c.dom.Node;
24  
25  /**
26   * Helper class for using {@link QName}.
27   *
28   * @author Arjen Poutsma
29   * @see javax.xml.namespace.QName
30   * @since 1.0.0
31   */
32  public abstract class QNameUtils {
33  
34      /** Indicates whether {@link QName} has a prefix. The first release of the class did not have this. */
35      private static boolean qNameHasPrefix;
36  
37      static {
38          try {
39              QName.class.getDeclaredConstructor(new Class[]{String.class, String.class, String.class});
40              qNameHasPrefix = true;
41          }
42          catch (NoSuchMethodException e) {
43              qNameHasPrefix = false;
44          }
45      }
46  
47      /**
48       * Creates a new <code>QName</code> with the given parameters. Sets the prefix if possible, i.e. if the
49       * <code>QName(String, String, String)</code> constructor can be found. If this constructor is not available (as is
50       * the case on older implementations of JAX-RPC), the prefix is ignored.
51       *
52       * @param namespaceUri namespace URI of the <code>QName</code>
53       * @param localPart    local part of the <code>QName</code>
54       * @param prefix       prefix of the <code>QName</code>. May be ignored.
55       * @return the created <code>QName</code>
56       * @see QName#QName(String,String,String)
57       */
58      public static QName createQName(String namespaceUri, String localPart, String prefix) {
59          if (qNameHasPrefix) {
60              return new QName(namespaceUri, localPart, prefix);
61          }
62          else {
63              return new QName(namespaceUri, localPart);
64          }
65      }
66  
67      /**
68       * Returns the prefix of the given <code>QName</code>. Returns the prefix if available, i.e. if the
69       * <code>QName.getPrefix()</code> method can be found. If this method is not available (as is the case on older
70       * implementations of JAX-RPC), an empty string is returned.
71       *
72       * @param qName the <code>QName</code> to return the prefix from
73       * @return the prefix, if available, or an empty string
74       * @see javax.xml.namespace.QName#getPrefix()
75       */
76      public static String getPrefix(QName qName) {
77          return qNameHasPrefix ? qName.getPrefix() : "";
78      }
79  
80      /**
81       * Validates the given String as a QName
82       *
83       * @param text the qualified name
84       * @return <code>true</code> if valid, <code>false</code> otherwise
85       */
86      public static boolean validateQName(String text) {
87          if (!StringUtils.hasLength(text)) {
88              return false;
89          }
90          if (text.charAt(0) == '{') {
91              int i = text.indexOf('}');
92  
93              if (i == -1 || i == text.length() - 1) {
94                  return false;
95              }
96          }
97          return true;
98      }
99  
100     /**
101      * Returns the qualified name of the given DOM Node.
102      *
103      * @param node the node
104      * @return the qualified name of the node
105      */
106     public static QName getQNameForNode(Node node) {
107         if (node.getNamespaceURI() != null && node.getPrefix() != null && node.getLocalName() != null) {
108             return createQName(node.getNamespaceURI(), node.getLocalName(), node.getPrefix());
109         }
110         else if (node.getNamespaceURI() != null && node.getLocalName() != null) {
111             return new QName(node.getNamespaceURI(), node.getLocalName());
112         }
113         else if (node.getLocalName() != null) {
114             return new QName(node.getLocalName());
115         }
116         else {
117             // as a last resort, use the node name
118             return new QName(node.getNodeName());
119         }
120     }
121 
122     /**
123      * Convert a <code>QName</code> to a qualified name, as used by DOM and SAX. The returned string has a format of
124      * <code>prefix:localName</code> if the prefix is set, or just <code>localName</code> if not.
125      *
126      * @param qName the <code>QName</code>
127      * @return the qualified name
128      */
129     public static String toQualifiedName(QName qName) {
130         String prefix = getPrefix(qName);
131         if (!StringUtils.hasLength(prefix)) {
132             return qName.getLocalPart();
133         }
134         else {
135             return prefix + ":" + qName.getLocalPart();
136         }
137     }
138 
139     /**
140      * Convert a namespace URI and DOM or SAX qualified name to a <code>QName</code>. The qualified name can have the
141      * form <code>prefix:localname</code> or <code>localName</code>.
142      *
143      * @param namespaceUri  the namespace URI
144      * @param qualifiedName the qualified name
145      * @return a QName
146      */
147     public static QName toQName(String namespaceUri, String qualifiedName) {
148         int idx = qualifiedName.indexOf(':');
149         if (idx == -1) {
150             return new QName(namespaceUri, qualifiedName);
151         }
152         else {
153             return createQName(namespaceUri, qualifiedName.substring(idx + 1), qualifiedName.substring(0, idx));
154         }
155     }
156 
157     /**
158      * Parse the given qualified name string into a <code>QName</code>. Expects the syntax <code>localPart</code>,
159      * <code>{namespace}localPart</code>, or <code>{namespace}prefix:localPart</code>. This format resembles the
160      * <code>toString()</code> representation of <code>QName</code> itself, but allows for prefixes to be specified as
161      * well.
162      *
163      * @return a corresponding QName instance
164      * @throws IllegalArgumentException when the given string is <code>null</code> or empty.
165      */
166     public static QName parseQNameString(String qNameString) {
167         Assert.hasLength(qNameString, "QName text may not be null or empty");
168         if (qNameString.charAt(0) != '{') {
169             return new QName(qNameString);
170         }
171         else {
172             int endOfNamespaceURI = qNameString.indexOf('}');
173             if (endOfNamespaceURI == -1) {
174                 throw new IllegalArgumentException(
175                         "Cannot create QName from \"" + qNameString + "\", missing closing \"}\"");
176             }
177             int prefixSeperator = qNameString.indexOf(':', endOfNamespaceURI + 1);
178             String namespaceURI = qNameString.substring(1, endOfNamespaceURI);
179             if (prefixSeperator == -1) {
180                 return new QName(namespaceURI, qNameString.substring(endOfNamespaceURI + 1));
181             }
182             else {
183                 return createQName(namespaceURI, qNameString.substring(prefixSeperator + 1),
184                         qNameString.substring(endOfNamespaceURI + 1, prefixSeperator));
185             }
186         }
187 
188     }
189 
190 }