001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.servicemix.jbi.util;
018
019 import java.util.Collection;
020 import java.util.Iterator;
021
022 import javax.xml.namespace.QName;
023
024 import org.w3c.dom.Attr;
025 import org.w3c.dom.Element;
026
027 /**
028 * Utilities for converting QNames into different representations
029 *
030 * @author Alex Boisvert
031 * @version $Revision: 1.5 $
032 * @since 3.0
033 */
034 public final class QNameUtil {
035
036 private QNameUtil() {
037 }
038
039 /**
040 * Convert QName to the Clark notation, e.g., {namespace}localName
041 */
042 public static String toString(QName qname) {
043 if (qname.getNamespaceURI() == null) {
044 return "{}" + qname.getLocalPart();
045 } else {
046 return "{" + qname.getNamespaceURI() + "}" + qname.getLocalPart();
047 }
048 }
049
050 /**
051 * Convert QName to the Clark notation, e.g., {namespace}localName
052 */
053 public static String toString(Element element) {
054 if (element.getNamespaceURI() == null) {
055 return "{}" + element.getLocalName();
056 } else {
057 return "{" + element.getNamespaceURI() + "}" + element.getLocalName();
058 }
059 }
060
061 /**
062 * Convert QName to the Clark notation, e.g., {namespace}localName
063 */
064 public static String toString(Attr attr) {
065 if (attr.getNamespaceURI() == null) {
066 return "{}" + attr.getLocalName();
067 } else {
068 return "{" + attr.getNamespaceURI() + "}" + attr.getLocalName();
069 }
070 }
071
072 public static String toString(Collection collection) {
073 StringBuffer buf = new StringBuffer();
074 Iterator iter = collection.iterator();
075 while (iter.hasNext()) {
076 QName qname = (QName) iter.next();
077 buf.append(toString(qname));
078 if (iter.hasNext()) {
079 buf.append(", ");
080 }
081 }
082 return buf.toString();
083 }
084
085 /**
086 * Convert a String back into a QName following the Clark notation
087 */
088 public static QName parse(String name) {
089 int pos = name.indexOf('}');
090 if (name.startsWith("{") && pos > 0) {
091 String ns = name.substring(1, pos);
092 String lname = name.substring(pos + 1, name.length());
093 return new QName(ns, lname);
094 }
095 return null;
096 }
097
098 }