Example usage for javax.naming.directory SearchControls setSearchScope

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

Introduction

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

Prototype

public void setSearchScope(int scope) 

Source Link

Document

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Usage

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

private String searchAttributes(DirContext oDirContext, String sIDAttribute, String sMapperAttribute, String id)
        throws OAException {
    String sReturn = null;//from w w  w .  ja v a2 s  . com
    NamingEnumeration oNamingEnumeration = null;
    try {
        if (sIDAttribute == null) {
            _logger.error("No attribute name to map from supplied");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        StringBuffer sbQuery = new StringBuffer("(");
        sbQuery.append(sIDAttribute);
        sbQuery.append("=");
        sbQuery.append(JNDIUtil.escapeLDAPSearchFilter(id));
        sbQuery.append(")");
        String sSearchQuery = sbQuery.toString();

        String sSearchFor = sMapperAttribute;
        if (sSearchFor == null)
            sSearchFor = "*";

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        oScope.setReturningAttributes(new String[] { sSearchFor });

        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, sSearchQuery, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(sSearchQuery);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        if (!oNamingEnumeration.hasMore()) {
            _logger.debug("No result when searching for: " + sSearchQuery);
        } else {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();

            if (sMapperAttribute == null) {
                sReturn = oSearchResult.getName();
                sReturn += "," + _sDNBase;
            } else {
                Attributes oSearchedAttributes = oSearchResult.getAttributes();
                Attribute attrMapping = oSearchedAttributes.get(sMapperAttribute);
                if (attrMapping == null) {
                    _logger.debug("Mapping attribute not found: " + sMapperAttribute);
                } else {
                    Object oValue = attrMapping.get();
                    if (!(oValue instanceof String)) {
                        StringBuffer sbError = new StringBuffer("Returned value for mapping attribute '");
                        sbError.append(_sMapperAttribute);
                        sbError.append("' has a value which is not of type 'String'");
                        _logger.error(sbError.toString());
                        throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
                    }
                    sReturn = (String) oValue;
                }
            }
        }
    } catch (OAException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch mapping attribute for id: " + id, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for id: " + id, e);
            }
        }
    }
    return sReturn;
}

From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java

private boolean doBind(String sUserID, String sPassword) throws OAException, UserException {
    StringBuffer sbTemp = null;//w w  w.  j a v  a 2 s .com
    DirContext oDirContext = null;
    String sQuery = null;
    String sRelUserDn = null;
    boolean bResult = false;
    NamingEnumeration enumSearchResults = null;

    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl);
    htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver);
    htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (_bSSL) {
        htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    if (_sPrincipalDn.length() <= 0)
    // If no principal dn is known, we do a simple binding
    {
        String sEscUserID = JNDIUtil.escapeDN(sUserID);
        _logger.debug("Escaped user: " + sEscUserID);
        sbTemp = new StringBuffer(_sUserDn);
        sbTemp.append('=');
        sbTemp.append(sEscUserID);
        sbTemp.append(", ");
        sbTemp.append(_sBaseDn);
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());

        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            // If supplied credentials are invalid or when authentication fails
            // while accessing the directory or naming service.
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            // If communication with the directory or naming service fails.
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            // The initial dir context could not be created.
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {

            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e);
            }
        }
    } else //search through the subtree
    {
        // 1 - Try to bind to LDAP using the security principal's DN and its password
        htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
        } catch (AuthenticationException eA) {
            _logger.warn("Could not bind to LDAP server", eA);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 2 - Search through the context for user's DN relative to the base DN
        sQuery = resolveSearchQuery(sUserID);

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

        try {
            enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope);
        } catch (NamingException eN) {
            _logger.warn("User id not found in password backend for user: " + sUserID, eN);
            throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        } finally {
            try {

                oDirContext.close();
                oDirContext = null;

            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e);
            }
        }

        try {
            if (!enumSearchResults.hasMoreElements()) {
                StringBuffer sb = new StringBuffer("User '");
                sb.append(sUserID);
                sb.append("' not found during LDAP search. The filter was: '");
                sb.append(sQuery);
                sb.append("'");
                _logger.warn(sb.toString());
                throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
            }

            SearchResult searchResult = (SearchResult) enumSearchResults.next();
            sRelUserDn = searchResult.getName();
            if (sRelUserDn == null) {
                _logger.warn("no user dn was returned for '" + sUserID + "'.");
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
        } catch (NamingException eN) {

            _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 3 - Bind user using supplied credentials
        sbTemp = new StringBuffer(sRelUserDn);
        sbTemp.append(",");
        sbTemp.append(_sBaseDn);

        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {
            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e);
            }
        }
    }
    return bResult;
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns the values of the specified fields for the supplied id. 
 * @see IExternalStorage#getFields(java.lang.String, java.util.List)
 *//*w  w  w  .ja  v  a  2 s  .  c o  m*/
public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException {
    Hashtable<String, Object> htReturn = new Hashtable<String, Object>();
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] saFields = fields.toArray(new String[0]);
        oScope.setReturningAttributes(saFields);

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes '");
            sbFailed.append(fields);
            sbFailed.append("' for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.error("User unknown: " + id);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        }

        if (!oNamingEnumeration.hasMore()) {
            StringBuffer sbFailed = new StringBuffer("User with id '");
            sbFailed.append(id);
            sbFailed.append("' not found after LDAP search with filter: ");
            sbFailed.append(searchFilter);
            _logger.error(sbFailed.toString());
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
        Attributes oAttributes = oSearchResult.getAttributes();
        NamingEnumeration neAttributes = oAttributes.getAll();
        while (neAttributes.hasMore()) {
            Attribute oAttribute = (Attribute) neAttributes.next();
            String sAttributeName = oAttribute.getID();

            if (oAttribute.size() > 1) {
                Vector<Object> vValue = new Vector<Object>();
                NamingEnumeration neAttribute = oAttribute.getAll();
                while (neAttribute.hasMore())
                    vValue.add(neAttribute.next());

                htReturn.put(sAttributeName, vValue);
            } else {
                Object oValue = oAttribute.get();
                if (oValue == null)
                    oValue = "";
                htReturn.put(sAttributeName, oValue);
            }
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields: " + fields, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return htReturn;
}

From source file:ldap.SearchUtility.java

/**
 * A utility method to get a conrols object.  May be redundant; the default new Controls() would probably
 * suffice./*from   w w w .  j  a  va  2  s .  c om*/
 * @return a new SearchControls object that can be modified and passed to a context.search method.
 */
private SearchControls getSearchControls() {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    constraints.setCountLimit(0);
    constraints.setTimeLimit(0);
    return constraints;
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Retrieves the roles for the from the identity provider.
 *
 * @param username the user to get the roles for
 * @return the list of roles for the user
 * @throws PortalServiceException for any errors encountered
 *//*from   w w  w  . ja v  a2s .  co  m*/
@SuppressWarnings("rawtypes")
public List<String> findRoles(String username) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);

        // Search for groups the user belongs to in order to get their names
        // Create the search controls
        SearchControls groupsSearchCtls = new SearchControls();

        // Specify the search scope
        groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Specify the attributes to return
        String groupsReturnedAtts[] = { "cn" };
        groupsSearchCtls.setReturningAttributes(groupsReturnedAtts);

        String userDn = MessageFormat.format(userDNPattern, username);
        // Search for objects using the filter
        NamingEnumeration groupsAnswer = ctx.search(groupsSearchBase,
                MessageFormat.format(groupsFilterPattern, userDn), groupsSearchCtls);

        List<String> groups = new ArrayList<String>();
        // Loop through the search results
        while (groupsAnswer.hasMoreElements()) {

            SearchResult sr = (SearchResult) groupsAnswer.next();
            Attributes attrs = sr.getAttributes();

            if (attrs != null) {
                groups.add((String) attrs.get("cn").get());
            }

            if (sr.getObject() instanceof Context) {
                closeContext((Context) sr.getObject());
            }
        }
        return groups;
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to get groups.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * //from w  w  w.java  2  s  .c  o m
 * @param search
 * @param searchValue
 * @param attributeNames
 * @return naming enumeration
 */
protected NamingEnumeration getLdapResults(Search search, String searchValue, String[] attributeNames) {
    DirContext context = null;
    NamingEnumeration results = null;
    String filter = search.getParam("filter");
    if (filter == null) {
        log.error("Search filter not found for search type:  " + search.getSearchType());
        return results;
    }
    filter = filter.replaceAll("%TERM%", escapeSearchFilter(searchValue));
    String base = search.getParam("base");
    if (base == null) {
        base = "";
        log.error("Search base not found for:  " + search.getSearchType() + ". Using base \"\" ");

    }
    int scopeNum = -1;
    String scope = search.getParam("scope");
    if (scope != null) {
        scopeNum = getScope(scope);
    }
    if (scopeNum == -1) {
        scopeNum = SearchControls.SUBTREE_SCOPE;
        log.error("Search scope not found for: " + search.getSearchType() + ". Using scope SUBTREE_SCOPE.");
    }
    log.debug("searchType: " + search.getSearchType() + " filter: " + filter + " base: " + base + " scope: "
            + scope);
    try {
        context = new InitialDirContext(this.environment);
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(scopeNum);
        constraints.setReturningAttributes(attributeNames);
        results = context.search(base, filter, constraints);
    } catch (AuthenticationException ex) {
        log.error("Ldap Authentication Exception: " + ex.getMessage(), ex);
    } catch (NamingException ex) {
        log.error("Ldap NamingException: " + ex.getMessage(), ex);

    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ne) {
                // squelch, since it is already closed
            }
        }
    }
    return results;

}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

public Map<String, Collection<String>> findUsersWithRoles(DirContext dirContext)
        throws LdapControllerException {
    Map<String, Collection<String>> usersWithRoles = new HashMap<String, Collection<String>>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {//from w  ww .j a  v  a2  s .c  om

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = dirContext.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            String groupName = searchResult.getName();
            // cn=blabla we only want bla bla
            groupName = StringUtils.substringAfter(groupName, "=");

            Attribute uniqueMemberAttr = searchResult.getAttributes().get("uniquemember");

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {
                    String userName = allMembersEnum.next();
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    Collection<String> roles = usersWithRoles.get(userName);
                    if (roles == null) {
                        roles = new HashSet<String>();
                    }

                    roles.add(groupName);

                    usersWithRoles.put(userName, roles);

                }
            }

            log.debug("found groupName: '{}' with users: {}", groupName);

        }

        return usersWithRoles;
    } catch (NamingException e) {
        throw new LdapControllerException(e.getMessage(), e);
    }

    finally {

        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

From source file:ru.efo.security.ADUserDetailsService.java

private void describeRoles(DirContext context, Attribute memberOf, Set<String> groups, Set<String> roles)
        throws NamingException {
    if (memberOf != null) {
        for (int i = 0; i < memberOf.size(); i++) {
            Attribute attr = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }).get("CN");
            if (attr != null) {
                final String role = attr.get().toString();
                if (rolesMapping != null) {
                    for (String key : rolesMapping.keySet()) {
                        if (role.matches(rolesMapping.get(key))) {
                            if (logger.isLoggable(Level.FINE)) {
                                if (!roles.contains(key)) {
                                    logger.log(Level.FINE, "Role: " + key);
                                }/*from   www .j a v  a 2  s .co  m*/
                            }
                            roles.add(key);
                        }
                    }
                } else {
                    final String roleWithPrefix = (rolePrefix == null ? "" : rolePrefix)
                            + role.toUpperCase().replaceAll("(\\s|-)+", "_");
                    if (logger.isLoggable(Level.FINE)) {
                        if (!roles.contains(role)) {
                            logger.log(Level.FINE, "Role: " + roleWithPrefix);
                        }
                    }
                    roles.add(roleWithPrefix);
                }
                groups.add(role);

                if (recursiveRoleSearch) {
                    SearchControls controls = new SearchControls();
                    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                    NamingEnumeration<SearchResult> renum = context.search(
                            groupSearchBase != null ? groupSearchBase : userSearchBase, "(CN=" + role + ")",
                            controls);
                    if (renum.hasMore()) {
                        SearchResult searchResult = renum.next();
                        attr = searchResult.getAttributes().get("memberOf");
                        describeRoles(context, attr, groups, roles);
                    }
                }
            }
        }
    }
}

From source file:net.jolm.JolmLdapTemplate.java

private SearchControls getDefaultSearchControls(int searchScope, boolean returnObjFlag, String[] attributes) {
    SearchControls controls = new SearchControls();

    controls.setSearchScope(searchScope);
    controls.setReturningObjFlag(returnObjFlag);
    controls.setReturningAttributes(attributes);
    controls.setTimeLimit(this.searchTimeoutInMs);

    return controls;
}

From source file:ru.efo.security.ADUserDetailsService.java

private ADUserDetails loadUserByUsername(DirContext context, String username, String password)
        throws UsernameNotFoundException {
    try {//from   w  w  w.ja va  2 s  . c  om
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // search for username
        NamingEnumeration<SearchResult> renum = context.search(userSearchBase,
                "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls);
        if (!renum.hasMoreElements()) {
            throw new UsernameNotFoundException("User '" + username + "' is not exist");
        }
        SearchResult result = renum.next();
        final Attributes attributes = result.getAttributes();

        // User's display name
        String displayName = null;
        Attribute attr = attributes.get(displayNameAttribute);
        if (attr != null) {
            displayName = attr.get().toString();
        }
        if (!StringUtils.hasText(displayName))
            displayName = username;
        logger.log(Level.FINE, "Display name: " + displayName);

        // User's email
        String email = null;
        attr = attributes.get(emailAttribute);
        if (attr != null) {
            email = attr.get().toString();
        }
        logger.log(Level.FINE, "E-mail: " + email);

        // User's phone number
        String phone = null;
        attr = attributes.get(phoneAttribute);
        if (attr != null) {
            phone = attr.get().toString();
        }
        logger.log(Level.FINE, "Phone: " + phone);

        // Is user blocked
        boolean blocked = false;
        attr = attributes.get("userAccountControl");
        if (attr != null) {
            blocked = (Long.parseLong(attr.get().toString()) & 2) != 0;
        }
        logger.log(Level.FINE, "Blocked: " + blocked);

        // describe roles and groups
        final Set<String> roles = new TreeSet<>();
        final Set<String> groups = new TreeSet<>();
        Attribute memberOf = attributes.get("memberOf");
        describeRoles(context, memberOf, groups, roles);

        // Describe user primary role
        Attribute attrPrimaryGroupId = attributes.get("primaryGroupId");
        Attribute attrObjectSid = attributes.get("objectSid");
        if (attrPrimaryGroupId != null && attrObjectSid != null) {
            int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString());
            byte[] objectSid = (byte[]) attrObjectSid.get();
            // add primary group RID
            for (int i = 0; i < 4; i++) {
                objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF);
                primaryGroupId >>= 8;
            }
            StringBuilder tmp = new StringBuilder();
            for (int i = 2; i <= 7; i++) {
                tmp.append(Integer.toHexString(objectSid[i] & 0xFF));
            }
            // convert objectSid to String
            StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-")
                    .append(Long.parseLong(tmp.toString(), 16));
            // the sub authorities count
            int count = objectSid[1];
            // add authorities
            for (int i = 0; i < count; i++) {
                tmp.setLength(0);

                int offset = i * 4;
                tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF),
                        (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF),
                        (objectSid[8 + offset] & 0xFF)));
                sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16));
            }
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))",
                    new Object[] { sidBuilder.toString() }, searchControls);
            if (renum.hasMoreElements()) {
                result = renum.next();
                attr = result.getAttributes().get("distinguishedName");
                describeRoles(context, attr, groups, roles);
            }
        }
        return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles);
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex);
        throw new UsernameNotFoundException(ex.getMessage());
    }
}