Example usage for javax.naming.directory SearchControls OBJECT_SCOPE

List of usage examples for javax.naming.directory SearchControls OBJECT_SCOPE

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls OBJECT_SCOPE.

Prototype

int OBJECT_SCOPE

To view the source code for javax.naming.directory SearchControls OBJECT_SCOPE.

Click Source Link

Document

Search the named object.

Usage

From source file:SearchObject.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {/*  www.j a v a  2  s  .  c  o m*/
        // Create initial context
        DirContext ctx = new InitialDirContext(env);

        // Specify the ids of the attributes to return
        String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

        // Specify the search filter to match
        // Ask for objects with attribute sn == Geisel and which have
        // the "mail" attribute.
        String filter = "(&(sn=Geisel)(mail=*))";

        // Search subtree for objects using filter
        NamingEnumeration answer = ctx.search("cn=Ted Geisel, ou=People", filter, ctls);

        // Print the answer
        // Search.printSearchEnumeration(answer);

        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Compare.java

public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {/*from  ww w  .jav a  2 s  . c  om*/
        // Create initial context
        DirContext ctx = new InitialDirContext(env);

        // Value of attribute
        byte[] key = { (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66,
                (byte) 0x67 };

        // Set up search controls
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(new String[0]); // return no attrs
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // search object only

        // Invoke search method that will use the LDAP "compare" operation
        NamingEnumeration answer = ctx.search("cn=S. User, ou=NewHires", "(mySpecialKey={0})",
                new Object[] { key }, ctls);

        // Print the answer
        // FilterArgs.printSearchEnumeration(answer);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:ldap.ActiveLoginImpl.java

/**
 * Returns whether this user is listed in the admin users role
 *
 * @param login/* w ww.j  a  v  a  2s  . com*/
 * @return
 * @throws Exception
 */
public boolean isAdmin(String login, DirContext context, String DN) throws Exception {
    NamingEnumeration result = null;

    String[] returnAttributes = new String[] { "uniqueMember" };

    /* specify search constraints to search subtree */
    SearchControls constraints = new SearchControls();

    constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
    constraints.setCountLimit(0);
    constraints.setTimeLimit(0);

    constraints.setReturningAttributes(returnAttributes);
    /*
            Entry user = null;
            try {
    user = searcher.getUser(LdapConstants.ldapAttrLogin, login, context);
            } catch (NamingException e) {
               throw new LdapException("getUser NamingException" + e.getMessage(), e);
            }
       String DN = null;
            if (user == null) {
               logger.info("USER DOES NOT EXIST");
               return false;
            } else {
          DN = user.getName().toString();
               if (DN != null) {
      logger.info("DN = " + DN);
               }
       }
    */

    //result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember="+getUserDN(login)+")", constraints);
    result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember=" + DN + ")", constraints);

    if (result.hasMore()) {
        if (debug) {
            SearchResult sResult = (SearchResult) result.next();
            logger.info("Read Admin Roles Object with members: " + sResult.getAttributes().toString());
        }
        return true;
    } else if (debug)
        logger.info("Failed to find admin object with member " + DN);

    return false;
}

From source file:edu.internet2.middleware.psp.util.PSPUtil.java

/**
 * Return <code>SearchControls</code> search scope from an SPML <code>Scope</code>.
 * //from  ww w.j av  a2 s.c  o m
 * @param scope the SPML scope
 * @return the javax.naming.directory search scope as an int
 */
public static int getScope(Scope scope) {

    if (scope.equals(Scope.ONELEVEL)) {
        return SearchControls.OBJECT_SCOPE;
    } else if (scope.equals(Scope.SUBTREE)) {
        return SearchControls.SUBTREE_SCOPE;
    } else if (scope.equals(Scope.PSO)) {
        return SearchControls.OBJECT_SCOPE;
    }

    throw new IllegalArgumentException("Unknow scope " + scope);
}

From source file:ldap.SearchUtility.java

public boolean checkPassword(String DN, String pwdAtt, String value, DirContext context)
        throws NamingException, UnsupportedEncodingException {
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(new String[0]); // Return no attrs
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // Search object only
    //byte[] pwdBytes = value.getBytes("UTF-8");
    byte[] pwdBytes = value.getBytes(LdapConstants.UTF8);

    // Invoke search method that will use the LDAP "compare" operation
    NamingEnumeration answer = context.search(DN, "(" + pwdAtt + "={0})", new Object[] { pwdBytes }, ctls);
    return answer.hasMore();
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public void execute(LookupRequest lookupRequest, LookupResponse lookupResponse) {

    Ldap ldap = null;//from w  w w.  ja  v a2s. c  om
    try {
        // will not return AD Range option attrs
        // Attributes attributes = ldap.getAttributes(escapedDn, retAttrs);

        SearchFilter sf = new SearchFilter();
        sf.setFilter("objectclass=*");
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);

        // This lookup requests attributes defined for *all* objects.
        // Perhaps there should be two searches, one for the identifier
        // and a second for attributes.
        String[] retAttrs = getPSP().getNames(getId(), lookupRequest.getReturnData()).toArray(new String[] {});
        sc.setReturningAttributes(retAttrs);

        // TODO logging
        String dn = lookupRequest.getPsoID().getID();
        String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn);

        ldap = ldapPool.checkOut();

        LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(lookupRequest));
        Iterator<SearchResult> searchResults = ldap.search(escapedDn, sf, sc);
        LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(lookupRequest));

        if (!searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
            return;
        }

        SearchResult result = searchResults.next();

        if (searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.CUSTOM_ERROR, "More than one result found.");
            return;
        }
        Attributes attributes = result.getAttributes();

        // return attributes in order defined by config
        OrderedLdapBeanFactory orderedLdapBeanFactory = new OrderedLdapBeanFactory();
        // sort values
        SortedLdapBeanFactory sortedLdapBeanFactory = new SortedLdapBeanFactory();

        LdapAttributes ldapAttributes = orderedLdapBeanFactory.newLdapAttributes();
        for (String retAttr : retAttrs) {
            Attribute attr = attributes.get(retAttr);
            if (attr != null) {
                LdapAttribute ldapAttribute = sortedLdapBeanFactory.newLdapAttribute();
                ldapAttribute.setAttribute(attr);
                ldapAttributes.addAttribute(ldapAttribute);
            }
        }

        LdapEntry entry = sortedLdapBeanFactory.newLdapEntry();
        entry.setDn(dn);
        entry.setLdapAttributes(ldapAttributes);

        if (this.isLogLdif()) {
            LdapResult lr = sortedLdapBeanFactory.newLdapResult();
            lr.addEntry(entry);
            LdifResultConverter lrc = new LdifResultConverter();
            LOG.info("Target '{}' - LDIF\n{}", getId(), lrc.toLdif(lr));
        }

        // build pso
        lookupResponse.setPso(getPSO(entry, lookupRequest.getReturnData()));

    } catch (NameNotFoundException e) {
        fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
    } catch (LdapPoolException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (InvalidNameException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (NamingException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (DSMLProfileException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (Spml2Exception e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        if (ldap != null) {
            ldapPool.checkIn(ldap);
        }
    }
}

From source file:com.funambol.LDAP.security.LDAPMailUserProvisioningOfficer.java

/**
 * Return a S4J user if successful bind to ldap
 * null if user or password is wrong//  w  w  w. ja  v a 2  s .  c om
 *      
 * TODO if I don't need to provision user on ldap,  I could avoid some of that stuff.. 
 * when binding, it retrieves imap/smtp server data to provision mail push
 * @param username
 * @param password
 * @return the {@link Sync4jUser} created from ldap fields
 */
public LDAPUser bindUserToLdap(String username, String password) {
    LDAPUser ldapUser = null;
    LdapManagerInterface ldapInterface = null;
    LdapManagerInterface ldapBindInterface = null;
    String userDN = null;
    /* TODO
     * this is now done creating an eventually authenticated context specified in 
     *  configuration file.
     *  moreover this context is shared between all ldap connections,
     *  so could be better defined at application server level 
     */
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        // use a bean configuration file
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(t.tmpLdapUrl, t.tmpBaseDn, getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // search the user binding with default ldap credential defined in the Officer.xml
            ldapInterface.setBaseDn(t.tmpBaseDn);
            SearchResult sr = ldapInterface.searchOneEntry(t.tmpUserSearch, new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr != null) {
                userDN = sr.getNameInNamespace().trim();
                log.info("binding with dn:" + userDN);
            } else {
                log.info("Username [" + username + "] not found");
                ldapInterface.close();
                return null;
            }
        } else { // use append
            userDN = "uid=" + username + "," + t.tmpBaseDn;
        }

        ldapInterface.close();
        ldapBindInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapBindInterface.init(t.tmpLdapUrl, userDN, userDN, password, false, false, null);
        SearchResult sr = ldapBindInterface.searchOneEntry("(objectclass=*)", getLdapAttributesToRetrieve(),
                SearchControls.OBJECT_SCOPE);

        if (sr != null) {
            ldapUser = new LDAPUser();
            ldapUser.setUsername(username);
            ldapUser.setPassword(password);

            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_EMAIL))) {
                ldapUser.setEmail(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_EMAIL)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_FIRSTNAME))) {
                ldapUser.setFirstname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_FIRSTNAME)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_LASTNAME))) {
                ldapUser.setLastname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_LASTNAME)));
            }

            // set attributes to be passed to LDAP and CalDAV connector
            ldapUser.setUserDn(userDN);
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_ADDRESSBOOK))) {
                ldapUser.setPsRoot(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_ADDRESSBOOK)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_CALENDAR))) {
                ldapUser.setCalUri(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_CALENDAR)));
            }

            // get server attributes from LDAP if not void
            if (getImapServer() == null && StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_IMAP))) {
                setImapServer(LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_IMAP)));
            }
            if (getSmtpServer() == null && StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_SMTP))) {
                setSmtpServer(LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_SMTP)));
            }

            if (Configuration.getConfiguration().isDebugMode()) {
                if (log.isTraceEnabled()) {
                    StringBuffer sb = new StringBuffer(64);
                    sb.append("psRoot: ").append(ldapUser.getPsRoot()).append("\n").append("calUri: ")
                            .append(ldapUser.getCalUri()).append("\n").append("imapServer: ")
                            .append(getImapServer()).append("\n").append("smtpServer: ")
                            .append(getSmtpServer());

                    log.trace(sb.toString());

                }
            }
        } else {
            ldapUser = null;
        }
        ldapBindInterface.close();

    } catch (SyncSourceException e1) {
        log.error("Can't instantiate context: " + e1.getMessage());
        ldapUser = null;
    } catch (NamingException e) {
        log.warn("Can't retrieve mailserver attributes from ldap: " + e.getMessage());
        ldapUser = null;
    } catch (LDAPAccessException e) {
        log.error("Can't instantiate context: " + e.getMessage());
        ldapUser = null;
    } finally {
        if (ldapInterface != null) {
            ldapInterface.close();
        }
        if (ldapBindInterface != null) {
            ldapBindInterface.close();
        }
    }
    return ldapUser;
}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java

/** Get the AD-derived access tokens for a user and domain */
protected List<String> getADTokens(String userPart, String domainPart, String userName)
        throws NameNotFoundException, NamingException, ManifoldCFException {
    // Now, look through the rules for the matching domain controller
    String domainController = null;
    for (DCRule rule : dCRules) {
        String suffix = rule.getSuffix();
        if (suffix.length() == 0
                || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT))
                        && (suffix.length() == domainPart.length()
                                || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) {
            domainController = rule.getDomainControllerName();
            break;
        }//from   www .j  a v a 2  s. co  m
    }

    if (domainController == null)
        // No AD user
        return null;

    // Look up connection parameters
    DCConnectionParameters dcParams = dCConnectionParameters.get(domainController);
    if (dcParams == null)
        // No AD user
        return null;

    // Use the complete fqn if the field is the "userPrincipalName"
    String userBase;
    String userACLsUsername = dcParams.getUserACLsUsername();
    if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) {
        userBase = userName;
    } else {
        userBase = userPart;
    }

    //Build the DN searchBase from domain part
    StringBuilder domainsb = new StringBuilder();
    int j = 0;
    while (true) {
        if (j > 0)
            domainsb.append(",");

        int k = domainPart.indexOf(".", j);
        if (k == -1) {
            domainsb.append("DC=").append(ldapEscape(domainPart.substring(j)));
            break;
        }
        domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k)));
        j = k + 1;
    }

    // Establish a session with the selected domain controller
    LdapContext ctx = createDCSession(domainController);

    //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com")
    String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername);
    if (searchBase == null)
        return null;

    //specify the LDAP search filter
    String searchFilter = "(objectClass=user)";

    //Create the search controls for finding the access tokens   
    SearchControls searchCtls = new SearchControls();

    //Specify the search scope, must be base level search for tokenGroups
    searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

    //Specify the attributes to return
    String returnedAtts[] = { "tokenGroups", "objectSid" };
    searchCtls.setReturningAttributes(returnedAtts);

    //Search for tokens.  Since every user *must* have a SID, the "no user" detection should be safe.
    NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

    List<String> theGroups = new ArrayList<String>();
    String userToken = userTokenFromLoginName(domainPart + "\\" + userPart);
    if (userToken != null)
        theGroups.add(userToken);

    //Loop through the search results
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        //the sr.GetName should be null, as it is relative to the base object

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                        String sid = sid2String((byte[]) e.next());
                        String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid)
                                : groupTokenFromSID(sid);
                        theGroups.add(token);
                    }
                }
            } catch (NamingException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
    }

    if (theGroups.size() == 0)
        return null;

    // User is in AD, so add the 'everyone' group
    theGroups.add(everyoneGroup());
    return theGroups;
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * Return a S4J user if successful bind to ldap
 * null if user or password is wrong/*  www  . ja v  a2 s  .c om*/
 *      
 * TODO if I don't need to provision user on ldap,  I could avoid some of that stuff.. 
 * when binding, it retrieves imap/smtp server data to provision mail push
 * @param username
 * @param password
 * @return the {@link Sync4jUser} created from ldap fields
 */
public LDAPUser bindUserToLdap(String username, String password) {
    LDAPUser ldapUser = null;
    String userDN = null;
    LdapManagerInterface ldapBindInterface = null;
    /* TODO
     * this is now done creating an eventually authenticated context specified in 
     *  configuration file.
     *  moreover this context is shared between all ldap connections,
     *  so could be better defined at application server level 
     */
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        // use a bean configuration file
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(t.tmpLdapUrl, t.tmpBaseDn, getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // search the user binding with default ldap credential defined in the Officer.xml
            ldapInterface.setBaseDn(t.tmpBaseDn);
            SearchResult sr = ldapInterface.searchOneEntry(t.tmpUserSearch, new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr != null) {
                userDN = sr.getNameInNamespace().trim();
                log.info("binding with dn:" + userDN);
            } else {
                log.info("Username" + username + "not found");
                return null;
            }
        } else { // use append
            userDN = "uid=" + username + "," + baseDn;
        }

        ldapInterface.close();
        ldapBindInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapBindInterface.init(t.tmpLdapUrl, userDN, userDN, password, false, false, null);
        SearchResult sr = ldapBindInterface.searchOneEntry("(objectclass=*)", getLdapAttributesToRetrieve(),
                SearchControls.OBJECT_SCOPE);

        if (sr != null) {
            ldapUser = new LDAPUser();
            ldapUser.setUsername(username);
            ldapUser.setPassword(password);

            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_EMAIL))) {
                ldapUser.setEmail(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_EMAIL)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_FIRSTNAME))) {
                ldapUser.setFirstname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_FIRSTNAME)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_LASTNAME))) {
                ldapUser.setLastname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_LASTNAME)));
            }

            // set attributes to be passed to LDAP and CalDAV connector
            ldapUser.setUserDn(userDN);
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_ADDRESSBOOK))) {
                ldapUser.setPsRoot(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_ADDRESSBOOK)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_CALENDAR))) {
                ldapUser.setPsRoot(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_CALENDAR)));
            }
        } else {
            return null;
        }

    } catch (SyncSourceException e1) {
        log.error("Can't instantiate context: " + e1.getMessage());
        ldapUser = null;
    } catch (NamingException e) {
        log.warn("Can't retrieve mailserver attributes from ldap: " + e.getMessage());
        ldapUser = null;
    } catch (LDAPAccessException e) {
        log.error("Can't instantiate context: " + e.getMessage());
        ldapUser = null;
    } finally {
        if (ldapInterface != null) {
            ldapInterface.close();
        }
        if (ldapBindInterface != null) {
            ldapBindInterface.close();
        }
    }

    return ldapUser;
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * This method will perform multiple queries into Active Directory
 * in order to resolve what groups a user is a member of.  The
 * logic will identify nested groups and add them to the table.
 * <p>/* w  ww.jav a  2 s. c o  m*/
 * The LDAP_ACCOUNT_NAME field must be populated in the user bag
 * prior to invoking this method.  Any site specific fields can be
 * assigned to the user bag will be included in the attribute query.
 * </p>
 * <p>
 * Any site specific fields can be assigned to the group bag will
 * be included in the attribute query.
 * </p>
 *
 * @param aUserBag Active Directory user attributes.
 * @param aGroupBag Active Directory group attributes.
 *
 * @return Table of groups that the user is a member of.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public DataTable loadUserGroupsByAccountName(DataBag aUserBag, DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    DataBag groupBag;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserGroupsByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    // First, we will populate our user bag so that we can obtain the distinguished name.

    loadUserByAccountName(aUserBag);

    // Now we will use the DN to find all of the groups the user is a member of.

    String distinguishedName = aUserBag.getValueAsString(LDAP_DISTINGUISHED_NAME);
    if (StringUtils.isEmpty(distinguishedName))
        distinguishedName = getPropertyValue("user_searchbasedn", null);

    // Next, we will initialize our group membership table.

    DataTable memberTable = new DataTable(aUserBag);
    memberTable.setName(String.format("%s Group Membership", aUserBag.getValueAsString(LDAP_COMMON_NAME)));

    // The next logic section will query AD for all of the groups the user is a member
    // of.  Because we are following tokenGroups, we will gain access to nested groups.

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);

    SearchControls userSearchControls = new SearchControls();
    userSearchControls.setSearchScope(SearchControls.OBJECT_SCOPE);

    StringBuffer groupsSearchFilter = null;
    String ldapAttrNames[] = { "tokenGroups" };
    userSearchControls.setReturningAttributes(ldapAttrNames);

    try {
        NamingEnumeration<?> userSearchResponse = mLdapContext.search(distinguishedName, "(objectClass=user)",
                userSearchControls);
        if ((userSearchResponse != null) && (userSearchResponse.hasMoreElements())) {
            groupsSearchFilter = new StringBuffer();
            groupsSearchFilter.append("(|");

            SearchResult userSearchResult = (SearchResult) userSearchResponse.next();
            Attributes userResultAttributes = userSearchResult.getAttributes();
            if (userResultAttributes != null) {
                try {
                    for (NamingEnumeration<?> searchResultAttributesAll = userResultAttributes
                            .getAll(); searchResultAttributesAll.hasMore();) {
                        Attribute attr = (Attribute) searchResultAttributesAll.next();
                        for (NamingEnumeration<?> namingEnumeration = attr.getAll(); namingEnumeration
                                .hasMore();) {
                            objectSid = (byte[]) namingEnumeration.next();
                            groupsSearchFilter.append("(objectSid=" + objectSidToString2(objectSid) + ")");
                        }
                        groupsSearchFilter.append(")");
                    }
                } catch (NamingException e) {
                    String msgStr = String.format("LDAP Listing Member Exception: %s", e.getMessage());
                    appLogger.error(msgStr, e);
                    throw new NSException(msgStr);
                }
            }
            userSearchResponse.close();

            // Finally, we will query each group in the search filter and add it to the table.

            SearchControls groupSearchControls = new SearchControls();
            groupSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            int field = 0;
            int attrCount = aGroupBag.count();
            String[] groupsReturnedAtts = new String[attrCount];
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                groupsReturnedAtts[field++] = fieldName;
            }
            groupSearchControls.setReturningAttributes(groupsReturnedAtts);
            NamingEnumeration<?> groupSearchResponse = mLdapContext.search(groupSearchBaseDN,
                    groupsSearchFilter.toString(), groupSearchControls);
            while ((groupSearchResponse != null) && (groupSearchResponse.hasMoreElements())) {
                SearchResult groupSearchResult = (SearchResult) groupSearchResponse.next();
                Attributes groupResultAttributes = groupSearchResult.getAttributes();
                if (groupResultAttributes != null) {
                    groupBag = new DataBag(aGroupBag);
                    for (DataField complexField : groupBag.getFields()) {
                        fieldName = complexField.getName();
                        responseAttribute = groupResultAttributes.get(fieldName);
                        if (responseAttribute != null) {
                            if (fieldName.equals(LDAP_OBJECT_SID)) {
                                objectSid = (byte[]) responseAttribute.get();
                                fieldValue = objectSidToString2(objectSid);
                            } else
                                fieldValue = (String) responseAttribute.get();
                            if (StringUtils.isNotEmpty(fieldValue))
                                complexField.setValue(fieldValue);
                        }
                    }
                    memberTable.addRow(groupBag);
                }
            }
            if (groupSearchResponse != null)
                groupSearchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", distinguishedName, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return memberTable;
}