KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > security > realm > factory > JResourceLDAP


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2004 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or 1any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * Initial developer: Florent BENOIT
22  * --------------------------------------------------------------------------
23  * $Id: JResourceLDAP.java,v 1.10 2005/04/14 14:24:12 benoitf Exp $
24  * --------------------------------------------------------------------------
25  */

26
27 package org.objectweb.jonas.security.realm.factory;
28
29 import java.security.NoSuchAlgorithmException JavaDoc;
30 import java.text.MessageFormat JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Enumeration JavaDoc;
33 import java.util.Hashtable JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.Vector JavaDoc;
36
37 import javax.naming.AuthenticationException JavaDoc;
38 import javax.naming.Context JavaDoc;
39 import javax.naming.Name JavaDoc;
40 import javax.naming.NameParser JavaDoc;
41 import javax.naming.NamingEnumeration JavaDoc;
42 import javax.naming.NamingException JavaDoc;
43 import javax.naming.Reference JavaDoc;
44 import javax.naming.StringRefAddr JavaDoc;
45 import javax.naming.directory.Attribute JavaDoc;
46 import javax.naming.directory.Attributes JavaDoc;
47 import javax.naming.directory.DirContext JavaDoc;
48 import javax.naming.directory.InitialDirContext JavaDoc;
49 import javax.naming.directory.SearchControls JavaDoc;
50 import javax.naming.directory.SearchResult JavaDoc;
51
52 import org.objectweb.util.monolog.api.BasicLevel;
53
54 import org.objectweb.jonas.security.realm.lib.HashHelper;
55 import org.objectweb.jonas.security.realm.principals.LDAPUser;
56 import org.objectweb.jonas.security.realm.principals.User;
57
58 /**
59  * This class extends the JResource class for the LDAP implementation.
60  * @author Florent Benoit
61  * @author Emmanuel Rias (12/03 some improvements)
62  */

63 public class JResourceLDAP extends JResource implements JResourceLDAPMBean {
64
65     /**
66      * Type of the factory
67      */

68     private static final String JavaDoc FACTORY_TYPE = "org.objectweb.jonas.security.realm.factory.JResourceLDAP";
69
70     /**
71      * Name of the factory
72      */

73     private static final String JavaDoc FACTORY_NAME = "org.objectweb.jonas.security.realm.factory.JResourceLDAPFactory";
74
75     /**
76      * Bind authentication mode. Bind to the ldap server with the l/p given by
77      * the user by the servlet
78      */

79     private static final String JavaDoc BIND_AUTHENTICATION_MODE = "bind";
80
81     /**
82      * Compare authentication mode. Retrieve password from the ldap server with
83      * the given login and compare the password retrived with the password given
84      * by the user
85      */

86     private static final String JavaDoc COMPARE_AUTHENTICATION_MODE = "compare";
87
88     /**
89      * Initial context factory for the LDAp server
90      */

91     private String JavaDoc initialContextFactory = null;
92
93     /**
94      * Url of the ldap server
95      */

96     private String JavaDoc providerUrl = null;
97
98     /**
99      * Type of the authentication used during the authentication to the LDAP
100      * server
101      */

102     private String JavaDoc securityAuthentication = null;
103
104     /**
105      * DN of the Principal(username). He can retrieve the information from the
106      * user
107      */

108     private String JavaDoc securityPrincipal = null;
109
110     /**
111      * Credential(password) of the principal
112      */

113     private String JavaDoc securityCredentials = null;
114
115     /**
116      * Constant that holds the name of the environment property for specifying
117      * the security protocol to use.
118      */

119     private String JavaDoc securityProtocol = null;
120
121     /**
122      * Constant that holds the name of the environment property for specifying
123      * the preferred language to use with the service.
124      */

125     private String JavaDoc language = null;
126
127     /**
128      * Constant that holds the name of the environment property for specifying
129      * how referrals encountered by the service provider are to be processed.
130      */

131     private String JavaDoc referral = null;
132
133     /**
134      * Constant that holds the name of the environment property for specifying
135      * the list of state factories to use.
136      */

137     private String JavaDoc stateFactories = null;
138
139     /**
140      * Mode for validate the authentication (BIND_AUTHENTICATION_MODE or
141      * COMPARE_AUTHENTICATION_MODE)
142      */

143     private String JavaDoc authenticationMode = null;
144
145     /**
146      * Attribute in order to get the password from the ldap server
147      */

148     private String JavaDoc userPasswordAttribute = null;
149
150     /**
151      * Attribute in order to get the user role from the ldap server
152      */

153     private String JavaDoc userRolesAttribute = null;
154
155     /**
156      * Attribute for the role name when performing a lookup on a role
157      */

158     private String JavaDoc roleNameAttribute = null;
159
160     /**
161      * DN used for the lookup
162      */

163     private String JavaDoc baseDN = null;
164
165     /**
166      * DN used when searching the user DN. Override the baseDN if it is defined
167      */

168     private String JavaDoc userDN = null;
169
170     /**
171      * Filter used when searching the user
172      */

173     private String JavaDoc userSearchFilter = null;
174
175     /**
176      * DN used when searching the role DN. Override the baseDN if it is defined
177      */

178     private String JavaDoc roleDN = null;
179
180     /**
181      * Filter used when searching the role
182      */

183     private String JavaDoc roleSearchFilter = null;
184
185     /**
186      * Default algorithm. If specified, the default is not 'clear' password
187      */

188     private String JavaDoc algorithm = null;
189
190     /**
191      * Constructor : use the super constructor
192      * @throws Exception if the super constructor fail
193      */

194     public JResourceLDAP() throws Exception JavaDoc {
195         super();
196     }
197
198     /**
199      * Check if a user is found and return it
200      * @param username the wanted user name
201      * @return the user found or null
202      * @throws JResourceException if there is a NamingException
203      */

204     public User findUser(String JavaDoc username) throws JResourceException {
205
206         // No username. failed
207
if (username == null) {
208             return null;
209         }
210
211         // User to return
212
LDAPUser user = new LDAPUser();
213         user.setName(username);
214         try {
215
216             // Attributes for performing the search
217
DirContext JavaDoc dirContext = getDirContext();
218             SearchControls JavaDoc sctls = new SearchControls JavaDoc();
219
220             String JavaDoc[] attributes = null;
221             if (authenticationMode.equals(COMPARE_AUTHENTICATION_MODE)) {
222                 attributes = new String JavaDoc[] {userPasswordAttribute, userRolesAttribute};
223             } else {
224                 attributes = new String JavaDoc[0];
225             }
226             sctls.setReturningAttributes(attributes);
227             sctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
228
229             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
230                 getLogger().log(BasicLevel.DEBUG, "userDN = '" + userDN + "'");
231                 getLogger().log(BasicLevel.DEBUG, "baseDN = '" + baseDN + "'");
232             }
233
234             String JavaDoc lookupUserDN = null;
235             // DN of the user. If no specific user DN, use the baseDN
236
if (userDN != null && !userDN.equals("")) {
237                 lookupUserDN = userDN.concat(",").concat(baseDN);
238             } else {
239                 lookupUserDN = baseDN;
240             }
241             Object JavaDoc[] arguments = {username};
242             lookupUserDN = MessageFormat.format(lookupUserDN, arguments);
243             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
244                 getLogger().log(BasicLevel.DEBUG, "lookupUserDN = '" + lookupUserDN + "'");
245             }
246
247             // Search the DN with the user filter with the specific argument and
248
// specific search controls
249
if (getLogger().isLoggable(BasicLevel.DEBUG)) {
250                 getLogger().log(BasicLevel.DEBUG, "search : lookupUserDN = '" + lookupUserDN + "', searchFilter = '"
251                         + userSearchFilter + "', username = '" + username + "'");
252             }
253             NamingEnumeration JavaDoc answer = dirContext
254                     .search(lookupUserDN, userSearchFilter, new Object JavaDoc[] {username}, sctls);
255             // No answer
256
if (answer == null || !answer.hasMore()) {
257                 if (getLogger().isLoggable(BasicLevel.DEBUG)) {
258                     if (answer == null) {
259                         getLogger().log(BasicLevel.DEBUG, "answer is null");
260                     } else {
261                         getLogger().log(BasicLevel.DEBUG, "no anwser");
262                     }
263                 }
264                 return null;
265             }
266
267             // Get first answer
268
SearchResult JavaDoc firstAnswer = (SearchResult JavaDoc) answer.next();
269             // More than one answer. Not so good.
270
if (answer.hasMore()) {
271                 return null;
272             }
273
274             // Build full User DN
275
NameParser JavaDoc nameParser = dirContext.getNameParser("");
276             Name JavaDoc contextName = nameParser.parse(dirContext.getNameInNamespace());
277
278             // Add the lookupUserDN to the context name -> baseDN
279
Name JavaDoc baseDNName = contextName.addAll(nameParser.parse(lookupUserDN));
280
281             // Add the uid retrieve from the search to the baseDN --> user DN
282
Name JavaDoc userFullDN = baseDNName.addAll(nameParser.parse(firstAnswer.getName()));
283             user.setDN(userFullDN.toString());
284
285             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
286                 getLogger().log(BasicLevel.DEBUG, "DN found : '" + userFullDN + "'");
287             }
288
289             // Get the user attributes
290
Attributes JavaDoc userAttributes = firstAnswer.getAttributes();
291             if (userAttributes == null) {
292                 if (getLogger().isLoggable(BasicLevel.DEBUG)) {
293                     getLogger().log(BasicLevel.DEBUG, "No user attributes found");
294                 }
295                 return null;
296             }
297
298             String JavaDoc password = null;
299             // Retrieve password if in compare mode
300
if (authenticationMode.equals(COMPARE_AUTHENTICATION_MODE)) {
301                 password = readValueFromAttribute(userPasswordAttribute, userAttributes);
302                 if (password != null) {
303                     user.setPassword(password);
304                 }
305             }
306
307             // Add the roles which are found from the user
308
String JavaDoc roles = readValuesFromAttribute(userRolesAttribute, userAttributes);
309             user.setRoles(roles);
310
311         } catch (javax.naming.NamingException JavaDoc ne) {
312             throw new JResourceException("Could not find user :" + ne.getMessage());
313         }
314         return user;
315     }
316
317     /**
318      * Check if the given user with the given credential is a valid user
319      * @param user the given user
320      * @param credentials credential of the user
321      * @return true if the user is valid
322      */

323     public boolean isValidUser(User user, String JavaDoc credentials) {
324
325         // null password ... can't authenticate
326
if (credentials == null || user == null) {
327             return false;
328         }
329
330         // Choose the right method
331
if (authenticationMode.equals(COMPARE_AUTHENTICATION_MODE)) {
332             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
333                 getLogger().log(BasicLevel.DEBUG, "Compare mode");
334             }
335             return isValidUserCompare(user, credentials);
336         } else if (authenticationMode.equals(BIND_AUTHENTICATION_MODE)) {
337             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
338                 getLogger().log(BasicLevel.DEBUG, "Bind mode");
339             }
340             return isValidUserBind(user, credentials);
341         } else {
342             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
343                 getLogger().log(BasicLevel.DEBUG, "No authentication mode found, return false");
344             }
345             return false;
346         }
347
348     }
349
350     /**
351      * Check if the given user with the given credential is a valid user. Check
352      * is done by binding to the LDAP server with the specific
353      * principal/credential.
354      * @param user the given user
355      * @param credentials credential of the user
356      * @return true if the user is valid
357      */

358     public boolean isValidUserBind(User user, String JavaDoc credentials) {
359
360         // Get the DN of the ldap user
361
if (!(user instanceof LDAPUser)) {
362             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
363                 getLogger().log(BasicLevel.DEBUG, "Not instance of LDAPUser");
364             }
365             return false;
366         }
367
368         String JavaDoc dn = ((LDAPUser) user).getDN();
369         if (dn == null) {
370             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
371                 getLogger().log(BasicLevel.DEBUG, "No DN found in User");
372             }
373             return false;
374         }
375
376         //Make our env
377
Hashtable JavaDoc env = getEnvInitialDirContext();
378         env.put(Context.SECURITY_PRINCIPAL, dn);
379         env.put(Context.SECURITY_CREDENTIALS, credentials);
380
381         boolean validated = false;
382         try {
383             DirContext JavaDoc dirContext = new InitialDirContext JavaDoc(env);
384             validated = true;
385             dirContext.close();
386         } catch (AuthenticationException JavaDoc e) {
387             // not validated
388
getLogger().log(BasicLevel.ERROR, "Can't make an initial dir context : " + e.getMessage());
389         } catch (NamingException JavaDoc ne) {
390             // not validated
391
getLogger().log(BasicLevel.ERROR, "Naming exception " + ne.getMessage());
392         }
393         return validated;
394     }
395
396     /**
397      * Check if the given user with the given credential is a valid user. Check
398      * is done by comparing the given credential with the credential which is
399      * retrieved from the LDAP server.
400      * @param user the given user
401      * @param credentials credential of the user
402      * @return true if the user is valid
403      */

404     public boolean isValidUserCompare(User user, String JavaDoc credentials) {
405
406         boolean validated = false;
407
408         if (user != null && user.getHashPassword() == null) {
409             // Don't use stringbuffer, error case
410
String JavaDoc errMsg = "No password for the user so it cannot perform a check.";
411             errMsg += " Check that you are using the correct mode ('compare' or 'bind').";
412             errMsg += " By using compare mode, the anonymous user cannot retrieved password in many cases.";
413             getLogger().log(BasicLevel.ERROR, errMsg);
414             return validated;
415         }
416
417         //Get algorithm and hashpassword
418
String JavaDoc pass = user.getHashPassword().getPassword();
419         String JavaDoc algo = user.getHashPassword().getAlgorithm();
420
421         // Crypt password ?
422
if (algo != null && pass != null) {
423             try {
424                 validated = HashHelper.hashPassword(credentials, algo).equalsIgnoreCase(pass);
425             } catch (NoSuchAlgorithmException JavaDoc nsae) {
426                 getLogger().log(BasicLevel.ERROR, "Can't make a password with the algorithm " + algo + ". "
427                         + nsae.getMessage());
428             }
429         } else if ((algorithm != null) && (!algorithm.equals(""))) {
430             // Encode password with the specified algorithm (no clear)
431
try {
432                 validated = HashHelper.hashPassword(credentials, algorithm).equalsIgnoreCase(pass);
433             } catch (NoSuchAlgorithmException JavaDoc nsae) {
434                 getLogger().log(BasicLevel.ERROR, "Can't make a password with the algorithm " + algorithm + ". "
435                         + nsae.getMessage());
436             }
437         } else {
438             // clear
439
validated = credentials.equals(pass);
440         }
441         return validated;
442     }
443
444     /**
445      * Get all the roles (from the roles and from the groups) of the given user
446      * @param user the given user
447      * @return the array list of all the roles for a given user
448      * @throws JResourceException if there is a naming exception
449      */

450     public ArrayList JavaDoc getArrayListCombinedRoles(User user) throws JResourceException {
451
452         ArrayList JavaDoc allCombinedRoles = new ArrayList JavaDoc();
453         // Return empty array if user null
454
if (user == null) {
455             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
456                 getLogger().log(BasicLevel.DEBUG, "User is empty, return empty array of roles");
457             }
458             return allCombinedRoles;
459         }
460
461         // Add all user roles found with the user ldap entry
462
String JavaDoc[] userRoles = user.getArrayRoles();
463         for (int r = 0; r < userRoles.length; r++) {
464             String JavaDoc roleName = userRoles[r];
465             if (!allCombinedRoles.contains(roleName)) {
466                 allCombinedRoles.add(roleName);
467             }
468         }
469
470         // Add roles found in ldap
471
if (!(user instanceof LDAPUser)) {
472             return allCombinedRoles;
473         }
474         String JavaDoc dn = ((LDAPUser) user).getDN();
475
476         // No valid info
477
if (dn == null) {
478             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
479                 getLogger().log(BasicLevel.DEBUG, "DN of user is empty, return empty array of roles");
480             }
481             return allCombinedRoles;
482         }
483
484         try {
485             // Attributes for performing the search
486
DirContext JavaDoc dirContext = getDirContext();
487             SearchControls JavaDoc sctls = new SearchControls JavaDoc();
488
489             String JavaDoc[] attributes = new String JavaDoc[] {roleNameAttribute};
490             sctls.setReturningAttributes(attributes);
491             sctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
492             if (getLogger().isLoggable(BasicLevel.DEBUG)) {
493                 getLogger().log(BasicLevel.DEBUG, "roleDN = '" + roleDN + "'");
494                 getLogger().log(BasicLevel.DEBUG, "baseDN = '" + baseDN + "'");
495             }
496
497             // DN of the role. If no specific role DN, use the baseDN
498
String JavaDoc lookupRoleDN = null;
499             if ((roleDN != null) && (!roleDN.equals(""))) {
500                 lookupRoleDN = roleDN.concat(",").concat(baseDN);
501             } else {
502                 lookupRoleDN = baseDN;
503             }
504
505             // Search the DN with the role filter with the specific argument and
506
// specific search controls
507
if (getLogger().isLoggable(BasicLevel.DEBUG)) {
508                 getLogger().log(BasicLevel.DEBUG, "search with lookupRoleDN = '" + lookupRoleDN + "', rolesearchFilter = '"
509                         + roleSearchFilter + "', dn = '" + dn + "'");
510             }
511
512             NamingEnumeration JavaDoc answers = dirContext.search(lookupRoleDN, roleSearchFilter, new Object JavaDoc[] {dn}, sctls);
513
514             if (answers == null) {
515                 if (getLogger().isLoggable(BasicLevel.DEBUG)) {
516                     getLogger().log(BasicLevel.DEBUG, "answer is null");
517                 }
518                 return allCombinedRoles;
519             }
520
521             Vector JavaDoc vRoles = new Vector JavaDoc();
522             while (answers.hasMore()) {
523                 SearchResult JavaDoc answer = (SearchResult JavaDoc) answers.next();
524                 Attributes JavaDoc roleAttributes = answer.getAttributes();
525                 if (roleAttributes == null) {
526                     continue;
527                 }
528                 addValueFromAttributeToVector(roleNameAttribute, roleAttributes, vRoles);
529             }
530
531             for (Enumeration JavaDoc e = vRoles.elements(); e.hasMoreElements();) {
532                 String JavaDoc roleName = (String JavaDoc) e.nextElement();
533                 if (!allCombinedRoles.contains(roleName)) {
534                     allCombinedRoles.add(roleName);
535                 }
536             }
537         } catch (javax.naming.NamingException JavaDoc ne) {
538             throw new JResourceException("Could not find roles from the user :" + ne.getMessage());
539         }
540         user.setCombinedRoles(allCombinedRoles);
541         if (getLogger().isLoggable(BasicLevel.DEBUG)) {
542             StringBuffer JavaDoc rolesStr = new StringBuffer JavaDoc();
543             for (Iterator JavaDoc it = allCombinedRoles.iterator(); it.hasNext();) {
544                 rolesStr.append((String JavaDoc) it.next());
545                 rolesStr.append(",");
546             }
547             getLogger().log(BasicLevel.DEBUG, "Roles are : " + rolesStr + " for user '" + user.getName() + "'");
548         }
549
550         return allCombinedRoles;
551     }
552
553     /**
554      * String representation of the LDAP realm
555      * @return the xml representation of the LDAP realm
556      */

557     public String JavaDoc toXML() {
558
559         // Required values
560

561         StringBuffer JavaDoc xml = new StringBuffer JavaDoc(" <ldaprealm name=\"");
562         xml.append(getName());
563
564         xml.append("\"\n baseDN=\"");
565         if (baseDN != null) {
566             xml.append(baseDN);
567         }
568
569         if ((initialContextFactory != null) && (!initialContextFactory.equals(""))) {
570             xml.append("\"\n initialContextFactory=\"");
571             xml.append(initialContextFactory);
572         }
573
574         if ((providerUrl != null) && (!providerUrl.equals(""))) {
575             xml.append("\"\n providerUrl=\"");
576             xml.append(providerUrl);
577         }
578
579         if ((securityAuthentication != null) && (!securityAuthentication.equals(""))) {
580             xml.append("\"\n securityAuthentication=\"");
581             xml.append(securityAuthentication);
582         }
583
584         if ((securityPrincipal != null) && (!securityPrincipal.equals(""))) {
585             xml.append("\"\n securityPrincipal=\"");
586             xml.append(securityPrincipal);
587         }
588
589         if ((securityCredentials != null) && (!securityCredentials.equals(""))) {
590             xml.append("\"\n securityCredentials=\"");
591             xml.append(securityCredentials);
592         }
593
594         if ((authenticationMode != null) && (!authenticationMode.equals(""))) {
595             xml.append("\"\n authenticationMode=\"");
596             xml.append(authenticationMode);
597         }
598
599         if ((userPasswordAttribute != null) && (!userPasswordAttribute.equals(""))) {
600             xml.append("\"\n userPasswordAttribute=\"");
601             xml.append(userPasswordAttribute);
602         }
603
604         if ((userRolesAttribute != null) && (!userRolesAttribute.equals(""))) {
605             xml.append("\"\n userRolesAttribute=\"");
606             xml.append(userRolesAttribute);
607         }
608
609         if ((roleNameAttribute != null) && (!roleNameAttribute.equals(""))) {
610             xml.append("\"\n roleNameAttribute=\"");
611             xml.append(roleNameAttribute);
612         }
613
614         if ((userDN != null) && (!userDN.equals(""))) {
615             xml.append("\"\n userDN=\"");
616             xml.append(userDN);
617         }
618
619         if ((userSearchFilter != null) && (!userSearchFilter.equals(""))) {
620             xml.append("\"\n userSearchFilter=\"");
621             xml.append(userSearchFilter);
622         }
623
624         if ((roleDN != null) && (!roleDN.equals(""))) {
625             xml.append("\"\n roleDN=\"");
626             xml.append(roleDN);
627         }
628
629         if ((roleSearchFilter != null) && (!roleSearchFilter.equals(""))) {
630             xml.append("\"\n roleSearchFilter=\"");
631             xml.append(roleSearchFilter);
632         }
633
634         // Optional values
635
if ((securityProtocol != null) && (!securityProtocol.equals(""))) {
636             xml.append("\"\n securityProtocol=\"");
637             xml.append(securityProtocol);
638         }
639
640         if ((language != null) && (!language.equals(""))) {
641             xml.append("\"\n language=\"");
642             xml.append(language);
643         }
644
645         if ((referral != null) && (!referral.equals(""))) {
646             xml.append("\"\n referral=\"");
647             xml.append(referral);
648         }
649
650         if ((stateFactories != null) && (!stateFactories.equals(""))) {
651             xml.append("\"\n stateFactories=\"");
652             xml.append(stateFactories);
653         }
654
655         if ((algorithm != null) && (!algorithm.equals(""))) {
656             xml.append("\"\n algorithm=\"");
657             xml.append(algorithm);
658         }
659
660         xml.append("\" />");
661
662         return xml.toString();
663     }
664
665     /**
666      * The string representation of this object is an XML value
667      * @return the xml representation of this object
668      */

669     public String JavaDoc toString() {
670         return this.toXML();
671     }
672
673     /**
674      * Retrieves the Reference of the object. The Reference contains the factory
675      * used to create this object and the optional parameters used to configure
676      * the factory.
677      * @return the non-null Reference of the object.
678      * @throws NamingException if a naming exception was encountered while
679      * retrieving the reference.
680      */

681     public Reference JavaDoc getReference() throws NamingException JavaDoc {
682
683         // Build the reference to the factory FACTORY_TYPE
684
Reference JavaDoc reference = new Reference JavaDoc(FACTORY_TYPE, FACTORY_NAME, null);
685
686         // Add ref addr
687
reference.add(new StringRefAddr JavaDoc("name", getName()));
688         reference.add(new StringRefAddr JavaDoc("initialContextFactory", getInitialContextFactory()));
689         reference.add(new StringRefAddr JavaDoc("providerUrl", getProviderUrl()));
690         reference.add(new StringRefAddr JavaDoc("securityAuthentication", getSecurityAuthentication()));
691         reference.add(new StringRefAddr JavaDoc("securityPrincipal", getSecurityPrincipal()));
692         reference.add(new StringRefAddr JavaDoc("securityCredentials", getSecurityCredentials()));
693         reference.add(new StringRefAddr JavaDoc("securityProtocol", getSecurityProtocol()));
694         reference.add(new StringRefAddr JavaDoc("language", getLanguage()));
695         reference.add(new StringRefAddr JavaDoc("referral", getReferral()));
696         reference.add(new StringRefAddr JavaDoc("stateFactories", getStateFactories()));
697         reference.add(new StringRefAddr JavaDoc("authenticationMode", getAuthenticationMode()));
698         reference.add(new StringRefAddr JavaDoc("userPasswordAttribute", getUserPasswordAttribute()));
699         reference.add(new StringRefAddr JavaDoc("userRolesAttribute", getUserRolesAttribute()));
700         reference.add(new StringRefAddr JavaDoc("roleNameAttribute", getRoleNameAttribute()));
701         reference.add(new StringRefAddr JavaDoc("baseDN", getBaseDN()));
702         reference.add(new StringRefAddr JavaDoc("userDN", getUserDN()));
703         reference.add(new StringRefAddr JavaDoc("userSearchFilter", getUserSearchFilter()));
704         reference.add(new StringRefAddr JavaDoc("roleDN", getRoleDN()));
705         reference.add(new StringRefAddr JavaDoc("roleSearchFilter", getRoleSearchFilter()));
706         reference.add(new StringRefAddr JavaDoc("algorithm", algorithm));
707
708         return reference;
709     }
710
711
712     /**
713      * Set the initial context factory of this LDAP realm
714      * @param initialContextFactory the initial context factory
715      */

716     public void setInitialContextFactory(String JavaDoc initialContextFactory) {
717         this.initialContextFactory = initialContextFactory;
718     }
719
720     /**
721      * Set the Url of the ldap server of this LDAP realm
722      * @param providerUrl Url of the ldap server
723      */

724     public void setProviderUrl(String JavaDoc providerUrl) {
725         this.providerUrl = providerUrl;
726     }
727
728     /**
729      * Set the authentication used during the authentication to the LDAP server
730      * of this LDAP realm
731      * @param securityAuthentication authentication used during the
732      * authentication to the LDAP server
733      */

734     public void setSecurityAuthentication(String JavaDoc securityAuthentication) {
735         this.securityAuthentication = securityAuthentication;
736     }
737
738     /**
739      * Set the DN of the Principal(username) of this LDAP realm
740      * @param securityPrincipal DN of the Principal(username)
741      */

742     public void setSecurityPrincipal(String JavaDoc securityPrincipal) {
743         this.securityPrincipal = securityPrincipal;
744     }
745
746     /**
747      * Set the Credential(password) of the principal of this LDAP realm
748      * @param securityCredentials Credential(password) of the principal
749      */

750     public void setSecurityCredentials(String JavaDoc securityCredentials) {
751         this.securityCredentials = securityCredentials;
752     }
753
754     /**
755      * Set the security protocol to use of this LDAP realm
756      * @param securityProtocol security protocol to use
757      */

758     public void setSecurityProtocol(String JavaDoc securityProtocol) {
759         this.securityProtocol = securityProtocol;
760     }
761
762     /**
763      * Set the preferred language to use with the service of this LDAP realm
764      * @param language preferred language to use with the service
765      */

766     public void setLanguage(String JavaDoc language) {
767         this.language = language;
768     }
769
770     /**
771      * Set how referrals encountered by the service provider are to be processed
772      * @param referral how referrals encountered by the service provider are to
773      * be processed
774      */

775     public void setReferral(String JavaDoc referral) {
776         this.referral = referral;
777     }
778
779     /**
780      * Set the the list of state factories of this LDAP realm
781      * @param stateFactories list of state factories
782      */

783     public void setStateFactories(String JavaDoc stateFactories) {
784         this.stateFactories = stateFactories;
785     }
786
787     /**
788      * Set the mode for validate the authentication of this LDAP realm
789      * @param authenticationMode BIND_AUTHENTICATION_MODE or
790      * COMPARE_AUTHENTICATION_MODE
791      */

792     public void setAuthenticationMode(String JavaDoc authenticationMode) {
793         this.authenticationMode = authenticationMode;
794     }
795
796     /**
797      * Set the attribute in order to get the password of this LDAP realm
798      * @param userPasswordAttribute attribute in order to get the password of
799      * this LDAP realm
800      */

801     public void setUserPasswordAttribute(String JavaDoc userPasswordAttribute) {
802         this.userPasswordAttribute = userPasswordAttribute;
803     }
804
805     /**
806      * Set the attribute in order to get the user role from the ldap server
807      * @param userRolesAttribute attribute in order to get the user role from
808      * the ldap server
809      */

810     public void setUserRolesAttribute(String JavaDoc userRolesAttribute) {
811         this.userRolesAttribute = userRolesAttribute;
812     }
813
814     /**
815      * Set the role name when performing a lookup on a role
816      * @param roleNameAttribute role name when performing a lookup on a role
817      */

818     public void setRoleNameAttribute(String JavaDoc roleNameAttribute) {
819         this.roleNameAttribute = roleNameAttribute;
820     }
821
822     /**
823      * Set the DN used for the lookup of this LDAP realm
824      * @param baseDN DN used for the lookup
825      */

826     public void setBaseDN(String JavaDoc baseDN) {
827         // empty value can't be set
828
if ((baseDN != null) && (!baseDN.equals(""))) {
829             this.baseDN = baseDN;
830         }
831     }
832
833     /**
834      * Set the DN used when searching the user DN. Override the baseDN if it is
835      * defined
836      * @param userDN DN used when searching the user DN
837      */

838     public void setUserDN(String JavaDoc userDN) {
839         if ((userDN != null) && (!userDN.equals(""))) {
840             this.userDN = userDN;
841         }
842     }
843
844     /**
845      * Set the filter used when searching the user
846      * @param userSearchFilter filter used when searching the user
847      */

848     public void setUserSearchFilter(String JavaDoc userSearchFilter) {
849         this.userSearchFilter = userSearchFilter;
850     }
851
852     /**
853      * Set the DN used when searching the role DN. Override the baseDN if it is
854      * defined
855      * @param roleDN DN used when searching the role DN. Override the baseDN if
856      * it is defined
857      */

858     public void setRoleDN(String JavaDoc roleDN) {
859         this.roleDN = roleDN;
860     }
861
862     /**
863      * Set the filter used when searching the role
864      * @param roleSearchFilter filter used when searching the role
865      */

866     public void setRoleSearchFilter(String JavaDoc roleSearchFilter) {
867         this.roleSearchFilter = roleSearchFilter;
868     }
869
870     /**
871      * Set the default algorithm to use
872      * @param algorithm algorithm to be used
873      */

874     public void setAlgorithm(String JavaDoc algorithm) {
875         this.algorithm = algorithm;
876     }
877
878     /**
879      * Return the initial context factory of this LDAP realm
880      * @return the initial context factory
881      */

882     public String JavaDoc getInitialContextFactory() {
883         return initialContextFactory;
884     }
885
886     /**
887      * Get the Url of the ldap server of this LDAP realm
888      * @return Url of the ldap server
889      */

890     public String JavaDoc getProviderUrl() {
891         return providerUrl;
892     }
893
894     /**
895      * Get the authentication used during the authentication to the LDAP server
896      * of this LDAP realm
897      * @return authentication used during the authentication to the LDAP server
898      */

899     public String JavaDoc getSecurityAuthentication() {
900         return securityAuthentication;
901     }
902
903     /**
904      * Get the DN of the Principal(username) of this LDAP realm
905      * @return DN of the Principal(username)
906      */

907     public String JavaDoc getSecurityPrincipal() {
908         return securityPrincipal;
909     }
910
911     /**
912      * Get the Credential(password) of the principal of this LDAP realm
913      * @return Credential(password) of the principal
914      */

915     public String JavaDoc getSecurityCredentials() {
916         return securityCredentials;
917     }
918
919     /**
920      * Get the security protocol to use of this LDAP realm
921      * @return security protocol to use
922      */

923     public String JavaDoc getSecurityProtocol() {
924         return securityProtocol;
925     }
926
927     /**
928      * Get the preferred language to use with the service of this LDAP realm
929      * @return language preferred language to use with the service
930      */

931     public String JavaDoc getLanguage() {
932         return language;
933     }
934
935     /**
936      * Get how referrals encountered by the service provider are to be processed
937      * @return how referrals encountered by the service provider are to be
938      * processed
939      */

940     public String JavaDoc getReferral() {
941         return referral;
942     }
943
944     /**
945      * Get the the list of state factories of this LDAP realm
946      * @return list of state factories
947      */

948     public String JavaDoc getStateFactories() {
949         return stateFactories;
950     }
951
952     /**
953      * Get the mode for validate the authentication of this LDAP realm
954      * @return BIND_AUTHENTICATION_MODE or COMPARE_AUTHENTICATION_MODE
955      */

956     public String JavaDoc getAuthenticationMode() {
957         return authenticationMode;
958     }
959
960     /**
961      * Get the attribute in order to get the password of this LDAP realm
962      * @return attribute in order to get the password of this LDAP realm
963      */

964     public String JavaDoc getUserPasswordAttribute() {
965         return userPasswordAttribute;
966     }
967
968     /**
969      * Get the attribute in order to get the user role from the ldap server
970      * @return attribute in order to get the user role from the ldap server
971      */

972     public String JavaDoc getUserRolesAttribute() {
973         return userRolesAttribute;
974     }
975
976     /**
977      * Get the role name when performing a lookup on a role
978      * @return role name when performing a lookup on a role
979      */

980     public String JavaDoc getRoleNameAttribute() {
981         return roleNameAttribute;
982     }
983
984     /**
985      * Get the DN used for the lookup of this LDAP realm
986      * @return baseDN DN used for the lookup
987      */

988     public String JavaDoc getBaseDN() {
989         return baseDN;
990     }
991
992     /**
993      * Get the DN used when searching the user DN. Override the baseDN if it is
994      * defined
995      * @return userDN DN used when searching the user DN
996      */

997     public String JavaDoc getUserDN() {
998         return userDN;
999     }
1000
1001    /**
1002     * Get the filter used when searching the user
1003     * @return userSearchFilter filter used when searching the user
1004     */

1005    public String JavaDoc getUserSearchFilter() {
1006        return userSearchFilter;
1007    }
1008
1009    /**
1010     * Get the DN used when searching the role DN. Override the baseDN if it is
1011     * defined
1012     * @return roleDN DN used when searching the role DN. Override the baseDN if
1013     * it is defined
1014     */

1015    public String JavaDoc getRoleDN() {
1016        return roleDN;
1017    }
1018
1019    /**
1020     * Get the filter used when searching the role
1021     * @return roleSearchFilter filter used when searching the role
1022     */

1023    public String JavaDoc getRoleSearchFilter() {
1024        return roleSearchFilter;
1025    }
1026
1027    /**
1028     * Get the default algorithm
1029     * @return the default algorithm
1030     */

1031    public String JavaDoc getAlgorithm() {
1032        return algorithm;
1033    }
1034
1035    /**
1036     * Return a dircontext for this LDAP server
1037     * @return a dircontext for this LDAP server
1038     * @throws NamingException if we can't retrieve a DirContext
1039     */

1040    protected DirContext JavaDoc getDirContext() throws NamingException JavaDoc {
1041        DirContext JavaDoc dirContext = null;
1042        // Get the InitialDirContext with our env
1043
dirContext = new InitialDirContext JavaDoc(getEnvInitialDirContext());
1044
1045        return dirContext;
1046    }
1047
1048    /**
1049     * Return the environment used to build a DirContext
1050     * @return the environment used to build a DirContext
1051     */

1052    private Hashtable JavaDoc getEnvInitialDirContext() {
1053
1054        // The environment is a hashtable
1055
Hashtable JavaDoc env = new Hashtable JavaDoc();
1056        env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
1057        env.put(Context.PROVIDER_URL, providerUrl);
1058        env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);
1059        if ((securityPrincipal != null) && (!securityPrincipal.equals(""))) {
1060            env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
1061        }
1062        if ((securityCredentials != null) && (!securityCredentials.equals(""))) {
1063            env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
1064        }
1065        if ((language != null) && (!language.equals(""))) {
1066            env.put(Context.LANGUAGE, language);
1067        }
1068        if ((referral != null) && (!referral.equals(""))) {
1069            env.put(Context.REFERRAL, referral);
1070        }
1071        if ((securityProtocol != null) && (!securityProtocol.equals(""))) {
1072            env.put(Context.SECURITY_PROTOCOL, securityProtocol);
1073        }
1074        if ((stateFactories != null) && (!stateFactories.equals(""))) {
1075            env.put(Context.STATE_FACTORIES, stateFactories);
1076        }
1077        return env;
1078    }
1079
1080    /**
1081     * Return the string value read into the attributes attributes with the key
1082     * attrID
1083     * @param attrID the key that we are looking for
1084     * @param attributes all the attributes
1085     * @return the string value read into the attributes attributes with the key
1086     * attrID
1087     * @throws NamingException if the attrID can't be read from the attributes
1088     */

1089    private String JavaDoc readValueFromAttribute(String JavaDoc attrID, Attributes JavaDoc attributes) throws NamingException JavaDoc {
1090
1091        // No attributes or the attrID is null (must be a non null attribute)
1092
if (attributes == null || attrID == null) {
1093            return null;
1094        }
1095
1096        Attribute JavaDoc attribute = attributes.get(attrID);
1097
1098        // Attribute not found
1099
if (attribute == null) {
1100            return null;
1101        }
1102
1103        Object JavaDoc o = attribute.get();
1104        String JavaDoc value = null;
1105
1106        if (o instanceof byte[]) {
1107            value = new String JavaDoc((byte[]) o);
1108        } else {
1109            value = o.toString();
1110        }
1111
1112        return value;
1113    }
1114
1115    /**
1116     * Return a comma separated string with the values read into the attributes
1117     * attributes with the key attrID
1118     * @param attrID the key that we are looking for
1119     * @param attributes all the attributes
1120     * @return comma separated string with the values read into the attributes
1121     * attributes with the key attrID
1122     * @throws NamingException if the attrID can't be read from the attributes
1123     */

1124    private String JavaDoc readValuesFromAttribute(String JavaDoc attrID, Attributes JavaDoc attributes) throws NamingException JavaDoc {
1125
1126        // No attributes or the attrID is null (must be a non null attribute)
1127
if (attributes == null || attrID == null) {
1128            return null;
1129        }
1130
1131        Attribute JavaDoc attribute = attributes.get(attrID);
1132
1133        // Attribute not found
1134
if (attribute == null) {
1135            return null;
1136        }
1137
1138        String JavaDoc value = null;
1139        NamingEnumeration JavaDoc e = attribute.getAll();
1140        while (e.hasMore()) {
1141            String JavaDoc s = (String JavaDoc) e.next();
1142            if (value == null) {
1143                value = s;
1144            } else {
1145                value = value + "," + s;
1146            }
1147        }
1148        return value;
1149    }
1150
1151    /**
1152     * Add to a vector the values retrieved from the attributes with the
1153     * keyattrID
1154     * @param attrID the key that we are looking for
1155     * @param attributes all the attributes
1156     * @param v the vector on which the data are added
1157     * @throws NamingException if the attrID can't be read from the attributes
1158     */

1159    private void addValueFromAttributeToVector(String JavaDoc attrID, Attributes JavaDoc attributes, Vector JavaDoc v) throws NamingException JavaDoc {
1160
1161        // No attributes or the attrID is null (must be a non null attribute)
1162
if (attributes == null || attrID == null) {
1163            return;
1164        }
1165
1166        Attribute JavaDoc attribute = attributes.get(attrID);
1167
1168        // Attribute not found
1169
if (attribute == null) {
1170            return;
1171        }
1172
1173        NamingEnumeration JavaDoc e = attribute.getAll();
1174        while (e.hasMore()) {
1175            v.add(e.next());
1176        }
1177
1178    }
1179
1180    /**
1181     * Remove all the Mbeans used by this resource
1182     * @throws JResourceException if the MBeans can not be removed
1183     */

1184    public void removeMBeans() throws JResourceException {
1185        //no MBeans
1186
}
1187
1188}
Popular Tags