KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > console > ldapmanager > LDAPManagerHelper


1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 package org.apache.geronimo.console.ldapmanager;
19
20 import java.util.ArrayList JavaDoc;
21 import java.util.Collection JavaDoc;
22 import java.util.Enumeration JavaDoc;
23 import java.util.HashMap JavaDoc;
24 import java.util.Hashtable JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.Map JavaDoc;
27
28 import javax.naming.Context JavaDoc;
29 import javax.naming.NameClassPair JavaDoc;
30 import javax.naming.NamingEnumeration JavaDoc;
31 import javax.naming.NamingException JavaDoc;
32 import javax.naming.directory.Attribute JavaDoc;
33 import javax.naming.directory.Attributes JavaDoc;
34 import javax.naming.directory.DirContext JavaDoc;
35 import javax.naming.directory.InitialDirContext JavaDoc;
36 import javax.naming.directory.SearchControls JavaDoc;
37 import javax.naming.directory.SearchResult JavaDoc;
38 import javax.servlet.http.HttpSession JavaDoc;
39
40 import uk.ltd.getahead.dwr.WebContext;
41 import uk.ltd.getahead.dwr.WebContextFactory;
42
43 /**
44  * The LDAP manager helper
45  */

46 public class LDAPManagerHelper {
47     private final static String JavaDoc LDAP_VERSION_KEY = "java.naming.ldap.version";
48
49     private final static String JavaDoc SSL_VALUE = "ssl";
50
51     private final static String JavaDoc NONE_VALUE = "none";
52
53     private final static String JavaDoc INITIAL_CONTEXT_FACTORY_DEFAULT = "com.sun.jndi.ldap.LdapCtxFactory";
54
55     private final static String JavaDoc HOST_DEFAULT = "localhost";
56
57     private final static String JavaDoc PORT_DEFAULT = "1389";
58
59     private final static String JavaDoc BASE_DN_DEFAULT = "ou=system";
60
61     // LDAP Version: "3", "2"
62
private final static String JavaDoc LDAP_VERSION_DEFAULT = "3";
63
64     // Security Protocol: "simple", "ssl", "sasl"
65
private final static String JavaDoc SECURITY_PROTOCOL_DEFAULT = "simple";
66
67     // Security Authentication: "simple", "none", "strong"
68
private final static String JavaDoc SECURITY_AUTHENTICATION_DEFAULT = "simple";
69
70     private final static String JavaDoc SECURITY_PRINCIPAL_DEFAULT = "uid=admin, ou=system";
71
72     private final static String JavaDoc SECURITY_CREDENTIALS_DEFAULT = "secret";
73
74     private final static String JavaDoc ONELEVEL_SCOPE = "onelevel";
75
76     private final static String JavaDoc SUBTREE_SCOPE = "subtree";
77
78     private final static String JavaDoc DIR_CONTEXT_KEY = "LDAPManagerHelper.dirContext";
79
80     private final static String JavaDoc DIR_ENV_KEY = "LDAPManagerHelper.dirEnv";
81
82     private final static String JavaDoc HOST_KEY = "LDAPManagerHelper.host";
83
84     private final static String JavaDoc PORT_KEY = "LDAPManagerHelper.port";
85
86     private final static String JavaDoc BASE_DN_KEY = "LDAPManagerHelper.baseDN";
87
88     private final static String JavaDoc SUCCESS_RESULT = "<SUCCESS>";
89
90     private DirContext JavaDoc dirContext;
91
92     private Hashtable JavaDoc dirEnv;
93
94     private String JavaDoc host;
95
96     private String JavaDoc port;
97
98     private String JavaDoc baseDN;
99
100     /**
101      * Construct an LDAP manager helper using config data (default)
102      */

103     public LDAPManagerHelper() throws Exception JavaDoc {
104         dirContext = (DirContext JavaDoc) getSessionAttribute(DIR_CONTEXT_KEY);
105         if (dirContext == null) {
106             // TODO: Get the default values from configuration / GBean
107
String JavaDoc result = connect(INITIAL_CONTEXT_FACTORY_DEFAULT,
108                     HOST_DEFAULT, PORT_DEFAULT, BASE_DN_DEFAULT,
109                     LDAP_VERSION_DEFAULT, SECURITY_PROTOCOL_DEFAULT,
110                     SECURITY_AUTHENTICATION_DEFAULT,
111                     SECURITY_PRINCIPAL_DEFAULT, SECURITY_CREDENTIALS_DEFAULT);
112             if (!SUCCESS_RESULT.equalsIgnoreCase(result)) {
113                 throw new Exception JavaDoc(result);
114             }
115         } else {
116             dirEnv = (Hashtable JavaDoc) getSessionAttribute(DIR_ENV_KEY);
117             host = (String JavaDoc) getSessionAttribute(HOST_KEY);
118             port = (String JavaDoc) getSessionAttribute(PORT_KEY);
119             baseDN = (String JavaDoc) getSessionAttribute(BASE_DN_KEY);
120         }
121     }
122
123     /**
124      * Construct an LDAP manager helper using config data (partial)
125      */

126     public LDAPManagerHelper(String JavaDoc host, String JavaDoc port, String JavaDoc baseDN,
127             String JavaDoc securityAuthentication, String JavaDoc userDN, String JavaDoc userPwd)
128             throws Exception JavaDoc {
129         connect(INITIAL_CONTEXT_FACTORY_DEFAULT, host, port, baseDN,
130                 LDAP_VERSION_DEFAULT, SECURITY_PROTOCOL_DEFAULT,
131                 securityAuthentication, userDN, userPwd);
132     }
133
134     /**
135      * Construct an LDAP manager helper using config data (all)
136      */

137     public LDAPManagerHelper(String JavaDoc initialContextFactory, String JavaDoc host,
138             String JavaDoc port, String JavaDoc baseDN, String JavaDoc ldapVersion,
139             String JavaDoc securityProtocol, String JavaDoc securityAuthentication,
140             String JavaDoc securityPrincipal, String JavaDoc securityCredentials)
141             throws Exception JavaDoc {
142         connect(initialContextFactory, host, port, baseDN, ldapVersion,
143                 securityProtocol, securityAuthentication, securityPrincipal,
144                 securityCredentials);
145     }
146
147     /**
148      * Create a directory context using config data
149      */

150     public synchronized String JavaDoc connect(String JavaDoc initialContextFactory,
151             String JavaDoc host, String JavaDoc port, String JavaDoc baseDN, String JavaDoc ldapVersion,
152             String JavaDoc securityProtocol, String JavaDoc securityAuthentication,
153             String JavaDoc securityPrincipal, String JavaDoc securityCredentials)
154             throws Exception JavaDoc {
155         String JavaDoc result = SUCCESS_RESULT;
156
157         Hashtable JavaDoc dirEnv = new Hashtable JavaDoc();
158         dirEnv.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
159         String JavaDoc providerURL = createLDAPURL(host, port, ""); // Empty Base DN
160
dirEnv.put(Context.PROVIDER_URL, providerURL);
161         dirEnv.put(LDAP_VERSION_KEY, ldapVersion);
162         if (SSL_VALUE.equalsIgnoreCase(securityProtocol)) {
163             dirEnv.put(Context.SECURITY_PROTOCOL, SSL_VALUE);
164         }
165         dirEnv.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);
166         if (!(NONE_VALUE.equalsIgnoreCase(securityAuthentication))) {
167             // Either "simple" or "strong"
168
dirEnv.put(Context.SECURITY_PRINCIPAL, securityPrincipal); // User DN
169
dirEnv.put(Context.SECURITY_CREDENTIALS, securityCredentials); // Password
170
}
171
172         try {
173             DirContext JavaDoc newDirContext = new InitialDirContext JavaDoc(dirEnv);
174             // Close old context
175
if (dirContext != null) {
176                 dirContext.close();
177             }
178             // Save directory data to class vars
179
this.dirContext = newDirContext;
180             this.dirEnv = dirEnv;
181             this.host = host;
182             this.port = port;
183             this.baseDN = baseDN;
184             // Save directory data to session
185
setSessionAttribute(DIR_CONTEXT_KEY, dirContext);
186             setSessionAttribute(DIR_ENV_KEY, dirEnv);
187             setSessionAttribute(HOST_KEY, host);
188             setSessionAttribute(PORT_KEY, port);
189             setSessionAttribute(BASE_DN_KEY, baseDN);
190         } catch (NamingException JavaDoc e) {
191             result = "Problem connecting to directory server: "
192                     + e.getMessage();
193         }
194
195         return result;
196     }
197
198     /**
199      * Return directory context environment
200      */

201     public Map JavaDoc getEnvironment() {
202         Map JavaDoc env = new HashMap JavaDoc();
203         env.put("host", host);
204         env.put("port", port);
205         String JavaDoc ldapVersion = (String JavaDoc) dirEnv.get(LDAP_VERSION_KEY);
206         env.put("ldapVersion", ldapVersion);
207         env.put("baseDN", baseDN);
208         String JavaDoc securityProtocol = (String JavaDoc) dirEnv
209                 .get(Context.SECURITY_PROTOCOL);
210         env.put("securityProtocol", securityProtocol);
211         String JavaDoc securityAuthentication = (String JavaDoc) dirEnv
212                 .get(Context.SECURITY_AUTHENTICATION);
213         env.put("securityAuthentication", securityAuthentication);
214         String JavaDoc securityPrincipal = (String JavaDoc) dirEnv
215                 .get(Context.SECURITY_PRINCIPAL);
216         env.put("securityPrincipal", securityPrincipal);
217
218         return env;
219     }
220
221     /**
222      * Returns the names bound in the named context
223      */

224     public Collection JavaDoc list(String JavaDoc name) throws Exception JavaDoc {
225         ArrayList JavaDoc result = new ArrayList JavaDoc();
226
227         try {
228             NamingEnumeration JavaDoc list = dirContext.list(name); // can't be ""
229

230             while (list.hasMore()) {
231                 NameClassPair JavaDoc ncp = (NameClassPair JavaDoc) list.next();
232                 String JavaDoc childName = ncp.getName();
233                 String JavaDoc dn = childName + ", " + name;
234                 String JavaDoc[] pair = { childName, dn };
235                 result.add(pair);
236             }
237         } catch (NamingException JavaDoc e) {
238             throw new Exception JavaDoc("Problem getting directory list: "
239                     + e.getMessage());
240         }
241
242         return result;
243     }
244
245     /**
246      * Returns the names bound in the base DN context
247      */

248     public Collection JavaDoc listBaseDN() throws Exception JavaDoc {
249         return list(baseDN);
250     }
251
252     /**
253      * Enumerates the names bound in the named context and return result as JSON
254      */

255     public String JavaDoc listJSON(String JavaDoc name) throws Exception JavaDoc {
256         return listJSON(name, null);
257     }
258
259     /**
260      * Enumerates the names bound in the named context and return result as JSON
261      */

262     public String JavaDoc listJSON(String JavaDoc name, String JavaDoc commonFields) throws Exception JavaDoc {
263         // JSON: [{title:"Title1",isFolder:true}, {title:"Title2"}]
264

265         StringBuffer JavaDoc json = new StringBuffer JavaDoc();
266         List JavaDoc list = (List JavaDoc) list(name);
267
268         json.append('[');
269         int size = list.size();
270         for (int i = 0; i < size; i++) {
271             String JavaDoc[] entry = (String JavaDoc[]) list.get(i);
272             json.append("{title:\"");
273             json.append(entry[0]);
274             json.append("\",widgetId:\"");
275             json.append(entry[1]);
276             json.append("\"");
277             if (commonFields != null) { // TODO: Do additional testing
278
json.append(commonFields);
279             }
280             json.append("}");
281             if ((i + 1) < size) {
282                 json.append(',');
283             }
284         }
285         json.append("]");
286
287         return json.toString();
288     }
289
290     /**
291      * Return the attributes of an LDAP entry
292      */

293     public Collection JavaDoc getAttributes(String JavaDoc name) throws Exception JavaDoc {
294         ArrayList JavaDoc result = new ArrayList JavaDoc();
295         try {
296             Attributes JavaDoc attribs = dirContext.getAttributes(name);
297             NamingEnumeration JavaDoc attributes = attribs.getAll();
298             while (attributes.hasMore()) {
299                 Attribute JavaDoc attribute = (Attribute JavaDoc) attributes.next();
300                 String JavaDoc id = attribute.getID();
301                 NamingEnumeration JavaDoc values = attribute.getAll();
302                 while (values.hasMore()) {
303                     String JavaDoc value = values.next().toString();
304                     String JavaDoc[] pair = { id, value };
305                     result.add(pair);
306                 }
307             }
308         } catch (NamingException JavaDoc e) {
309             throw new Exception JavaDoc("Problem retrieving attributes: "
310                     + e.getMessage());
311         }
312         return result;
313     }
314
315     /**
316      * Execute an LDAP search
317      */

318     public Collection JavaDoc search(String JavaDoc searchDN, String JavaDoc filter, String JavaDoc searchScope)
319             throws Exception JavaDoc {
320         ArrayList JavaDoc result = new ArrayList JavaDoc();
321         try {
322             String JavaDoc ldapURL = createLDAPURL(host, port, searchDN);
323             SearchControls JavaDoc sc = new SearchControls JavaDoc();
324             if (ONELEVEL_SCOPE.equalsIgnoreCase(searchScope)) {
325                 sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
326             } else if (SUBTREE_SCOPE.equalsIgnoreCase(searchScope)) {
327                 sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
328             } else {
329                 // Default to one level scope
330
sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
331             }
332             // Filter: "(objectclass=*)"
333
boolean isSearchDNAdded = false;
334             NamingEnumeration JavaDoc ne = dirContext.search(ldapURL, filter, sc);
335             while (ne.hasMore()) {
336                 SearchResult JavaDoc sr = (SearchResult JavaDoc) ne.next();
337                 String JavaDoc name = sr.getName();
338                 String JavaDoc dn = null;
339                 if (name.length() > 0) {
340                     dn = name + "," + searchDN;
341                     result.add(dn);
342                 } else if ((name.length() == 0) && !isSearchDNAdded) {
343                     dn = searchDN;
344                     result.add(dn);
345                     isSearchDNAdded = true;
346                 }
347             }
348         } catch (NamingException JavaDoc e) {
349             throw new Exception JavaDoc("Problem performing directory search: "
350                     + e.getMessage());
351         }
352         return result;
353     }
354
355     /**
356      * Close directory context
357      */

358     public void close() throws Exception JavaDoc {
359         try {
360             dirContext.close();
361         } catch (NamingException JavaDoc e) {
362             throw new Exception JavaDoc("Problem closing directory context: "
363                     + e.getMessage());
364         }
365     }
366
367     /**
368      * Return base DN of this directory context
369      */

370     public String JavaDoc getBaseDN() {
371         return baseDN;
372     }
373
374     /**
375      * Create an LDAP url using host, port, and base DN
376      */

377     private String JavaDoc createLDAPURL(String JavaDoc host, String JavaDoc port, String JavaDoc baseDN) {
378         StringBuffer JavaDoc url = new StringBuffer JavaDoc();
379         url.append("ldap://");
380         url.append(host);
381         url.append(':');
382         url.append(port);
383         if ((baseDN != null) && (baseDN.length() >= 3)) {
384             if (!baseDN.startsWith("/")) {
385                 url.append('/');
386             }
387             url.append(baseDN);
388         }
389         return url.toString();
390     }
391
392     /**
393      * Get the HTTP session
394      */

395     private HttpSession JavaDoc getSession() {
396         WebContext ctx = WebContextFactory.get();
397         HttpSession JavaDoc session = ctx.getSession();
398         return session;
399     }
400
401     /**
402      * Set an HTTP session attribute
403      */

404     private void setSessionAttribute(String JavaDoc name, Object JavaDoc value) {
405         getSession().setAttribute(name, value);
406     }
407
408     /**
409      * Get an HTTP session attribute
410      */

411     private Object JavaDoc getSessionAttribute(String JavaDoc name) {
412         return getSession().getAttribute(name);
413     }
414
415     /**
416      * Dump HTTP session attributes
417      */

418     private void dumpSession() {
419         System.out.println("--- dumpSession()");
420         WebContext ctx = WebContextFactory.get();
421         HttpSession JavaDoc session = ctx.getSession();
422         Enumeration JavaDoc attribNames = session.getAttributeNames();
423         while (attribNames.hasMoreElements()) {
424             String JavaDoc attribName = (String JavaDoc) attribNames.nextElement();
425             System.out.print("--- session: " + attribName + " = ");
426             Object JavaDoc attribValue = session.getAttribute(attribName);
427             System.out.println(attribValue);
428         }
429     }
430
431     /**
432      * Dump search enumeration
433      */

434     private void printSearchEnumeration(NamingEnumeration JavaDoc ne) {
435         try {
436             while (ne.hasMore()) {
437                 SearchResult JavaDoc sr = (SearchResult JavaDoc) ne.next();
438                 System.out.println("-->" + sr.getName());
439                 System.out.println(sr.getAttributes());
440             }
441         } catch (NamingException JavaDoc e) {
442             e.printStackTrace();
443         }
444     }
445
446 }
447
Popular Tags