1
2
3
4
5
6
7
8
9
10
11
12
13
14 package org.eclipse.jetty.jndi;
15
16 import java.util.HashMap;
17 import java.util.Map;
18
19 import javax.naming.Binding;
20 import javax.naming.Context;
21 import javax.naming.Name;
22 import javax.naming.NameNotFoundException;
23 import javax.naming.NameParser;
24 import javax.naming.NamingEnumeration;
25 import javax.naming.NamingException;
26
27 import org.eclipse.jetty.util.log.Log;
28
29
30
31
32
33
34
35
36
37
38
39 public class NamingUtil
40 {
41
42
43
44
45
46
47
48
49
50
51
52 public static Context bind (Context ctx, String nameStr, Object obj)
53 throws NamingException
54 {
55 Name name = ctx.getNameParser("").parse(nameStr);
56
57
58 if (name.size() == 0)
59 return null;
60
61 Context subCtx = ctx;
62
63
64 for (int i=0; i < name.size() - 1; i++)
65 {
66 try
67 {
68 subCtx = (Context)subCtx.lookup (name.get(i));
69 if(Log.isDebugEnabled())Log.debug("Subcontext "+name.get(i)+" already exists");
70 }
71 catch (NameNotFoundException e)
72 {
73 subCtx = subCtx.createSubcontext(name.get(i));
74 if(Log.isDebugEnabled())Log.debug("Subcontext "+name.get(i)+" created");
75 }
76 }
77
78 subCtx.rebind (name.get(name.size() - 1), obj);
79 if(Log.isDebugEnabled())Log.debug("Bound object to "+name.get(name.size() - 1));
80 return subCtx;
81
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 }