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