KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hero > session > BnLdapBean


1 /**
2  *
3  * Bonita
4  * Copyright (C) 1999 Bull S.A.
5  * Bull 68 route de versailles 78434 Louveciennes Cedex France
6  * Further information: bonita@objectweb.org
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21  * USA
22  *
23  *
24 --------------------------------------------------------------------------
25  * $Id: BnLdapBean.java,v 1.5 2005/04/18 13:51:12 mvaldes Exp $
26  *
27 --------------------------------------------------------------------------
28  */

29
30 package hero.session;
31 import javax.ejb.EJBException JavaDoc;
32 import javax.ejb.SessionBean JavaDoc;
33 import javax.ejb.SessionContext JavaDoc;
34 import javax.naming.Context JavaDoc;
35 import javax.naming.InitialContext JavaDoc;
36 import javax.naming.NamingException JavaDoc;
37 import java.util.*;
38 import java.text.MessageFormat JavaDoc;
39 // added for jndi/ldap
40
import javax.naming.*;
41 import javax.naming.directory.*;
42
43 // added for Mejb manage
44
import javax.rmi.PortableRemoteObject JavaDoc;
45 import hero.util.HeroException;
46 // JMX
47
import javax.management.ObjectName JavaDoc;
48 import javax.management.InstanceNotFoundException JavaDoc;
49 import javax.management.Query JavaDoc;
50
51 // J2EE management imports
52
import javax.management.j2ee.ManagementHome JavaDoc;
53 import javax.management.j2ee.Management JavaDoc;
54
55 // For bonita Beans
56
import java.rmi.RemoteException JavaDoc;
57 import hero.interfaces.UserRegistrationLocalHome;
58 import hero.interfaces.UserRegistrationLocal;
59 import hero.interfaces.UserRegistrationUtil;
60
61 import hero.interfaces.ProjectSessionLocalHome;
62 import hero.interfaces.ProjectSessionLocal;
63 import hero.interfaces.ProjectSessionUtil;
64
65 import hero.interfaces.UserSessionLocalHome;
66 import hero.interfaces.UserSessionLocal;
67 import hero.interfaces.UserSessionUtil;
68
69 import hero.util.HeroException;
70 import javax.ejb.CreateException JavaDoc;
71
72
73 /**
74  * @ejb:bean name="BnLdap"
75  * display-name="BnLdap Bean"
76  * type="Stateless"
77  * transaction-type="Container"
78  * jndi-name="ejb/hero/BnLdap"
79  * local-jndi-name="ejb/hero/BnLdap_L"
80  *
81  * @ejb:ejb-ref ejb-name="BnLdap"
82  * ref-name="myhero/BnLdap"
83  *
84  * @ejb.ejb-external-ref
85  * view-type="remote"
86  * ref-name="ejb/mgmt/MEJB"
87  * type="Session"
88  * home="javax.management.j2ee.ManagementHome"
89  * remote="javax.management.j2ee.Management"
90  *
91  * @jonas.ejb-ref ejb-ref-name="ejb/mgmt/MEJB"
92  * jndi-name="ejb/mgmt/MEJB"
93  * @ejb.permission role-name="BONITAUSER,user,SuperAdmin"
94  * @ejb:transaction type="Required"
95  * @ejb:transaction-type type="Container"
96   * @jonas.bean
97  * ejb-name="BnLdap"
98  * jndi-name="ejb/hero/BnLdap"
99  *
100  **/

101
102 public class BnLdapBean implements SessionBean JavaDoc {
103
104     private String JavaDoc ldapRealmName = null;
105     private SessionContext JavaDoc sessionContext = null;
106     
107         String JavaDoc baseDn = "";
108         String JavaDoc initialContextFactory = "";
109         String JavaDoc providerUrl = "";
110         String JavaDoc authenticationMode = "";
111         String JavaDoc securityAuthentication = "";
112         String JavaDoc securityPrincipal = "";
113         String JavaDoc securityCredentials = "";
114         String JavaDoc referral = "";
115         String JavaDoc roleDN = "";
116         String JavaDoc roleNameAttribute = "";
117         String JavaDoc roleSearchFilter = "";
118         String JavaDoc userDN = "";
119         String JavaDoc userPasswordAttribute = "";
120         String JavaDoc userRolesAttribute = "";
121         String JavaDoc userSearchFilter = "";
122     
123     /** The directory server connection */
124     private DirContext dirContext = null;
125     
126     /**
127     * Internal Enterprise Java Beans method.
128     **/

129         public void setSessionContext(SessionContext JavaDoc ctx) {
130         sessionContext = ctx;
131         
132         Context JavaDoc initialContext = null;
133             try{
134                 initialContext = new InitialContext JavaDoc();
135         } catch (Exception JavaDoc e) {e.printStackTrace();
136             System.err.println("Cannot get initial context for JNDI: " + e);
137         }
138
139         // --------------
140
// Access to MEJB
141
// --------------
142

143         // Connecting to the MEJB home through JNDI
144
ManagementHome JavaDoc mgmtHome = null;
145         try {
146             mgmtHome = (ManagementHome JavaDoc) PortableRemoteObject.narrow(initialContext.lookup("java:comp/env/ejb/mgmt/MEJB"), ManagementHome JavaDoc.class);
147         }
148         catch (Exception JavaDoc e) {e.printStackTrace();
149             System.err.println("Cannot lookup java:comp/env/ejb/mgmt/MEJB: " + e);
150             return;
151         }
152         // Management bean creation
153
Management JavaDoc mgmt = null;
154         try {
155             mgmt = mgmtHome.create();
156             System.out.println("MEJB created");
157         }
158         catch (Exception JavaDoc e) {e.printStackTrace();
159             System.err.println("Error creating MEJB: " + e );
160         }
161
162         // -------------------------------------------------------
163
// Access to the J2EEDomain MBean for ldap securityfactory
164
// -------------------------------------------------------
165

166         System.out.println("Access the J2EEDomain MBean");
167         ObjectName JavaDoc objectName = null;
168         
169         // get the default domain
170
String JavaDoc defaultDomain ="";
171         try {
172         defaultDomain = mgmt.getDefaultDomain();
173         }
174         catch (Exception JavaDoc e) {
175             System.err.println("Cannot create MEJB: " + e );
176         }
177         
178         //Check that there's only one Ldap realm defined in the JOnAS configuration
179
try {
180         ObjectName JavaDoc searchpattern = new ObjectName JavaDoc(defaultDomain + ":type=securityfactory,subtype=ldap,*");
181         Query JavaDoc q = new Query JavaDoc();
182         Set managedObject = mgmt.queryNames(searchpattern,null);
183          
184         if ((managedObject.size()) > 1) {
185             System.err.println("Error detected in JOnAS configuration:");
186             System.err.println("More than 1 Ldap realms has been defined");
187             Iterator itr = managedObject.iterator();
188             while (itr.hasNext()) {
189                 ObjectName JavaDoc name = (ObjectName JavaDoc)itr.next();
190                 System.out.println(name.toString());
191             }
192         throw new RemoteException JavaDoc("More than 1 Ldap realms has been defined");
193                  
194         } // end if
195
else if ((managedObject.size()) == 0) {
196         System.err.println("Error detected in JOnAS configuration:");
197         System.err.println("No ldap configuration has been defined.");
198         throw new RemoteException JavaDoc("0 Ldap realms has been defined");
199         }
200         else {
201             // The right case ! One ldap config defined !
202
Iterator itr = managedObject.iterator();
203             while (itr.hasNext()) {
204                 objectName = (ObjectName JavaDoc)itr.next();
205                 System.out.println("1 Ldap realm name detected in JOnAS configuration:");
206                 System.out.println(objectName.toString());
207                 
208             }
209         }
210         
211         }catch (Exception JavaDoc e) {
212             System.err.println("Error checking ldap objectName: " + e );
213         }
214                
215     if (objectName != null){
216         // Get the values of attributes of the the MBean for ldap securityfactory
217
try {
218             boolean exists = mgmt.isRegistered(objectName);
219             if (exists) {
220 //System.out.println("J2EEDomain managed object registered in the current MBean server");
221

222                 //BaseDN
223
if (mgmt.getAttribute(objectName, "BaseDN")!=null) baseDn = mgmt.getAttribute(objectName, "BaseDN").toString();
224         else baseDn ="";
225 //System.out.println("BaseDN = " + baseDn);
226

227         // InitialContextFactory
228
if (mgmt.getAttribute(objectName, "InitialContextFactory")!=null) initialContextFactory = mgmt.getAttribute(objectName, "InitialContextFactory").toString();
229         else initialContextFactory ="";
230 //System.out.println("initialContextFactory = " + initialContextFactory);
231

232         //ProviderUrl
233
if (mgmt.getAttribute(objectName, "ProviderUrl")!=null) providerUrl = mgmt.getAttribute(objectName, "ProviderUrl").toString();
234         else providerUrl ="";
235 //System.out.println("providerUrl = " + providerUrl);
236

237         //SecurityAuthentication
238
if (mgmt.getAttribute(objectName, "SecurityAuthentication")!=null) securityAuthentication = mgmt.getAttribute(objectName, "SecurityAuthentication").toString();
239         else securityAuthentication ="";
240 //System.out.println("securityAuthentication = " + securityAuthentication);
241

242         //SecurityPrincipal
243
if (mgmt.getAttribute(objectName, "SecurityPrincipal")!=null) securityPrincipal = mgmt.getAttribute(objectName, "SecurityPrincipal").toString();
244         else securityPrincipal ="";
245 //System.out.println("securityPrincipal = " + securityPrincipal);
246

247         //SecurityCredentials
248
if (mgmt.getAttribute(objectName, "SecurityCredentials")!=null) securityCredentials = mgmt.getAttribute(objectName, "SecurityCredentials").toString();
249         else securityCredentials ="";
250 //System.out.println("securityCredentials = " + securityCredentials);
251

252         // RoleDN
253
if (mgmt.getAttribute(objectName, "RoleDN")!=null) roleDN = mgmt.getAttribute(objectName, "RoleDN").toString();
254         else roleDN ="";
255 //System.out.println("roleDN = " + roleDN);
256

257         //RoleNameAttribute
258
if (mgmt.getAttribute(objectName, "RoleNameAttribute")!=null) roleNameAttribute = mgmt.getAttribute(objectName, "RoleNameAttribute").toString();
259         else roleNameAttribute ="";
260 //System.out.println("roleNameAttribute = " + roleNameAttribute);
261

262         //RoleSearchFilter
263
if (mgmt.getAttribute(objectName, "RoleSearchFilter")!=null) roleSearchFilter = mgmt.getAttribute(objectName, "RoleSearchFilter").toString();
264         else roleSearchFilter ="";
265 //System.out.println("roleSearchFilter = " + roleSearchFilter);
266

267         //UserDN
268
if (mgmt.getAttribute(objectName, "UserDN")!=null) userDN = mgmt.getAttribute(objectName, "UserDN").toString();
269         else userDN ="";
270 //System.out.println("userDN = " + userDN);
271

272         //UserPasswordAttribute
273
if (mgmt.getAttribute(objectName, "UserPasswordAttribute")!=null) userPasswordAttribute = mgmt.getAttribute(objectName, "UserPasswordAttribute").toString();
274         else userPasswordAttribute ="";
275 //System.out.println("userPasswordAttribute = " + userPasswordAttribute);
276

277         //UserRolesAttribute
278
if (mgmt.getAttribute(objectName, "UserRolesAttribute")!=null) userRolesAttribute = mgmt.getAttribute(objectName, "UserRolesAttribute").toString();
279         else userRolesAttribute ="";
280 //System.out.println("userRolesAttribute = " + userRolesAttribute);
281

282         //UserSearchFilter
283
if (mgmt.getAttribute(objectName, "UserSearchFilter")!=null) userSearchFilter = mgmt.getAttribute(objectName, "UserSearchFilter").toString();
284         else userSearchFilter ="";
285 //System.out.println("userSearchFilter = " + userSearchFilter);
286

287         // optional : Referral (parameter value = "throw")
288
if (mgmt.getAttribute(objectName, "Referral")!=null) referral = mgmt.getAttribute(objectName, "Referral").toString();
289         else referral ="";
290 //System.out.println("referral = " + referral);
291
}
292             else {
293                 System.out.println("Can't find J2EEDomain managed object having the above name in the current MBean server");
294                 return;
295             }
296         }
297         catch (Exception JavaDoc e) {
298             System.err.println("Error when using the J2EEDomain managed object: " + e);
299             return;
300         }
301     }
302             
303     }
304
305     /**
306      * Import users from the LDAP used for authentication by the Application Server
307      * to Bonita database.
308      * For each user found in LDAP:
309      * - if it doesn't exists in bonita database then this user is created
310      * - if it exists in bonita database then the mail property is updated.
311      * It requires that the ldap resource within the AS. is configured and activated.
312      *
313      * @ejb:interface-method view-type="both"
314      * @ejb:transaction type="Required"
315      * @throws HeroException
316      *
317     **/

318     public void importLdapUsers()throws HeroException{
319         
320
321        String JavaDoc userId ="";
322        String JavaDoc email = "";
323        UserRegistrationLocalHome userRegistrationh=null;
324        UserRegistrationLocal userRegistration=null;
325        
326        UserSessionLocalHome userSessionh=null;
327        UserSessionLocal userSession=null;
328
329        // Initialize the InitialContext passed on the
330
// connection parameters
331
Hashtable env = new Hashtable();
332         
333        env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
334        env.put(Context.PROVIDER_URL, providerUrl);
335        env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);
336        env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
337        env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
338        env.put(Context.REFERRAL, referral);
339        
340          try
341            {
342            dirContext = new InitialDirContext(env);
343            }
344        catch (NamingException JavaDoc e)
345            {
346                    System.err.println("cannot initialize the initialContext of naming" + e);
347                    throw new EJBException JavaDoc("cannot initialize the initialContext of naming");
348            }
349            
350         // Get users into ldap and Bonita database to be able to compare ...
351
Map map = null;
352         Collection bnUsersCol = null;
353        try {
354         map = getTreeMapUidMailLdap();
355        } catch (Exception JavaDoc e){
356        throw new HeroException("Error getting users from LDAP " + e.getMessage());
357       }
358         try {
359         bnUsersCol = getAllSortedBnUsers();
360        } catch(Exception JavaDoc e){
361         throw new HeroException("Error getting users from bonita database " + e.getMessage());
362        }
363     
364                    
365        try {
366         userRegistrationh = (UserRegistrationLocalHome)UserRegistrationUtil.getLocalHome();
367         userRegistration = userRegistrationh.create();
368          } catch (Exception JavaDoc e){
369                    e.printStackTrace();
370                    System.err.println("Error creating userRegistration Bean" + e);
371          }
372          
373         try {
374         userSessionh = (UserSessionLocalHome)UserSessionUtil.getLocalHome();
375         userSession = userSessionh.create();
376         
377          } catch (Exception JavaDoc e){
378                   e.printStackTrace();
379                   System.err.println("Error creating userSession Bean" + e);
380          }
381       
382         try {
383         // Look for each entry the Ldap if it exists in Bonita DB
384
Set entries = map.entrySet();
385         Iterator iterator = entries.iterator();
386           
387           while (iterator.hasNext()) {
388             Map.Entry entry = (Map.Entry)iterator.next();
389             userId = entry.getKey().toString();
390             email = entry.getValue().toString();
391             if (!bnUsersCol.contains(userId)){
392                 // create the user in Bonita DB.
393
userRegistration.userCreate(userId, userId, email);
394                 // debug
395
System.out.println("Create user in Bonita DB: " + entry.getKey() + " / " + entry.getValue());
396             }
397             else {
398                 System.out.println( "User already into Bonita database then set the mail of this user : " + entry.getKey() + " / " + entry.getValue());
399                 // set/update the mail attribute
400
userSession.setUserMail(userId, email);
401                 // suppress it from bnUsersCol to prevent removal as done after
402
bnUsersCol.remove(userId);
403             }
404           }
405           
406        // Prevent removing mandatory/default users for the Bonita DB.
407
if (bnUsersCol.contains("admin")) bnUsersCol.remove("admin");
408        if (bnUsersCol.contains("admin2")) bnUsersCol.remove("admin2");
409        if (bnUsersCol.contains("nobody")) bnUsersCol.remove("nobody");
410        
411        // Remaining users in the bnUsersCol list doesnt exist in Ldap then delete these.
412
Iterator it=bnUsersCol.iterator();
413           while (it.hasNext()) {
414             userId = (String JavaDoc)it.next();
415             //debug
416
System.out.println( "Deleting user in Bonita DB: " + userId);
417             //delete user from bonita DB
418
try {
419                 userRegistration.deleteUser(userId);
420             } catch (HeroException e) {
421               System.out.println( "Cannot remove user: " + userId + e.getMessage());
422             }
423           }
424         // remove the beans
425
userRegistration.remove();
426         userSession.remove();
427        
428       } catch (Exception JavaDoc e) {
429         e.printStackTrace();
430         System.err.println("Error executing import of users from ldap into Bonita DB. " + e);
431       }
432
433        // Disconnect from the directory server
434
try { dirContext.close(); } catch (Exception JavaDoc e) {};
435         
436      }
437
438     /**
439      * Get the members of a given group into the ldap server.
440      * It requires that the ldap resource within the AS. is configured and activated.
441      *
442      * @ejb:interface-method view-type="both"
443      * @ejb:transaction type="Required"
444      * @throws HeroException
445      *
446     **/

447     public Collection getGroupMembers(String JavaDoc groupName) throws HeroException{
448         
449       // Initialize the InitialContext passed on the
450
// connection parameters
451
Hashtable env = new Hashtable();
452         
453       env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
454       env.put(Context.PROVIDER_URL, providerUrl);
455       env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);
456       env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
457       env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
458       env.put(Context.REFERRAL, referral);
459         try
460           {
461           dirContext = new InitialDirContext(env);
462           }
463       catch (NamingException JavaDoc e)
464           {
465                   System.err.println("cannot initialize the initialContext of naming" + e);
466                   throw new EJBException JavaDoc("cannot initialize the initialContext of naming");
467           }
468         ArrayList al = new ArrayList();
469
470         // Retreiving groups in LDAP is supposed to be based on:
471
// - LDAP objectclass = groupOfUniqueNames
472
// - LDAP attribute containing members = uniquemember
473
// - It is not recursive: the groups inside a group are not taken into account
474
String JavaDoc dn = "";
475         String JavaDoc filter = "(&(objectclass=groupOfUniqueNames)(" + roleNameAttribute + "=" + groupName + "))";
476         // Specify the ids of the attributes to return and the scope of the search
477
SearchControls constraints = new SearchControls();
478         String JavaDoc[] attrID1s = {roleNameAttribute};
479         String JavaDoc[] attrID2s = {"uniquemember"};
480         
481         
482         constraints.setSearchScope(SearchControls.SUBTREE_SCOPE) ;
483         //constraints.setSearchScope(SearchControls.OBJECT_SCOPE) ;
484
// constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE) ;
485
String JavaDoc subTree= roleDN + "," + baseDn;
486         NamingEnumeration ne = null;
487         int taille = 0;
488         
489         // Check if the group exist in the LDAP
490
try {
491         constraints.setReturningAttributes(attrID1s);
492         ne = dirContext.search(subTree, filter, constraints);
493         }catch (NamingException JavaDoc e) {
494           throw new HeroException("Error searching groups in LDAP " + e);
495         }
496         try {
497           while (ne.hasMore()){
498             SearchResult sr = (SearchResult)ne.next();
499             Attributes attrs = sr.getAttributes();
500             // logs trace
501
System.out.println("LDAP group searching : " + attrs.toString());
502                           
503             taille = attrs.size();
504           }
505         } catch (NamingException JavaDoc e) {
506             throw new HeroException("Error dirContext.search" + e);
507         }
508         
509         
510         if ( taille == 0 ) {
511             // logs trace
512
System.err.println("The group " + groupName + " does not exist in the LDAP");
513             throw new HeroException("The group " + groupName + " does not exist in the LDAP ");
514         }
515         else {
516                 try
517                   {
518                     constraints.setReturningAttributes(attrID2s);
519                     ne = dirContext.search(subTree, filter, constraints);
520                   }catch (NamingException JavaDoc e){
521                     throw new HeroException ("Error searching groups in LDAP " + e);
522                   }
523                   
524                 // get the members
525
try {
526             
527                 while (ne.hasMore()){
528                         SearchResult sr = (SearchResult)ne.next();
529                         //get the members (dn)
530
Attributes attrs = sr.getAttributes();
531                                                     
532                     for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
533                         Attribute attr = (Attribute)ae.next();
534                         // logs trace
535
System.out.println("attribute: " + attr.getID());
536         
537                         //print each value
538
for (NamingEnumeration e = attr.getAll(); e.hasMore();){
539                           dn = (String JavaDoc) e.next();
540                           
541                           // logs trace
542
System.out.println(" dn: " + dn);
543                           
544                           // dn : cn = X, subtree
545
// 3 cases:
546
// 1- if subtree = UserDn then get the User Id
547
// 2- if subtree = RoleDn then the member is also a group, then call recusively the getGroupMembers ??
548
// 3- if subtree != UserDn and != RoleDn then return null
549
// => At now we suppose that we are always in case 1
550
//get the uid of the dn's ldap object
551
String JavaDoc userId = getUserIdFromDn(dn) ;
552                           
553                           // logs trace
554
System.out.println(" uid: " +userId);
555                           
556                           if (!"".equals(userId)){
557                             al.add(userId);
558                           }
559                         }
560                     }
561                   } // end while
562
ne.close();
563                  } catch (NamingException JavaDoc e){
564                             e.printStackTrace();
565                             throw new HeroException("Error searching userId from group members in LDAP");
566                 }
567         } // end else
568
return al;
569     }
570
571     /**
572      * Get the uid giving a partial DN (without Base suffix) as input.
573      * It requires that the ldap resource within the AS. is configured and activated.
574      *
575      * @ejb:interface-method view-type="both"
576      * @ejb:transaction type="Required"
577      * @throws HeroException
578      *
579     **/

580     public String JavaDoc getUserIdFromPartialDn(String JavaDoc partialDN) throws HeroException{
581             //Initialize the InitialContext passed on the
582
// connection parameters
583
Hashtable env = new Hashtable();
584             
585            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
586            env.put(Context.PROVIDER_URL, providerUrl);
587            env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);
588            env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
589            env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
590            env.put(Context.REFERRAL, referral);
591            
592              try
593                {
594                dirContext = new InitialDirContext(env);
595                }
596            catch (NamingException JavaDoc na)
597                {
598                     throw new HeroException("cannot initialize the initialContext of naming" + na.getMessage(), na);
599                }
600            
601             ArrayList al = new ArrayList();
602             String JavaDoc userId = "";
603             String JavaDoc filter = "uid=*";
604             NamingEnumeration ne = null;
605             // Specify the ids of the attributes to return
606
// and the scope of the search
607
SearchControls constraints = new SearchControls();
608             String JavaDoc[] attrIDs = {"uid"};
609             constraints.setReturningAttributes(attrIDs);
610             //constraints.setSearchScope(SearchControls.SUBTREE_SCOPE) ;
611
constraints.setSearchScope(SearchControls.OBJECT_SCOPE) ;
612         
613            // Search for objects that have those matching attributes
614
try {
615 //debug
616
System.out.println("BnLdapBean/getUserIdFromPartialDn: partialDN = " + partialDN + " baseDn = " + baseDn );
617                ne = dirContext.search(partialDN + "," + baseDn, filter, constraints);
618                 while (ne.hasMore())
619                   {
620                   SearchResult sr = (SearchResult)ne.next();
621                   //String dn = sr.getName() + ", " + userDN + "," + baseDn;
622
Attributes attrs = sr.getAttributes();
623                   Attribute attr = attrs.get("uid");
624                   userId = (String JavaDoc)attr.get();
625                   }
626                 ne.close();
627            } catch (NamingException JavaDoc na)
628             {
629                         throw new HeroException("Error searching directory :" + na.getMessage(), na);
630             }
631             return userId;
632           }
633     
634     /***************************************************************************
635                          getSortedMapUidMailLdap
636              Target: Get user "uid" and "mail" and return a sortedMap
637     ****************************************************************************/

638     private Map getTreeMapUidMailLdap() {
639         TreeMap treeMap = new TreeMap();
640       try
641         {
642
643         // using the User Search Filter as jonas-realm_1_0.dtd : "uid={0}"
644
MessageFormat JavaDoc form = new MessageFormat JavaDoc(userSearchFilter);
645         // Get all user by replacing the parameter {0} by *
646
Object JavaDoc[] testArgs = {"*"};
647         String JavaDoc filter = form.format(testArgs);
648         
649         // logs trace
650
System.out.println("Filter used to get user in Ldap: " + filter);
651         
652         // Specify the ids of the attributes to return
653
// and the scope of the search
654
SearchControls constraints = new SearchControls();
655         
656         // get the attribut name from "User serach Filter" ie: uid={0}
657
int indSep = userSearchFilter.indexOf('=');
658             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(userSearchFilter);
659             String JavaDoc userParameter = sb.substring(0,indSep);
660             
661         // logs trace
662
System.out.println("UserParameter from userSearchFilter = " + userParameter);
663         
664         String JavaDoc[] attrIDs = {userParameter,"mail"};
665         constraints.setReturningAttributes(attrIDs);
666         
667         constraints.setSearchScope(SearchControls.SUBTREE_SCOPE) ;
668         
669         // logs trace
670
// Set SearchControl for "CountLimit" and "TimeLimit" for information
671
System.out.println("Naming CountLimit = " + constraints.getCountLimit());
672         System.out.println("Naming TimeLimit = " + constraints.getTimeLimit());
673     
674         // Search for objects that have those matching attributes
675
NamingEnumeration ne = dirContext.search(userDN + "," + baseDn, filter, constraints);
676         String JavaDoc userId ="";
677         String JavaDoc userMail ="";
678         Attribute attr = null;
679         while (ne.hasMore())
680           {
681           SearchResult sr = (SearchResult)ne.next();
682
683            
684           Attributes attrs = sr.getAttributes();
685           // uid -> key
686
attr = attrs.get(userParameter);
687           userId = (String JavaDoc)attr.get();
688           // mail -> value
689
if (attrs.get("mail") != null) {
690                     attr = attrs.get("mail");
691                 userMail = (String JavaDoc)attr.get();
692             }
693           else {
694             userMail = "";
695           }
696                   
697           treeMap.put(userId,userMail);
698           }
699         ne.close();
700         
701         // logs trace
702
System.out.println("------------------" + userParameter + " and mail found un Ldap -------------------------");
703         printUidMailCollection(treeMap);
704         } // end try
705
catch (SizeLimitExceededException e)
706         {
707             // logs trace
708
System.err.println(e);
709             System.err.println("");
710             System.err.println("Sizelimit Exceeded from the LDAP server.");
711             System.out.println("Please contact the ldap administrator to extend this limit,");
712             System.out.println("or reduce the scope of the user searching.");
713             System.err.println("");
714             e.printStackTrace();
715         }
716       catch (NamingException JavaDoc e)
717         {
718             e.printStackTrace();
719             System.err.println("Error reading directory" + e);
720             throw new EJBException JavaDoc("Error reading directory");
721         }
722             return treeMap;
723       }
724     
725     
726  
727     /***************************************************************************
728                          getUidFromLdap
729              Target: Get user uid and return a sorted collection
730     ****************************************************************************/

731     private Collection getUidFromLdap() {
732         TreeSet sorter = new TreeSet();
733       try
734         {
735
736         // using the User Search Filter as jonas-realm_1_0.dtd : "uid={0}"
737
MessageFormat JavaDoc form = new MessageFormat JavaDoc(userSearchFilter);
738         // Get all user by replacing the parameter {0} by *
739
Object JavaDoc[] testArgs = {"*"};
740         String JavaDoc filter = form.format(testArgs);
741         
742         // logs trace
743
System.out.println("Filter used to get user in Ldap: " + filter);
744         
745         // Specify the ids of the attributes to return
746
// and the scope of the search
747
SearchControls constraints = new SearchControls();
748         
749         // get the attribut name from "User serach Filter" ie: uid={0}
750
int indSep = userSearchFilter.indexOf('=');
751             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(userSearchFilter);
752             String JavaDoc userParameter = sb.substring(0,indSep);
753             
754         // logs trace
755
System.out.println("UserParameter from userSearchFilter = " + userParameter);
756         
757         String JavaDoc[] attrIDs = {userParameter};
758         constraints.setReturningAttributes(attrIDs);
759         
760         constraints.setSearchScope(SearchControls.SUBTREE_SCOPE) ;
761         
762         // logs trace
763
// Set SearchControl for "CountLimit" and "TimeLimit" for information
764
System.out.println("Naming CountLimit = " + constraints.getCountLimit());
765         System.out.println("Naming TimeLimit = " + constraints.getTimeLimit());
766     
767        // Search for objects that have those matching attributes
768
NamingEnumeration ne = dirContext.search(userDN + "," + baseDn , filter, constraints);
769         
770         while (ne.hasMore())
771           {
772           SearchResult sr = (SearchResult)ne.next();
773           //String dn = sr.getName() + ", " + userDN + "," + baseDn;
774
Attributes attrs = sr.getAttributes();
775           Attribute attr = attrs.get(userParameter);
776           String JavaDoc userId = (String JavaDoc)attr.get();
777           sorter.add(userId);
778           // logs trace
779
System.out.println(userId);
780           }
781         ne.close();
782         
783         // logs trace
784
System.out.println("------------------" + userParameter + " found in Ldap -------------------------");
785         
786         printUidCollection(sorter);
787         } // end try
788
catch (SizeLimitExceededException e)
789         {
790             System.err.println(e);
791             System.err.println("Sizelimit Exceeded from the LDAP server.");
792             System.out.println("-> Please contact the ldap administrator to extend this limit.");
793                 System.out.println("-> or reduce the scope of the user searching.");
794                 System.err.println("Stack of the Error:");
795                 e.printStackTrace();
796         }
797       catch (NamingException JavaDoc e)
798         {
799                     e.printStackTrace();
800                     System.err.println("Error reading directory" + e);
801                     throw new EJBException JavaDoc("Error reading directory");
802         }
803             return sorter;
804       }
805  
806     
807     /***************************************************************************
808          getAttributesFromUser
809          ex. to get attributes in naming (ldap) service
810     ****************************************************************************/

811     private Collection getAttributesFromUser(String JavaDoc userID) {
812     
813       try
814         {
815         ArrayList al = new ArrayList();
816         
817         // using the User Search Filter as jonas-realm_1_0.dtd : "uid={0}"
818
MessageFormat JavaDoc form = new MessageFormat JavaDoc(userSearchFilter);
819         Object JavaDoc[] testArgs = {userID};
820         String JavaDoc filter = form.format(testArgs);
821             
822         // logs trace
823
System.out.println("Filter to get the users name in LDAP: " + filter);
824         
825         // Specify the ids of the attributes to return
826
// and the scope of the search
827
SearchControls constraints = new SearchControls();
828         String JavaDoc[] attrIDs = {"sn", "givenname", "cn", "mail"};
829         constraints.setReturningAttributes(attrIDs);
830         constraints.setSearchScope(SearchControls.SUBTREE_SCOPE) ;
831     
832        // Search for objects that have those matching attributes
833
NamingEnumeration ne = dirContext.search(userDN + "," + baseDn, filter, constraints);
834         
835         while (ne.hasMore())
836           {
837           SearchResult sr = (SearchResult)ne.next();
838           //String dn = sr.getName() + ", " + userDN + "," + baseDn;
839
Attributes a = sr.getAttributes();
840           al.add(a);
841           }
842         ne.close();
843         
844         // logs trace
845
printUserAttributes(al);
846         
847         return al;
848         
849         }
850       catch (NamingException JavaDoc e)
851         {
852                     e.printStackTrace();
853                     System.err.println("Error reading directory" + e);
854                     throw new EJBException JavaDoc("Error reading directory");
855         }
856       }
857     
858
859     private String JavaDoc getUserIdFromDn(String JavaDoc dn) {
860     
861       try
862         {
863     
864         ArrayList al = new ArrayList();
865         
866         String JavaDoc userId = "";
867         //String filter = "dn=" + dn;
868
String JavaDoc filter = "uid=*";
869         // debug
870
System.out.println("Filter to identify the user to get it's attributes: " + filter);
871         
872         // Specify the ids of the attributes to return
873
// and the scope of the search
874
SearchControls constraints = new SearchControls();
875         String JavaDoc[] attrIDs = {"uid"};
876         constraints.setReturningAttributes(attrIDs);
877         //constraints.setSearchScope(SearchControls.SUBTREE_SCOPE) ;
878
constraints.setSearchScope(SearchControls.OBJECT_SCOPE) ;
879     
880        // Search for objects that have those matching attributes
881
//NamingEnumeration ne = dirContext.search(userDN + "," + baseDn, filter, constraints);
882
NamingEnumeration ne = dirContext.search(dn, filter, constraints);
883         
884         while (ne.hasMore())
885           {
886           SearchResult sr = (SearchResult)ne.next();
887           //String dn = sr.getName() + ", " + userDN + "," + baseDn;
888
Attributes attrs = sr.getAttributes();
889           Attribute attr = attrs.get("uid");
890           userId = (String JavaDoc)attr.get();
891           }
892         ne.close();
893         return userId;
894         
895         }
896       catch (NamingException JavaDoc e)
897         {
898                     e.printStackTrace();
899                     System.err.println("Error reading directory" + e);
900                     throw new EJBException JavaDoc("Error reading directory");
901         }
902       }
903      
904
905                     
906     /**********************************************
907          get all users in bonita database
908     **********************************************/

909      private Collection getAllSortedBnUsers() throws HeroException{
910      TreeSet sorter = new TreeSet();
911     Collection unSortedList = null;
912     try {
913     ProjectSessionLocalHome projecth = (ProjectSessionLocalHome)ProjectSessionUtil.getLocalHome();
914     ProjectSessionLocal projectsession = projecth.create();
915     // get users in bonita database
916
unSortedList = projectsession.getAllUsers();
917     
918     Iterator it = unSortedList.iterator();
919     while (it.hasNext()){
920         sorter.add(it.next());
921     }
922     } catch (Exception JavaDoc e){
923                 e.printStackTrace();
924                 System.err.println("Error in BnLdapBean for getAllSortedBnUsers " + e);
925                 throw new HeroException("Error in BnLdapBean for getAllSortedBnUsers" + e.getMessage());
926         }
927     // logs trace
928
System.out.println("------------------ Bonita registered users -------------------------");
929         printUidCollection(sorter);
930         return sorter;
931      }
932
933     /**
934      * Creates the BnLdap Bean. This method is the first one to invoke in order to
935      * use BnLdap API.
936      * The client user of the API must be authentified otherwise an exception will be thrown
937      *
938      * @ejb:create-method view-type="both"
939      **/

940     public void ejbCreate() {
941     }
942
943
944     /**
945     * Internal Enterprise Java Beans method.
946     **/

947     public void ejbActivate() {
948     }
949
950
951     /**
952     * Internal Enterprise Java Beans method.
953     **/

954     public void ejbPassivate() {
955     // Nothing to do for this simple example
956
}
957
958
959     /**
960     * Internal Enterprise Java Beans method.
961     **/

962     public void ejbRemove() {
963     // Nothing to do for this simple example
964
}
965
966
967     /****************************************************************
968           Utility: printUidCollection Only to print out !
969      ***************************************************************/

970     private static void printUidCollection(Collection co){
971           // Example for searching user attributes in ldap giving the "uid" attribute (not unique !)
972
try {
973           Collection c = co;
974       Iterator it = c.iterator();
975          Attributes a=null;
976          while (it.hasNext()) {
977             //a = (Attributes)it.next();
978
//printAttrs(a);
979
System.out.println( (String JavaDoc)(it.next()) );
980      }// end while
981
} catch (Exception JavaDoc e) {
982         System.err.println("erreur Client pour la recherche des uid dans ldap : " + e);
983         System.exit(2);
984      }
985    }
986
987     /****************************************************************
988           Utility: printUidMailCollection return TreeMap
989      ***************************************************************/

990     private static void printUidMailCollection(Map map){
991           // Example for searching user attributes in ldap giving the "uid" attribute (not unique !)
992
try {
993           Set entries = map.entrySet();
994           Iterator iterator = entries.iterator();
995           while (iterator.hasNext()) {
996             Map.Entry entry = (Map.Entry)iterator.next();
997             System.out.println(entry.getKey() + " : " + entry.getValue());
998           }
999       } catch (Exception JavaDoc e) {
1000        System.err.println("erreur Client pour la recherche des uid dans ldap : " + e);
1001        System.exit(2);
1002      }
1003   }
1004    
1005              
1006    /****************************************************************
1007            Utility: printUserAttributes
1008     ***************************************************************/

1009    private static void printUserAttributes(Collection co){
1010          // Example for searching user attributes in ldap giving the "uid" attribute (not unique !)
1011
try {
1012          Collection c = co;
1013      Iterator it = c.iterator();
1014         Attributes a=null;
1015         System.out.println("------------------ search attributes -------------------------");
1016         while (it.hasNext()) {
1017            a = (Attributes)it.next();
1018        printAttrs(a);
1019     }// end while
1020
} catch (Exception JavaDoc e) {
1021        System.err.println("erreur chez le client pour la recherche des attributs dans ldap: " + e);
1022        System.exit(2);
1023     }
1024   }
1025
1026
1027    /****************************************************************
1028                Utility : printGroupMember
1029     ***************************************************************/

1030    private static void printGroupMember(Collection co){
1031         // Example for searching mmber of a goup in ldap
1032
try {
1033         Attributes a=null;
1034         // recup d'une array list of SearchResult
1035
Collection c = co;
1036     Iterator it = c.iterator();
1037     System.out.println("");
1038    
1039         while (it.hasNext()) {
1040            SearchResult sr = (SearchResult)it.next();
1041            // recup du nom du name et des uniquemember du groupe
1042
System.out.println("");
1043                System.out.println("------- Group name = " + sr.getName());
1044                a = sr.getAttributes();
1045                printAttrs(a);
1046     } // end while
1047
} catch (Exception JavaDoc e) {
1048        System.err.println("Client error pour la recherche de groupes dans ldap : " + e);
1049        System.exit(2);
1050     }
1051      }
1052    /***********************************
1053    Utility for printing for debug ...
1054    ************************************/

1055    private static void printAttrs(Attributes attrs) {
1056    if (attrs == null) {
1057        System.out.println("No attributes");
1058    } else {
1059        /* Print each attribute */
1060        try {
1061        for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
1062            Attribute attr = (Attribute)ae.next();
1063            System.out.println("attribute: " + attr.getID());
1064
1065            /* print each value */
1066            for (NamingEnumeration e = attr.getAll(); e.hasMore();
1067             System.out.println("value: " + e.next()))
1068            ;
1069        }
1070        } catch (NamingException JavaDoc e) {
1071        e.printStackTrace();
1072        }
1073    }
1074    }
1075
1076        
1077} // end class
1078
Popular Tags