1 package org.codehaus.xfire.util;
2
3 import java.util.StringTokenizer;
4
5 import org.dom4j.DocumentFactory;
6 import org.dom4j.Element;
7 import org.dom4j.Namespace;
8
9 /***
10 * Namespace utilities.
11 *
12 * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
13 */
14 public class NamespaceHelper
15 {
16 /***
17 * @param nsUri
18 * @return The namespace with the specified URI. If one doesn't
19 * exist, one is created.
20 */
21 public static Namespace createNamespace( String prefix, String nsUri )
22 {
23 return DocumentFactory.getInstance().createNamespace( prefix, nsUri );
24 }
25
26 /***
27 * Create a unique namespace uri/prefix combination.
28 *
29 * @param nsUri
30 * @return The namespace with the specified URI. If one doesn't
31 * exist, one is created.
32 */
33 public static Namespace getNamespace( Element el, String nsUri )
34 {
35 Namespace ns = el.getNamespaceForURI( nsUri );
36
37 if ( ns == null || ns.getPrefix().equals("") )
38 {
39 ns = DocumentFactory.getInstance().createNamespace( getUniquePrefix( el ), nsUri );
40 el.add( ns );
41 }
42
43 return ns;
44 }
45
46 private static String getUniquePrefix( Element el )
47 {
48 int n = 1;
49
50 while(true)
51 {
52 String nsPrefix = "ns" + n;
53
54 if ( el.getNamespaceForPrefix( nsPrefix ) == null )
55 return nsPrefix;
56
57 n++;
58 }
59 }
60
61 public static String makeNamespaceFromClassName(String className, String protocol)
62 {
63 int index = className.lastIndexOf(".");
64
65 if (index == -1)
66 {
67 return protocol + "://" + "DefaultNamespace";
68 }
69
70 String packageName = className.substring(0, index);
71
72 StringTokenizer st = new StringTokenizer(packageName, ".");
73 String[] words = new String[st.countTokens()];
74
75 for (int i = 0; i < words.length; ++i)
76 {
77 words[i] = st.nextToken();
78 }
79
80 StringBuffer sb = new StringBuffer(80);
81
82 for (int i = words.length - 1; i >= 0; --i)
83 {
84 String word = words[i];
85
86
87 if (i != words.length - 1)
88 {
89 sb.append('.');
90 }
91
92 sb.append(word);
93 }
94
95 return protocol + "://" + sb.toString();
96 }
97 }