View Javadoc
1   /*
2    * Copyright 2005-2010 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 java.beans.PropertyEditorSupport;
20  import javax.xml.namespace.QName;
21  
22  import org.springframework.util.StringUtils;
23  
24  /**
25   * PropertyEditor for <code>javax.xml.namespace.QName</code>, to populate a property of type QName from a String value.
26   * <p/>
27   * Expects the syntax
28   * <pre>
29   * localPart
30   * </pre>
31   * or
32   * <pre>
33   * {namespace}localPart
34   * </pre>
35   * or
36   * <pre>
37   * {namespace}prefix:localPart
38   * </pre>
39   * This resembles the <code>toString()</code> representation of <code>QName</code> itself, but allows for prefixes to be
40   * specified as well.
41   *
42   * @author Arjen Poutsma
43   * @see javax.xml.namespace.QName
44   * @see javax.xml.namespace.QName#toString()
45   * @see javax.xml.namespace.QName#valueOf(String)
46   * @since 1.0.0
47   */
48  public class QNameEditor extends PropertyEditorSupport {
49  
50      @Override
51      public void setAsText(String text) throws IllegalArgumentException {
52          setValue(QNameUtils.parseQNameString(text));
53      }
54  
55      @Override
56      public String getAsText() {
57          Object value = getValue();
58          if (value == null || !(value instanceof QName)) {
59              return "";
60          }
61          else {
62              QName qName = (QName) value;
63              String prefix = QNameUtils.getPrefix(qName);
64              if (StringUtils.hasLength(qName.getNamespaceURI()) && StringUtils.hasLength(prefix)) {
65                  return "{" + qName.getNamespaceURI() + "}" + prefix + ":" + qName.getLocalPart();
66              }
67              else if (StringUtils.hasLength(qName.getNamespaceURI())) {
68                  return "{" + qName.getNamespaceURI() + "}" + qName.getLocalPart();
69              }
70              else {
71                  return qName.getLocalPart();
72              }
73          }
74      }
75  }