0001: /**
0002: *
0003: * Bonita
0004: * Copyright (C) 1999 Bull S.A.
0005: * Bull 68 route de versailles 78434 Louveciennes Cedex France
0006: * Further information: bonita@objectweb.org
0007: *
0008: * This library is free software; you can redistribute it and/or
0009: * modify it under the terms of the GNU Lesser General Public
0010: * License as published by the Free Software Foundation; either
0011: * version 2.1 of the License, or any later version.
0012: *
0013: * This library is distributed in the hope that it will be useful,
0014: * but WITHOUT ANY WARRANTY; without even the implied warranty of
0015: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
0016: * Lesser General Public License for more details.
0017: *
0018: * You should have received a copy of the GNU Lesser General Public
0019: * License along with this library; if not, write to the Free Software
0020: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
0021: * USA
0022: *
0023: *
0024: --------------------------------------------------------------------------
0025: * $Id: BnLdapBean.java,v 1.8 2006/11/14 10:37:48 blachonm Exp $
0026: *
0027: --------------------------------------------------------------------------
0028: */package hero.session;
0029:
0030: import javax.ejb.EJBException;
0031: import javax.ejb.SessionBean;
0032: import javax.ejb.SessionContext;
0033: import javax.naming.Context;
0034: import javax.naming.InitialContext;
0035: import javax.naming.NamingException;
0036: import java.util.*;
0037: import java.text.MessageFormat; // added for jndi/ldap
0038: import javax.naming.*;
0039: import javax.naming.directory.*;
0040:
0041: // added for Mejb manage
0042: import javax.rmi.PortableRemoteObject;
0043: import hero.util.HeroException; // JMX
0044: import javax.management.ObjectName;
0045: import javax.management.InstanceNotFoundException;
0046: import javax.management.Query;
0047:
0048: // J2EE management imports
0049: import javax.management.j2ee.ManagementHome;
0050: import javax.management.j2ee.Management;
0051:
0052: // For bonita Beans
0053: import java.rmi.RemoteException;
0054: import hero.interfaces.UserRegistrationLocalHome;
0055: import hero.interfaces.UserRegistrationLocal;
0056: import hero.interfaces.UserRegistrationUtil;
0057:
0058: import hero.interfaces.ProjectSessionLocalHome;
0059: import hero.interfaces.ProjectSessionLocal;
0060: import hero.interfaces.ProjectSessionUtil;
0061:
0062: import hero.interfaces.UserSessionLocalHome;
0063: import hero.interfaces.UserSessionLocal;
0064: import hero.interfaces.UserSessionUtil;
0065:
0066: import hero.util.HeroException;
0067: import javax.ejb.CreateException;
0068:
0069: /**
0070: * @ejb:bean name="BnLdap"
0071: * display-name="BnLdap Bean"
0072: * type="Stateless"
0073: * transaction-type="Container"
0074: * jndi-name="ejb/hero/BnLdap"
0075: * local-jndi-name="ejb/hero/BnLdap_L"
0076: *
0077: * @ejb:ejb-ref ejb-name="BnLdap"
0078: * ref-name="myhero/BnLdap"
0079: *
0080: * @ejb.ejb-external-ref
0081: * view-type="remote"
0082: * ref-name="ejb/mgmt/MEJB"
0083: * type="Session"
0084: * home="javax.management.j2ee.ManagementHome"
0085: * remote="javax.management.j2ee.Management"
0086: *
0087: * @jonas.ejb-ref ejb-ref-name="ejb/mgmt/MEJB"
0088: * jndi-name="ejb/mgmt/MEJB"
0089: * @ejb.permission role-name="BONITAUSER,user,SuperAdmin"
0090: * @ejb:transaction type="Required"
0091: * @ejb:transaction-type type="Container"
0092: * @jonas.bean
0093: * ejb-name="BnLdap"
0094: * jndi-name="ejb/hero/BnLdap"
0095: *
0096: * @jboss:ejb-ref-jndi ref-name="mgmt/MEJB"
0097: * jndi-name="ejb/mgmt/MEJB"
0098: *
0099: * @jboss.container-configuration name="Standard Stateless SessionBean for Bonita"
0100: **/
0101:
0102: public class BnLdapBean implements SessionBean {
0103:
0104: private String ldapRealmName = null;
0105: private SessionContext sessionContext = null;
0106:
0107: String baseDn = "";
0108: String initialContextFactory = "";
0109: String providerUrl = "";
0110: String authenticationMode = "";
0111: String securityAuthentication = "";
0112: String securityPrincipal = "";
0113: String securityCredentials = "";
0114: String referral = "";
0115: String roleDN = "";
0116: String roleNameAttribute = "";
0117: String roleSearchFilter = "";
0118: String userDN = "";
0119: String userPasswordAttribute = "";
0120: String userRolesAttribute = "";
0121: String userSearchFilter = "";
0122:
0123: /** The directory server connection */
0124: private DirContext dirContext = null;
0125:
0126: /**
0127: * Internal Enterprise Java Beans method.
0128: **/
0129: public void setSessionContext(SessionContext ctx) {
0130: sessionContext = ctx;
0131:
0132: Context initialContext = null;
0133: try {
0134: initialContext = new InitialContext();
0135: } catch (Exception e) {
0136: e.printStackTrace();
0137: System.err.println("Cannot get initial context for JNDI: "
0138: + e);
0139: }
0140:
0141: // --------------
0142: // Access to MEJB
0143: // --------------
0144:
0145: // Connecting to the MEJB home through JNDI
0146: ManagementHome mgmtHome = null;
0147: try {
0148: mgmtHome = (ManagementHome) PortableRemoteObject.narrow(
0149: initialContext
0150: .lookup("java:comp/env/ejb/mgmt/MEJB"),
0151: ManagementHome.class);
0152: } catch (Exception e) {
0153: e.printStackTrace();
0154: System.err
0155: .println("Cannot lookup java:comp/env/ejb/mgmt/MEJB: "
0156: + e);
0157: return;
0158: }
0159: // Management bean creation
0160: Management mgmt = null;
0161: try {
0162: mgmt = mgmtHome.create();
0163: System.out.println("MEJB created");
0164: } catch (Exception e) {
0165: e.printStackTrace();
0166: System.err.println("Error creating MEJB: " + e);
0167: }
0168:
0169: // -------------------------------------------------------
0170: // Access to the J2EEDomain MBean for ldap securityfactory
0171: // -------------------------------------------------------
0172:
0173: System.out.println("Access the J2EEDomain MBean");
0174: ObjectName objectName = null;
0175:
0176: // get the default domain
0177: String defaultDomain = "";
0178: try {
0179: defaultDomain = mgmt.getDefaultDomain();
0180: } catch (Exception e) {
0181: System.err.println("Cannot create MEJB: " + e);
0182: }
0183:
0184: //Check that there's only one Ldap realm defined in the JOnAS configuration
0185: try {
0186: ObjectName searchpattern = new ObjectName(defaultDomain
0187: + ":type=securityfactory,subtype=ldap,*");
0188: Query q = new Query();
0189: Set managedObject = mgmt.queryNames(searchpattern, null);
0190:
0191: if ((managedObject.size()) > 1) {
0192: System.err
0193: .println("Error detected in JOnAS configuration:");
0194: System.err
0195: .println("More than 1 Ldap realms has been defined");
0196: Iterator itr = managedObject.iterator();
0197: while (itr.hasNext()) {
0198: ObjectName name = (ObjectName) itr.next();
0199: System.out.println(name.toString());
0200: }
0201: throw new RemoteException(
0202: "More than 1 Ldap realms has been defined");
0203:
0204: } // end if
0205: else if ((managedObject.size()) == 0) {
0206: System.err
0207: .println("Error detected in JOnAS configuration:");
0208: System.err
0209: .println("No ldap configuration has been defined.");
0210: throw new RemoteException(
0211: "0 Ldap realms has been defined");
0212: } else {
0213: // The right case ! One ldap config defined !
0214: Iterator itr = managedObject.iterator();
0215: while (itr.hasNext()) {
0216: objectName = (ObjectName) itr.next();
0217: System.out
0218: .println("1 Ldap realm name detected in JOnAS configuration:");
0219: System.out.println(objectName.toString());
0220:
0221: }
0222: }
0223:
0224: } catch (Exception e) {
0225: System.err.println("Error checking ldap objectName: " + e);
0226: }
0227:
0228: if (objectName != null) {
0229: // Get the values of attributes of the the MBean for ldap securityfactory
0230: try {
0231: boolean exists = mgmt.isRegistered(objectName);
0232: if (exists) {
0233: //System.out.println("J2EEDomain managed object registered in the current MBean server");
0234:
0235: //BaseDN
0236: if (mgmt.getAttribute(objectName, "BaseDN") != null)
0237: baseDn = mgmt
0238: .getAttribute(objectName, "BaseDN")
0239: .toString();
0240: else
0241: baseDn = "";
0242: //System.out.println("BaseDN = " + baseDn);
0243:
0244: // InitialContextFactory
0245: if (mgmt.getAttribute(objectName,
0246: "InitialContextFactory") != null)
0247: initialContextFactory = mgmt.getAttribute(
0248: objectName, "InitialContextFactory")
0249: .toString();
0250: else
0251: initialContextFactory = "";
0252: //System.out.println("initialContextFactory = " + initialContextFactory);
0253:
0254: //ProviderUrl
0255: if (mgmt.getAttribute(objectName, "ProviderUrl") != null)
0256: providerUrl = mgmt.getAttribute(objectName,
0257: "ProviderUrl").toString();
0258: else
0259: providerUrl = "";
0260: //System.out.println("providerUrl = " + providerUrl);
0261:
0262: //SecurityAuthentication
0263: if (mgmt.getAttribute(objectName,
0264: "SecurityAuthentication") != null)
0265: securityAuthentication = mgmt.getAttribute(
0266: objectName, "SecurityAuthentication")
0267: .toString();
0268: else
0269: securityAuthentication = "";
0270: //System.out.println("securityAuthentication = " + securityAuthentication);
0271:
0272: //SecurityPrincipal
0273: if (mgmt.getAttribute(objectName,
0274: "SecurityPrincipal") != null)
0275: securityPrincipal = mgmt.getAttribute(
0276: objectName, "SecurityPrincipal")
0277: .toString();
0278: else
0279: securityPrincipal = "";
0280: //System.out.println("securityPrincipal = " + securityPrincipal);
0281:
0282: //SecurityCredentials
0283: if (mgmt.getAttribute(objectName,
0284: "SecurityCredentials") != null)
0285: securityCredentials = mgmt.getAttribute(
0286: objectName, "SecurityCredentials")
0287: .toString();
0288: else
0289: securityCredentials = "";
0290: //System.out.println("securityCredentials = " + securityCredentials);
0291:
0292: // RoleDN
0293: if (mgmt.getAttribute(objectName, "RoleDN") != null)
0294: roleDN = mgmt
0295: .getAttribute(objectName, "RoleDN")
0296: .toString();
0297: else
0298: roleDN = "";
0299: //System.out.println("roleDN = " + roleDN);
0300:
0301: //RoleNameAttribute
0302: if (mgmt.getAttribute(objectName,
0303: "RoleNameAttribute") != null)
0304: roleNameAttribute = mgmt.getAttribute(
0305: objectName, "RoleNameAttribute")
0306: .toString();
0307: else
0308: roleNameAttribute = "";
0309: //System.out.println("roleNameAttribute = " + roleNameAttribute);
0310:
0311: //RoleSearchFilter
0312: if (mgmt.getAttribute(objectName,
0313: "RoleSearchFilter") != null)
0314: roleSearchFilter = mgmt.getAttribute(
0315: objectName, "RoleSearchFilter")
0316: .toString();
0317: else
0318: roleSearchFilter = "";
0319: //System.out.println("roleSearchFilter = " + roleSearchFilter);
0320:
0321: //UserDN
0322: if (mgmt.getAttribute(objectName, "UserDN") != null)
0323: userDN = mgmt
0324: .getAttribute(objectName, "UserDN")
0325: .toString();
0326: else
0327: userDN = "";
0328: //System.out.println("userDN = " + userDN);
0329:
0330: //UserPasswordAttribute
0331: if (mgmt.getAttribute(objectName,
0332: "UserPasswordAttribute") != null)
0333: userPasswordAttribute = mgmt.getAttribute(
0334: objectName, "UserPasswordAttribute")
0335: .toString();
0336: else
0337: userPasswordAttribute = "";
0338: //System.out.println("userPasswordAttribute = " + userPasswordAttribute);
0339:
0340: //UserRolesAttribute
0341: if (mgmt.getAttribute(objectName,
0342: "UserRolesAttribute") != null)
0343: userRolesAttribute = mgmt.getAttribute(
0344: objectName, "UserRolesAttribute")
0345: .toString();
0346: else
0347: userRolesAttribute = "";
0348: //System.out.println("userRolesAttribute = " + userRolesAttribute);
0349:
0350: //UserSearchFilter
0351: if (mgmt.getAttribute(objectName,
0352: "UserSearchFilter") != null)
0353: userSearchFilter = mgmt.getAttribute(
0354: objectName, "UserSearchFilter")
0355: .toString();
0356: else
0357: userSearchFilter = "";
0358: //System.out.println("userSearchFilter = " + userSearchFilter);
0359:
0360: // optional : Referral (parameter value = "throw")
0361: if (mgmt.getAttribute(objectName, "Referral") != null)
0362: referral = mgmt.getAttribute(objectName,
0363: "Referral").toString();
0364: else
0365: referral = "";
0366: //System.out.println("referral = " + referral);
0367: } else {
0368: System.out
0369: .println("Can't find J2EEDomain managed object having the above name in the current MBean server");
0370: return;
0371: }
0372: } catch (Exception e) {
0373: System.err
0374: .println("Error when using the J2EEDomain managed object: "
0375: + e);
0376: return;
0377: }
0378: }
0379:
0380: }
0381:
0382: /**
0383: * Import users from the LDAP used for authentication by the Application Server
0384: * to Bonita database.
0385: * For each user found in LDAP:
0386: * - if it doesn't exists in bonita database then this user is created
0387: * - if it exists in bonita database then the mail property is updated.
0388: * It requires that the ldap resource within the AS. is configured and activated.
0389: *
0390: * @ejb:interface-method view-type="both"
0391: * @ejb:transaction type="Required"
0392: * @throws HeroException
0393: *
0394: **/
0395: public void importLdapUsers() throws HeroException {
0396:
0397: String userId = "";
0398: String email = "";
0399: UserRegistrationLocalHome userRegistrationh = null;
0400: UserRegistrationLocal userRegistration = null;
0401:
0402: UserSessionLocalHome userSessionh = null;
0403: UserSessionLocal userSession = null;
0404:
0405: // Initialize the InitialContext passed on the
0406: // connection parameters
0407: Hashtable env = new Hashtable();
0408:
0409: env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
0410: env.put(Context.PROVIDER_URL, providerUrl);
0411: env
0412: .put(Context.SECURITY_AUTHENTICATION,
0413: securityAuthentication);
0414: env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
0415: env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
0416: env.put(Context.REFERRAL, referral);
0417:
0418: try {
0419: dirContext = new InitialDirContext(env);
0420: } catch (NamingException e) {
0421: System.err
0422: .println("cannot initialize the initialContext of naming"
0423: + e);
0424: throw new EJBException(
0425: "cannot initialize the initialContext of naming");
0426: }
0427:
0428: // Get users into ldap and Bonita database to be able to compare ...
0429: Map map = null;
0430: Collection bnUsersCol = null;
0431: try {
0432: map = getTreeMapUidMailLdap();
0433: } catch (Exception e) {
0434: throw new HeroException("Error getting users from LDAP "
0435: + e.getMessage());
0436: }
0437: try {
0438: bnUsersCol = getAllSortedBnUsers();
0439: } catch (Exception e) {
0440: throw new HeroException(
0441: "Error getting users from bonita database "
0442: + e.getMessage());
0443: }
0444:
0445: try {
0446: userRegistrationh = (UserRegistrationLocalHome) UserRegistrationUtil
0447: .getLocalHome();
0448: userRegistration = userRegistrationh.create();
0449: } catch (Exception e) {
0450: e.printStackTrace();
0451: System.err.println("Error creating userRegistration Bean"
0452: + e);
0453: }
0454:
0455: try {
0456: userSessionh = (UserSessionLocalHome) UserSessionUtil
0457: .getLocalHome();
0458: userSession = userSessionh.create();
0459:
0460: } catch (Exception e) {
0461: e.printStackTrace();
0462: System.err.println("Error creating userSession Bean" + e);
0463: }
0464:
0465: try {
0466: // Look for each entry the Ldap if it exists in Bonita DB
0467: Set entries = map.entrySet();
0468: Iterator iterator = entries.iterator();
0469:
0470: while (iterator.hasNext()) {
0471: Map.Entry entry = (Map.Entry) iterator.next();
0472: userId = entry.getKey().toString();
0473: email = entry.getValue().toString();
0474: if (!bnUsersCol.contains(userId)) {
0475: // create the user in Bonita DB.
0476: userRegistration.userCreate(userId, userId, email);
0477: // debug
0478: System.out
0479: .println("Create user in Bonita DB: "
0480: + entry.getKey() + " / "
0481: + entry.getValue());
0482: } else {
0483: System.out
0484: .println("User already into Bonita database then set the mail of this user : "
0485: + entry.getKey()
0486: + " / "
0487: + entry.getValue());
0488: // set/update the mail attribute
0489: userSession.setUserMail(userId, email);
0490: // suppress it from bnUsersCol to prevent removal as done after
0491: bnUsersCol.remove(userId);
0492: }
0493: }
0494:
0495: // Prevent removing mandatory/default users for the Bonita DB.
0496: if (bnUsersCol.contains("admin"))
0497: bnUsersCol.remove("admin");
0498: if (bnUsersCol.contains("admin2"))
0499: bnUsersCol.remove("admin2");
0500: if (bnUsersCol.contains("nobody"))
0501: bnUsersCol.remove("nobody");
0502:
0503: // Remaining users in the bnUsersCol list doesnt exist in Ldap then delete these.
0504: Iterator it = bnUsersCol.iterator();
0505: while (it.hasNext()) {
0506: userId = (String) it.next();
0507: //debug
0508: System.out.println("Deleting user in Bonita DB: "
0509: + userId);
0510: //delete user from bonita DB
0511: try {
0512: userRegistration.deleteUser(userId);
0513: } catch (HeroException e) {
0514: System.out.println("Cannot remove user: " + userId
0515: + e.getMessage());
0516: }
0517: }
0518: // remove the beans
0519: userRegistration.remove();
0520: userSession.remove();
0521:
0522: } catch (Exception e) {
0523: e.printStackTrace();
0524: System.err
0525: .println("Error executing import of users from ldap into Bonita DB. "
0526: + e);
0527: }
0528:
0529: // Disconnect from the directory server
0530: try {
0531: dirContext.close();
0532: } catch (Exception e) {
0533: }
0534: ;
0535:
0536: }
0537:
0538: /**
0539: * Get the members of a given group into the ldap server.
0540: * It requires that the ldap resource within the AS. is configured and activated.
0541: *
0542: * @ejb:interface-method view-type="both"
0543: * @ejb:transaction type="Required"
0544: * @throws HeroException
0545: *
0546: **/
0547: public Collection getGroupMembers(String groupName)
0548: throws HeroException {
0549:
0550: // Initialize the InitialContext passed on the
0551: // connection parameters
0552: Hashtable env = new Hashtable();
0553:
0554: env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
0555: env.put(Context.PROVIDER_URL, providerUrl);
0556: env
0557: .put(Context.SECURITY_AUTHENTICATION,
0558: securityAuthentication);
0559: env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
0560: env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
0561: env.put(Context.REFERRAL, referral);
0562: try {
0563: dirContext = new InitialDirContext(env);
0564: } catch (NamingException e) {
0565: System.err
0566: .println("cannot initialize the initialContext of naming"
0567: + e);
0568: throw new EJBException(
0569: "cannot initialize the initialContext of naming");
0570: }
0571: ArrayList al = new ArrayList();
0572:
0573: // Retreiving groups in LDAP is supposed to be based on:
0574: // - LDAP objectclass = groupOfUniqueNames
0575: // - LDAP attribute containing members = uniquemember
0576: // - It is not recursive: the groups inside a group are not taken into account
0577: String dn = "";
0578: String filter = "(&(objectclass=groupOfUniqueNames)("
0579: + roleNameAttribute + "=" + groupName + "))";
0580: // Specify the ids of the attributes to return and the scope of the search
0581: SearchControls constraints = new SearchControls();
0582: String[] attrID1s = { roleNameAttribute };
0583: String[] attrID2s = { "uniquemember" };
0584:
0585: constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
0586: //constraints.setSearchScope(SearchControls.OBJECT_SCOPE) ;
0587: // constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE) ;
0588: String subTree = roleDN + "," + baseDn;
0589: NamingEnumeration ne = null;
0590: int taille = 0;
0591:
0592: // Check if the group exist in the LDAP
0593: try {
0594: constraints.setReturningAttributes(attrID1s);
0595: ne = dirContext.search(subTree, filter, constraints);
0596: } catch (NamingException e) {
0597: throw new HeroException("Error searching groups in LDAP "
0598: + e);
0599: }
0600: try {
0601: while (ne.hasMore()) {
0602: SearchResult sr = (SearchResult) ne.next();
0603: Attributes attrs = sr.getAttributes();
0604: // logs trace
0605: System.out.println("LDAP group searching : "
0606: + attrs.toString());
0607:
0608: taille = attrs.size();
0609: }
0610: } catch (NamingException e) {
0611: throw new HeroException("Error dirContext.search" + e);
0612: }
0613:
0614: if (taille == 0) {
0615: // logs trace
0616: System.err.println("The group " + groupName
0617: + " does not exist in the LDAP");
0618: throw new HeroException("The group " + groupName
0619: + " does not exist in the LDAP ");
0620: } else {
0621: try {
0622: constraints.setReturningAttributes(attrID2s);
0623: ne = dirContext.search(subTree, filter, constraints);
0624: } catch (NamingException e) {
0625: throw new HeroException(
0626: "Error searching groups in LDAP " + e);
0627: }
0628:
0629: // get the members
0630: try {
0631:
0632: while (ne.hasMore()) {
0633: SearchResult sr = (SearchResult) ne.next();
0634: //get the members (dn)
0635: Attributes attrs = sr.getAttributes();
0636:
0637: for (NamingEnumeration ae = attrs.getAll(); ae
0638: .hasMore();) {
0639: Attribute attr = (Attribute) ae.next();
0640: // logs trace
0641: System.out
0642: .println("attribute: " + attr.getID());
0643:
0644: //print each value
0645: for (NamingEnumeration e = attr.getAll(); e
0646: .hasMore();) {
0647: dn = (String) e.next();
0648:
0649: // logs trace
0650: System.out.println(" dn: " + dn);
0651:
0652: // dn : cn = X, subtree
0653: // 3 cases:
0654: // 1- if subtree = UserDn then get the User Id
0655: // 2- if subtree = RoleDn then the member is also a group, then call recusively the getGroupMembers ??
0656: // 3- if subtree != UserDn and != RoleDn then return null
0657: // => At now we suppose that we are always in case 1
0658: //get the uid of the dn's ldap object
0659: String userId = getUserIdFromDn(dn);
0660:
0661: // logs trace
0662: System.out.println(" uid: " + userId);
0663:
0664: if (!"".equals(userId)) {
0665: al.add(userId);
0666: }
0667: }
0668: }
0669: } // end while
0670: ne.close();
0671: } catch (NamingException e) {
0672: e.printStackTrace();
0673: throw new HeroException(
0674: "Error searching userId from group members in LDAP");
0675: }
0676: } // end else
0677: return al;
0678: }
0679:
0680: /**
0681: * Get the uid giving a partial DN (without Base suffix) as input.
0682: * It requires that the ldap resource within the AS. is configured and activated.
0683: *
0684: * @ejb:interface-method view-type="both"
0685: * @ejb:transaction type="Required"
0686: * @throws HeroException
0687: *
0688: **/
0689: public String getUserIdFromPartialDn(String partialDN)
0690: throws HeroException {
0691: //Initialize the InitialContext passed on the
0692: // connection parameters
0693: Hashtable env = new Hashtable();
0694:
0695: env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
0696: env.put(Context.PROVIDER_URL, providerUrl);
0697: env
0698: .put(Context.SECURITY_AUTHENTICATION,
0699: securityAuthentication);
0700: env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
0701: env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
0702: env.put(Context.REFERRAL, referral);
0703:
0704: try {
0705: dirContext = new InitialDirContext(env);
0706: } catch (NamingException na) {
0707: throw new HeroException(
0708: "cannot initialize the initialContext of naming"
0709: + na.getMessage(), na);
0710: }
0711:
0712: ArrayList al = new ArrayList();
0713: String userId = "";
0714: String filter = "uid=*";
0715: NamingEnumeration ne = null;
0716: // Specify the ids of the attributes to return
0717: // and the scope of the search
0718: SearchControls constraints = new SearchControls();
0719: String[] attrIDs = { "uid" };
0720: constraints.setReturningAttributes(attrIDs);
0721: //constraints.setSearchScope(SearchControls.SUBTREE_SCOPE) ;
0722: constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
0723:
0724: // Search for objects that have those matching attributes
0725: try {
0726: //debug
0727: System.out
0728: .println("BnLdapBean/getUserIdFromPartialDn: partialDN = "
0729: + partialDN + " baseDn = " + baseDn);
0730: ne = dirContext.search(partialDN + "," + baseDn, filter,
0731: constraints);
0732: while (ne.hasMore()) {
0733: SearchResult sr = (SearchResult) ne.next();
0734: //String dn = sr.getName() + ", " + userDN + "," + baseDn;
0735: Attributes attrs = sr.getAttributes();
0736: Attribute attr = attrs.get("uid");
0737: userId = (String) attr.get();
0738: }
0739: ne.close();
0740: } catch (NamingException na) {
0741: throw new HeroException("Error searching directory :"
0742: + na.getMessage(), na);
0743: }
0744: return userId;
0745: }
0746:
0747: /***************************************************************************
0748: getSortedMapUidMailLdap
0749: Target: Get user "uid" and "mail" and return a sortedMap
0750: ****************************************************************************/
0751: private Map getTreeMapUidMailLdap() {
0752: TreeMap treeMap = new TreeMap();
0753: try {
0754:
0755: // using the User Search Filter as jonas-realm_1_0.dtd : "uid={0}"
0756: MessageFormat form = new MessageFormat(userSearchFilter);
0757: // Get all user by replacing the parameter {0} by *
0758: Object[] testArgs = { "*" };
0759: String filter = form.format(testArgs);
0760:
0761: // logs trace
0762: System.out.println("Filter used to get user in Ldap: "
0763: + filter);
0764:
0765: // Specify the ids of the attributes to return
0766: // and the scope of the search
0767: SearchControls constraints = new SearchControls();
0768:
0769: // get the attribut name from "User serach Filter" ie: uid={0}
0770: int indSep = userSearchFilter.indexOf('=');
0771: StringBuffer sb = new StringBuffer(userSearchFilter);
0772: String userParameter = sb.substring(0, indSep);
0773:
0774: // logs trace
0775: System.out.println("UserParameter from userSearchFilter = "
0776: + userParameter);
0777:
0778: String[] attrIDs = { userParameter, "mail" };
0779: constraints.setReturningAttributes(attrIDs);
0780:
0781: constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
0782:
0783: // logs trace
0784: // Set SearchControl for "CountLimit" and "TimeLimit" for information
0785: System.out.println("Naming CountLimit = "
0786: + constraints.getCountLimit());
0787: System.out.println("Naming TimeLimit = "
0788: + constraints.getTimeLimit());
0789:
0790: // Search for objects that have those matching attributes
0791: NamingEnumeration ne = dirContext.search(userDN + ","
0792: + baseDn, filter, constraints);
0793: String userId = "";
0794: String userMail = "";
0795: Attribute attr = null;
0796: while (ne.hasMore()) {
0797: SearchResult sr = (SearchResult) ne.next();
0798:
0799: Attributes attrs = sr.getAttributes();
0800: // uid -> key
0801: attr = attrs.get(userParameter);
0802: userId = (String) attr.get();
0803: // mail -> value
0804: if (attrs.get("mail") != null) {
0805: attr = attrs.get("mail");
0806: userMail = (String) attr.get();
0807: } else {
0808: userMail = "";
0809: }
0810:
0811: treeMap.put(userId, userMail);
0812: }
0813: ne.close();
0814:
0815: // logs trace
0816: System.out
0817: .println("------------------"
0818: + userParameter
0819: + " and mail found un Ldap -------------------------");
0820: printUidMailCollection(treeMap);
0821: } // end try
0822: catch (SizeLimitExceededException e) {
0823: // logs trace
0824: System.err.println(e);
0825: System.err.println("");
0826: System.err
0827: .println("Sizelimit Exceeded from the LDAP server.");
0828: System.out
0829: .println("Please contact the ldap administrator to extend this limit,");
0830: System.out
0831: .println("or reduce the scope of the user searching.");
0832: System.err.println("");
0833: e.printStackTrace();
0834: } catch (NamingException e) {
0835: e.printStackTrace();
0836: System.err.println("Error reading directory" + e);
0837: throw new EJBException("Error reading directory");
0838: }
0839: return treeMap;
0840: }
0841:
0842: /***************************************************************************
0843: getUidFromLdap
0844: Target: Get user uid and return a sorted collection
0845: ****************************************************************************/
0846: private Collection getUidFromLdap() {
0847: TreeSet sorter = new TreeSet();
0848: try {
0849:
0850: // using the User Search Filter as jonas-realm_1_0.dtd : "uid={0}"
0851: MessageFormat form = new MessageFormat(userSearchFilter);
0852: // Get all user by replacing the parameter {0} by *
0853: Object[] testArgs = { "*" };
0854: String filter = form.format(testArgs);
0855:
0856: // logs trace
0857: System.out.println("Filter used to get user in Ldap: "
0858: + filter);
0859:
0860: // Specify the ids of the attributes to return
0861: // and the scope of the search
0862: SearchControls constraints = new SearchControls();
0863:
0864: // get the attribut name from "User serach Filter" ie: uid={0}
0865: int indSep = userSearchFilter.indexOf('=');
0866: StringBuffer sb = new StringBuffer(userSearchFilter);
0867: String userParameter = sb.substring(0, indSep);
0868:
0869: // logs trace
0870: System.out.println("UserParameter from userSearchFilter = "
0871: + userParameter);
0872:
0873: String[] attrIDs = { userParameter };
0874: constraints.setReturningAttributes(attrIDs);
0875:
0876: constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
0877:
0878: // logs trace
0879: // Set SearchControl for "CountLimit" and "TimeLimit" for information
0880: System.out.println("Naming CountLimit = "
0881: + constraints.getCountLimit());
0882: System.out.println("Naming TimeLimit = "
0883: + constraints.getTimeLimit());
0884:
0885: // Search for objects that have those matching attributes
0886: NamingEnumeration ne = dirContext.search(userDN + ","
0887: + baseDn, filter, constraints);
0888:
0889: while (ne.hasMore()) {
0890: SearchResult sr = (SearchResult) ne.next();
0891: //String dn = sr.getName() + ", " + userDN + "," + baseDn;
0892: Attributes attrs = sr.getAttributes();
0893: Attribute attr = attrs.get(userParameter);
0894: String userId = (String) attr.get();
0895: sorter.add(userId);
0896: // logs trace
0897: System.out.println(userId);
0898: }
0899: ne.close();
0900:
0901: // logs trace
0902: System.out.println("------------------" + userParameter
0903: + " found in Ldap -------------------------");
0904:
0905: printUidCollection(sorter);
0906: } // end try
0907: catch (SizeLimitExceededException e) {
0908: System.err.println(e);
0909: System.err
0910: .println("Sizelimit Exceeded from the LDAP server.");
0911: System.out
0912: .println("-> Please contact the ldap administrator to extend this limit.");
0913: System.out
0914: .println("-> or reduce the scope of the user searching.");
0915: System.err.println("Stack of the Error:");
0916: e.printStackTrace();
0917: } catch (NamingException e) {
0918: e.printStackTrace();
0919: System.err.println("Error reading directory" + e);
0920: throw new EJBException("Error reading directory");
0921: }
0922: return sorter;
0923: }
0924:
0925: /***************************************************************************
0926: getAttributesFromUser
0927: ex. to get attributes in naming (ldap) service
0928: ****************************************************************************/
0929: private Collection getAttributesFromUser(String userID) {
0930:
0931: try {
0932: ArrayList al = new ArrayList();
0933:
0934: // using the User Search Filter as jonas-realm_1_0.dtd : "uid={0}"
0935: MessageFormat form = new MessageFormat(userSearchFilter);
0936: Object[] testArgs = { userID };
0937: String filter = form.format(testArgs);
0938:
0939: // logs trace
0940: System.out.println("Filter to get the users name in LDAP: "
0941: + filter);
0942:
0943: // Specify the ids of the attributes to return
0944: // and the scope of the search
0945: SearchControls constraints = new SearchControls();
0946: String[] attrIDs = { "sn", "givenname", "cn", "mail" };
0947: constraints.setReturningAttributes(attrIDs);
0948: constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
0949:
0950: // Search for objects that have those matching attributes
0951: NamingEnumeration ne = dirContext.search(userDN + ","
0952: + baseDn, filter, constraints);
0953:
0954: while (ne.hasMore()) {
0955: SearchResult sr = (SearchResult) ne.next();
0956: //String dn = sr.getName() + ", " + userDN + "," + baseDn;
0957: Attributes a = sr.getAttributes();
0958: al.add(a);
0959: }
0960: ne.close();
0961:
0962: // logs trace
0963: printUserAttributes(al);
0964:
0965: return al;
0966:
0967: } catch (NamingException e) {
0968: e.printStackTrace();
0969: System.err.println("Error reading directory" + e);
0970: throw new EJBException("Error reading directory");
0971: }
0972: }
0973:
0974: private String getUserIdFromDn(String dn) throws HeroException {
0975:
0976: try {
0977:
0978: ArrayList al = new ArrayList();
0979:
0980: String userId = "";
0981: //String filter = "dn=" + dn;
0982: String filter = "uid=*";
0983: // debug
0984: System.out
0985: .println("Filter to identify the user to get it's attributes: "
0986: + filter);
0987:
0988: // Specify the ids of the attributes to return
0989: // and the scope of the search
0990: SearchControls constraints = new SearchControls();
0991: String[] attrIDs = { "uid" };
0992: constraints.setReturningAttributes(attrIDs);
0993: //constraints.setSearchScope(SearchControls.SUBTREE_SCOPE) ;
0994: constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
0995:
0996: // Search for objects that have those matching attributes
0997: //NamingEnumeration ne = dirContext.search(userDN + "," + baseDn, filter, constraints);
0998: NamingEnumeration ne = dirContext.search(dn, filter,
0999: constraints);
1000: while (ne.hasMore()) {
1001: SearchResult sr = (SearchResult) ne.next();
1002: //String dn = sr.getName() + ", " + userDN + "," + baseDn;
1003: Attributes attrs = sr.getAttributes();
1004: Attribute attr = attrs.get("uid");
1005: userId = (String) attr.get();
1006: }
1007: ne.close();
1008: return userId;
1009:
1010: } catch (NamingException e) {
1011: System.err.println("ERROR getting Id from dn = " + dn
1012: + " - " + e);
1013: throw new HeroException("Error reading directory");
1014: }
1015: }
1016:
1017: /**********************************************
1018: get all users in bonita database
1019: **********************************************/
1020: private Collection getAllSortedBnUsers() throws HeroException {
1021: TreeSet sorter = new TreeSet();
1022: Collection unSortedList = null;
1023: try {
1024: ProjectSessionLocalHome projecth = (ProjectSessionLocalHome) ProjectSessionUtil
1025: .getLocalHome();
1026: ProjectSessionLocal projectsession = projecth.create();
1027: // get users in bonita database
1028: unSortedList = projectsession.getAllUsers();
1029:
1030: Iterator it = unSortedList.iterator();
1031: while (it.hasNext()) {
1032: sorter.add(it.next());
1033: }
1034: } catch (Exception e) {
1035: e.printStackTrace();
1036: System.err
1037: .println("Error in BnLdapBean for getAllSortedBnUsers "
1038: + e);
1039: throw new HeroException(
1040: "Error in BnLdapBean for getAllSortedBnUsers"
1041: + e.getMessage());
1042: }
1043: // logs trace
1044: System.out
1045: .println("------------------ Bonita registered users -------------------------");
1046: printUidCollection(sorter);
1047: return sorter;
1048: }
1049:
1050: /**
1051: * Creates the BnLdap Bean. This method is the first one to invoke in order to
1052: * use BnLdap API.
1053: * The client user of the API must be authentified otherwise an exception will be thrown
1054: *
1055: * @ejb:create-method view-type="both"
1056: **/
1057: public void ejbCreate() {
1058: }
1059:
1060: /**
1061: * Internal Enterprise Java Beans method.
1062: **/
1063: public void ejbActivate() {
1064: }
1065:
1066: /**
1067: * Internal Enterprise Java Beans method.
1068: **/
1069: public void ejbPassivate() {
1070: // Nothing to do for this simple example
1071: }
1072:
1073: /**
1074: * Internal Enterprise Java Beans method.
1075: **/
1076: public void ejbRemove() {
1077: // Nothing to do for this simple example
1078: }
1079:
1080: /****************************************************************
1081: Utility: printUidCollection Only to print out !
1082: ***************************************************************/
1083: private static void printUidCollection(Collection co) {
1084: // Example for searching user attributes in ldap giving the "uid" attribute (not unique !)
1085: try {
1086: Collection c = co;
1087: Iterator it = c.iterator();
1088: Attributes a = null;
1089: while (it.hasNext()) {
1090: //a = (Attributes)it.next();
1091: //printAttrs(a);
1092: System.out.println((String) (it.next()));
1093: }// end while
1094: } catch (Exception e) {
1095: System.err
1096: .println("erreur Client pour la recherche des uid dans ldap : "
1097: + e);
1098: System.exit(2);
1099: }
1100: }
1101:
1102: /****************************************************************
1103: Utility: printUidMailCollection return TreeMap
1104: ***************************************************************/
1105: private static void printUidMailCollection(Map map) {
1106: // Example for searching user attributes in ldap giving the "uid" attribute (not unique !)
1107: try {
1108: Set entries = map.entrySet();
1109: Iterator iterator = entries.iterator();
1110: while (iterator.hasNext()) {
1111: Map.Entry entry = (Map.Entry) iterator.next();
1112: System.out.println(entry.getKey() + " : "
1113: + entry.getValue());
1114: }
1115: } catch (Exception e) {
1116: System.err
1117: .println("erreur Client pour la recherche des uid dans ldap : "
1118: + e);
1119: System.exit(2);
1120: }
1121: }
1122:
1123: /****************************************************************
1124: Utility: printUserAttributes
1125: ***************************************************************/
1126: private static void printUserAttributes(Collection co) {
1127: // Example for searching user attributes in ldap giving the "uid" attribute (not unique !)
1128: try {
1129: Collection c = co;
1130: Iterator it = c.iterator();
1131: Attributes a = null;
1132: System.out
1133: .println("------------------ search attributes -------------------------");
1134: while (it.hasNext()) {
1135: a = (Attributes) it.next();
1136: printAttrs(a);
1137: }// end while
1138: } catch (Exception e) {
1139: System.err
1140: .println("erreur chez le client pour la recherche des attributs dans ldap: "
1141: + e);
1142: System.exit(2);
1143: }
1144: }
1145:
1146: /****************************************************************
1147: Utility : printGroupMember
1148: ***************************************************************/
1149: private static void printGroupMember(Collection co) {
1150: // Example for searching mmber of a goup in ldap
1151: try {
1152: Attributes a = null;
1153: // recup d'une array list of SearchResult
1154: Collection c = co;
1155: Iterator it = c.iterator();
1156: System.out.println("");
1157:
1158: while (it.hasNext()) {
1159: SearchResult sr = (SearchResult) it.next();
1160: // recup du nom du name et des uniquemember du groupe
1161: System.out.println("");
1162: System.out.println("------- Group name = "
1163: + sr.getName());
1164: a = sr.getAttributes();
1165: printAttrs(a);
1166: } // end while
1167: } catch (Exception e) {
1168: System.err
1169: .println("Client error pour la recherche de groupes dans ldap : "
1170: + e);
1171: System.exit(2);
1172: }
1173: }
1174:
1175: /***********************************
1176: Utility for printing for debug ...
1177: ************************************/
1178: private static void printAttrs(Attributes attrs) {
1179: if (attrs == null) {
1180: System.out.println("No attributes");
1181: } else {
1182: /* Print each attribute */
1183: try {
1184: for (NamingEnumeration ae = attrs.getAll(); ae
1185: .hasMore();) {
1186: Attribute attr = (Attribute) ae.next();
1187: System.out.println("attribute: " + attr.getID());
1188:
1189: /* print each value */
1190: for (NamingEnumeration e = attr.getAll(); e
1191: .hasMore(); System.out.println("value: "
1192: + e.next()))
1193: ;
1194: }
1195: } catch (NamingException e) {
1196: e.printStackTrace();
1197: }
1198: }
1199: }
1200:
1201: } // end class
|