1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mortbay.naming;
17
18 import java.util.HashMap;
19 import java.util.Map;
20
21 import javax.naming.Binding;
22 import javax.naming.Context;
23 import javax.naming.Name;
24 import javax.naming.NameNotFoundException;
25 import javax.naming.NameParser;
26 import javax.naming.NamingEnumeration;
27 import javax.naming.NamingException;
28
29 import org.mortbay.log.Log;
30
31
32
33
34
35
36
37
38
39
40
41 public class NamingUtil
42 {
43
44
45
46
47
48
49
50
51
52
53
54 public static void bind (Context ctx, String nameStr, Object obj)
55 throws NamingException
56 {
57 Name name = ctx.getNameParser("").parse(nameStr);
58
59
60 if (name.size() == 0)
61 return;
62
63 Context subCtx = ctx;
64
65
66 for (int i=0; i < name.size() - 1; i++)
67 {
68 try
69 {
70 subCtx = (Context)subCtx.lookup (name.get(i));
71 if(Log.isDebugEnabled())Log.debug("Subcontext "+name.get(i)+" already exists");
72 }
73 catch (NameNotFoundException e)
74 {
75 subCtx = subCtx.createSubcontext(name.get(i));
76 if(Log.isDebugEnabled())Log.debug("Subcontext "+name.get(i)+" created");
77 }
78 }
79
80 subCtx.rebind (name.get(name.size() - 1), obj);
81 if(Log.isDebugEnabled())Log.debug("Bound object to "+name.get(name.size() - 1));
82 }
83
84
85 public static void unbind (Context ctx)
86 throws NamingException
87 {
88
89 NamingEnumeration ne = ctx.listBindings(ctx.getNameInNamespace());
90
91 while (ne.hasMoreElements())
92 {
93 Binding b = (Binding)ne.nextElement();
94 if (b.getObject() instanceof Context)
95 {
96 unbind((Context)b.getObject());
97 }
98 else
99 ctx.unbind(b.getName());
100 }
101 }
102
103
104
105
106
107
108
109
110 public static Map flattenBindings (Context ctx, String name)
111 throws NamingException
112 {
113 HashMap map = new HashMap();
114
115
116 Context c = (Context)ctx.lookup (name);
117 NameParser parser = c.getNameParser("");
118 NamingEnumeration enm = ctx.listBindings(name);
119 while (enm.hasMore())
120 {
121 Binding b = (Binding)enm.next();
122
123 if (b.getObject() instanceof Context)
124 {
125 map.putAll(flattenBindings (c, b.getName()));
126 }
127 else
128 {
129 Name compoundName = parser.parse (c.getNameInNamespace());
130 compoundName.add(b.getName());
131 map.put (compoundName.toString(), b.getObject());
132 }
133
134 }
135
136 return map;
137 }
138
139 }