Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration next.

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 *
 * @param attributes// ww w  .  j av a 2  s.  co m
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws javax.naming.NamingException
 *             the naming exception
 */
private Attribute getRangeRestrictedAttribute(Attributes attributes, String attributeName)
        throws NamingException {
    Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null) {
        return unrestricted;
    }
    NamingEnumeration<? extends Attribute> i = attributes.getAll();
    String searchString = attributeName.toLowerCase() + ';';
    while (i.hasMore()) {
        Attribute attribute = i.next();
        if (attribute.getID().toLowerCase().startsWith(searchString)) {
            return attribute;
        }
    }
    return null;
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

/** 
 * Return a list of all of the subcontexts of the current context, which is relative to parentContext. 
 * @return an array of Strings containing a list of the subcontexts for a current context.
 *///from  w ww .jav a  2  s. c o  m
public String[] getSubContextList(DirContext parentContext, String relativeContext,
        ParameterResolutionContext prc) {
    String[] retValue = null;

    try {
        // Create a vector object and add the names of all of the subcontexts
        //  to it
        Vector n = new Vector();
        NamingEnumeration list = parentContext.list(relativeContext);
        if (log.isDebugEnabled())
            log.debug("getSubCOntextList(context) : context = " + relativeContext);
        for (int x = 0; list.hasMore(); x++) {
            NameClassPair nc = (NameClassPair) list.next();
            n.addElement(nc);
        }

        // Create a string array of the same size as the vector object
        String contextList[] = new String[n.size()];
        for (int x = 0; x < n.size(); x++) {
            // Add each name to the array
            contextList[x] = ((NameClassPair) (n.elementAt(x))).getName();
        }
        retValue = contextList;

    } catch (NamingException e) {
        storeLdapException(e, prc);
        log.error("Exception in operation [" + getOperation() + "] ", e);
    }

    return retValue;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Obtain the properties for the user associated with the given uid using the
 * configured user properties query string.
 *
 * @param uid the user id of the user for whom its user properties are required.
 * @return the hash map containing user properties as name/value pairs.
 * @throws NamingException LDAP error obtaining user properties.
 * @throws IOException /* ww w . j  a  va 2s .c om*/
 */
protected HashMap selectUserProperties(String uid) throws NamingException, IOException {
    HashMap userPropertiesResultSet = new HashMap();

    InitialLdapContext ctx = null;
    try {
        ctx = createLdapInitialContext(getUseBindCredentials());
    } catch (NamingException e) {
        if (getUseBindCredentials()) {
            // in case we are using virtual identity store
            return userPropertiesResultSet;
        } else {
            throw e;
        }
    }

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    BasicAttributes matchAttrs = new BasicAttributes(true);

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    matchAttrs.put(principalUidAttrName, uid);

    String userPropertiesQueryString = getUserPropertiesQueryString();
    HashMap userPropertiesQueryMap = parseQueryString(userPropertiesQueryString);

    Iterator i = userPropertiesQueryMap.keySet().iterator();
    List propertiesAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        propertiesAttrList.add(o);
    }

    String[] propertiesAttr = (String[]) propertiesAttrList.toArray(new String[propertiesAttrList.size()]);

    try {

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            for (int j = 0; j < propertiesAttr.length; j++) {

                Attribute attribute = attrs.get(propertiesAttr[j]);

                if (attribute == null) {
                    logger.warn("Invalid user property attribute '" + propertiesAttr[j] + "'");
                    continue;
                }

                Object propertyObject = attrs.get(propertiesAttr[j]).get();

                if (propertyObject == null) {
                    logger.warn("Found a 'null' value for user property '" + propertiesAttr[j] + "'");
                    continue;
                }

                String propertyValue = propertyObject.toString();
                String propertyName = (String) userPropertiesQueryMap.get(propertiesAttr[j]);

                userPropertiesResultSet.put(propertyName, propertyValue);

                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user property '" + propertyName + "' with value '" + propertyValue + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return userPropertiesResultSet;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback/* w ww  .  j a va  2 s  . co  m*/
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws AlfrescoRuntimeException
 */
protected void processQuery(final SearchCallback callback, final String searchBase, final String query,
        final String[] returningAttributes) {
    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "Processing query {}\nSearch base: {}\n\rReturn result limit: {}\n\tDereflink: {}\n\rReturn named object: {}\n\tTime limit for search: {}\n\tAttributes to return: {} items\n\tAttributes: {}",
                query, searchBase, searchControls.getCountLimit(), searchControls.getDerefLinkFlag(),
                searchControls.getReturningObjFlag(), searchControls.getTimeLimit(),
                String.valueOf(returningAttributes.length), Arrays.toString(returningAttributes));
    }

    InitialDirContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize);
        do {
            searchResults = ctx.search(searchBase, query, searchControls);

            while (searchResults.hasMore()) {
                result = searchResults.next();
                callback.process(result);

                this.commonCloseSearchResult(result);
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (final NamingException e) {
        final Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (final ParseException e) {
        final Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        this.commonAfterQueryCleanup(searchResults, result, ctx);
    }
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * @see org.opentravel.schemacompiler.security.AuthenticationProvider#searchCandidateUsers(java.lang.String, int)
 *///from  www.j  a va 2  s. co  m
@Override
public List<UserPrincipal> searchCandidateUsers(String searchCriteria, int maxResults)
        throws RepositoryException {
    List<UserPrincipal> userList = new ArrayList<>();

    if ((searchCriteria != null) && (searchCriteria.length() > 0)) {
        List<String> searchAttributes = Arrays.asList(userLastNameAttribute, userFirstNameAttribute,
                userFullNameAttribute);
        StringBuilder searchFilter = new StringBuilder("(&(objectCategory=person)(").append(userIdAttribute)
                .append("=*)(|");
        SearchControls constraints = new SearchControls();
        DirContext context = null;

        for (String searchAttr : searchAttributes) {
            if ((searchAttr != null) && (searchAttr.length() > 0)) {
                searchFilter.append("(").append(searchAttr).append("=*").append(searchCriteria).append("*)");
            }
        }
        searchFilter.append("))");
        constraints.setSearchScope(
                searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
        constraints.setTimeLimit(userSearchTimeout);
        constraints.setCountLimit(maxResults);
        constraints.setReturningAttributes(new String[] { userIdAttribute, userLastNameAttribute,
                userFirstNameAttribute, userEmailAttribute });

        try {
            context = openConnection(connectionPrincipal, connectionPassword);
            NamingEnumeration<SearchResult> searchResults = context.search(userSearchBase,
                    searchFilter.toString(), constraints);

            while (searchResults.hasMore()) {
                SearchResult resultItem = searchResults.next();
                Attributes itemAttrs = resultItem.getAttributes();
                String userId = getAttributeValue(itemAttrs, userIdAttribute);
                String lastName = getAttributeValue(itemAttrs, userLastNameAttribute);
                String firstName = getAttributeValue(itemAttrs, userFirstNameAttribute);
                String email = getAttributeValue(itemAttrs, userEmailAttribute);
                UserPrincipal user = new UserPrincipal();

                user.setUserId(userId);
                user.setLastName(lastName);
                user.setFirstName(firstName);
                user.setEmailAddress(email);
                userList.add(user);
            }

        } catch (PartialResultException | SizeLimitExceededException e) {
            // Ignore - this means we have reached the end of the list and that any remaining
            // items are aliased referrals which cannot be resolved.

        } catch (NamingException e) {
            throw new RepositoryException("Error encountered during directory search.", e);
        }
    }
    return userList;
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Searches the remote directory for the user's entry and returns its distinguished name
 * string./*from  w  w  w .j  a v  a 2s .  co m*/
 * 
 * @param userId
 *            the ID of the user whose DN is to be retrieved
 * @param context
 *            the directory context from which to retrieve the user's DN
 * @return String
 * @throws NamingException
 */
protected String findUserDn(String userId, DirContext context) throws NamingException {
    String userDn = null;

    for (MessageFormat userSearchPattern : userSearchPatterns) {
        try {
            String searchFilter = userSearchPattern.format(new String[] { userId });
            SearchControls constraints = new SearchControls();

            constraints.setSearchScope(
                    searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
            constraints.setTimeLimit(userSearchTimeout);

            NamingEnumeration<SearchResult> results = context.search(userSearchBase, searchFilter, constraints);
            SearchResult result = null;

            try {
                if ((results != null) && results.hasMore()) {
                    result = results.next();

                    // Make sure only one entry exists for the requested user
                    if (results.hasMore()) {
                        log.warn("Multiple entries found for user: " + userId);
                        result = null;
                    }
                }
            } catch (PartialResultException e) {
                // Ignore partial result errors - most likely due to ActiveDirectory referrals
            }

            if (result != null) {
                userDn = result.getNameInNamespace();
                break;
            }

        } catch (NameNotFoundException e) {
            // Ignore and keep searching
        }
    }
    return userDn;
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

protected Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx,
        final LdapContextFactory ldapContextFactory, Session session) throws NamingException {
    final Set<String> roleNames = new HashSet<>();
    final Set<String> groupNames = new HashSet<>();
    final String userName;
    if (getUserLowerCase()) {
        log.debug("userLowerCase true");
        userName = userNameIn.toLowerCase();
    } else {/*  w  w  w.  j a  v a  2  s  .com*/
        userName = userNameIn;
    }

    String userDn = getUserDnForSearch(userName);

    // Activate paged results
    int pageSize = getPagingSize();
    if (log.isDebugEnabled()) {
        log.debug("Ldap PagingSize: " + pageSize);
    }
    int numResults = 0;
    byte[] cookie = null;
    try {
        ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");

        ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });

        do {
            // ldapsearch -h localhost -p 33389 -D
            // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password
            // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
            NamingEnumeration<SearchResult> searchResultEnum = null;
            SearchControls searchControls = getGroupSearchControls();
            try {
                if (groupSearchEnableMatchingRuleInChain) {
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), String
                            .format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn),
                            searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();

                        Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
                        String groupName = attribute.get().toString();

                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                    }
                } else {
                    // Default group search filter
                    String searchFilter = String.format("(objectclass=%1$s)", groupObjectClass);

                    // If group search filter is defined in Shiro config, then use it
                    if (groupSearchFilter != null) {
                        searchFilter = expandTemplate(groupSearchFilter, userName);
                        //searchFilter = String.format("%1$s", groupSearchFilter);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Group SearchBase|SearchFilter|GroupSearchScope: " + getGroupSearchBase()
                                + "|" + searchFilter + "|" + groupSearchScope);
                    }
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), searchFilter, searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();
                        addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
                    }
                }
            } catch (PartialResultException e) {
                log.debug("Ignoring PartitalResultException");
            } finally {
                if (searchResultEnum != null) {
                    searchResultEnum.close();
                }
            }
            // Re-activate paged results
            ldapCtx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
        } while (cookie != null);
    } catch (SizeLimitExceededException e) {
        log.info("Only retrieved first " + numResults + " groups due to SizeLimitExceededException.");
    } catch (IOException e) {
        log.error("Unabled to setup paged results");
    }
    // save role names and group names in session so that they can be
    // easily looked up outside of this object
    session.setAttribute(SUBJECT_USER_ROLES, roleNames);
    session.setAttribute(SUBJECT_USER_GROUPS, groupNames);
    if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
        ((MutablePrincipalCollection) principals).addAll(groupNames, getName());
    }
    if (log.isDebugEnabled()) {
        log.debug("User RoleNames: " + userName + "::" + roleNames);
    }
    return roleNames;
}

From source file:org.lsc.jndi.JndiServices.java

public Map<String, LscDatasets> doGetAttrsList(final String base, final String filter, final int scope,
        final List<String> attrsNames) throws NamingException {

    // sanity checks
    String searchBase = base == null ? "" : rewriteBase(base);
    String searchFilter = filter == null ? DEFAULT_FILTER : filter;

    Map<String, LscDatasets> res = new LinkedHashMap<String, LscDatasets>();

    if (attrsNames == null || attrsNames.size() == 0) {
        LOGGER.error("No attribute names to read! Check configuration.");
        return res;
    }//from   www . j av a2s. c  o  m

    String[] attributes = new String[attrsNames.size()];
    attributes = attrsNames.toArray(attributes);

    SearchControls constraints = new SearchControls();
    constraints.setDerefLinkFlag(false);
    constraints.setReturningAttributes(attributes);
    constraints.setSearchScope(scope);
    constraints.setReturningObjFlag(true);

    try {
        boolean requestPagedResults = false;

        List<Control> extControls = new ArrayList<Control>();

        if (pageSize > 0) {
            requestPagedResults = true;
            LOGGER.debug("Using pagedResults control for {} entries at a time", pageSize);
        }

        if (requestPagedResults) {
            extControls.add(new PagedResultsControl(pageSize, Control.CRITICAL));
        }

        if (sortedBy != null) {
            extControls.add(new SortControl(sortedBy, Control.CRITICAL));
        }

        if (extControls.size() > 0) {
            ctx.setRequestControls(extControls.toArray(new Control[extControls.size()]));
        }

        byte[] pagedResultsResponse = null;
        do {
            NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, constraints);

            if (results != null) {
                Map<String, Object> attrsValues = null;
                while (results.hasMoreElements()) {
                    attrsValues = new HashMap<String, Object>();

                    SearchResult ldapResult = (SearchResult) results.next();

                    // get the value for each attribute requested
                    for (String attributeName : attrsNames) {
                        Attribute attr = ldapResult.getAttributes().get(attributeName);
                        if (attr != null && attr.get() != null) {
                            attrsValues.put(attributeName, attr.get());
                        }
                    }

                    res.put(ldapResult.getNameInNamespace(), new LscDatasets(attrsValues));
                }
            }

            Control[] respCtls = ctx.getResponseControls();
            if (respCtls != null) {
                for (Control respCtl : respCtls) {
                    if (requestPagedResults && respCtl instanceof PagedResultsResponseControl) {
                        pagedResultsResponse = ((PagedResultsResponseControl) respCtl).getCookie();
                    }
                }
            }

            if (requestPagedResults && pagedResultsResponse != null) {
                ctx.setRequestControls(new Control[] {
                        new PagedResultsControl(pageSize, pagedResultsResponse, Control.CRITICAL) });
            }

        } while (pagedResultsResponse != null);

        // clear requestControls for future use of the JNDI context
        if (requestPagedResults) {
            ctx.setRequestControls(null);
        }
    } catch (CommunicationException e) {
        // Avoid handling the communication exception as a generic one
        throw e;
    } catch (ServiceUnavailableException e) {
        // Avoid handling the service unavailable exception as a generic one
        throw e;
    } catch (NamingException e) {
        // clear requestControls for future use of the JNDI context
        ctx.setRequestControls(null);
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);

    } catch (IOException e) {
        // clear requestControls for future use of the JNDI context
        ctx.setRequestControls(null);
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);
    }
    return res;
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {//from  w  w  w.  j ava2  s .com
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", e);
        }
    }

}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetch the Ldap user attributes to be used as credentials.
 *
 * @param uid the user id (or lookup value) for whom credentials are required
 * @return the hash map containing user credentials as name/value pairs
 * @throws NamingException LDAP error obtaining user credentials.
 * @throws IOException //from   w ww .  jav  a 2  s.co  m
 */
protected HashMap selectCredentials(String uid, CredentialProvider cp) throws NamingException, IOException {
    HashMap credentialResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String schemeName = null;
    if (cp instanceof AuthenticationScheme) {
        schemeName = ((AuthenticationScheme) cp).getName();
    }

    String principalLookupAttrName = this.getPrincipalLookupAttributeID();
    if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("")
            || !"strong-authentication".equals(schemeName)) {
        principalLookupAttrName = this.getPrincipalUidAttributeID();
    }

    String usersCtxDN = this.getUsersCtxDN();

    // BasicAttributes matchAttrs = new BasicAttributes(true);
    // matchAttrs.put(principalUidAttrName, uid);

    String credentialQueryString = getCredentialQueryString();
    HashMap credentialQueryMap = parseQueryString(credentialQueryString);

    Iterator i = credentialQueryMap.keySet().iterator();
    List credentialAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        credentialAttrList.add(o);
    }

    String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]);

    try {

        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr);

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalLookupAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            String userDN = sr.getNameInNamespace();
            if (logger.isDebugEnabled())
                logger.debug("Processing results for entry '" + userDN + "'");

            for (int j = 0; j < credentialAttr.length; j++) {
                if (attrs.get(credentialAttr[j]) == null)
                    continue;

                //Object credentialObject = attrs.get(credentialAttr[j]).get();
                String credentialName = (String) credentialQueryMap.get(credentialAttr[j]);
                String credentialValue = null;

                Attribute attr = attrs.get(credentialAttr[j]);
                NamingEnumeration attrEnum = attr.getAll();
                while (attrEnum.hasMore()) {
                    Object credentialObject = attrEnum.next();
                    if (credentialObject == null)
                        continue;

                    if (logger.isDebugEnabled())
                        logger.debug("Found user credential '" + credentialName + "' of type '"
                                + credentialObject.getClass().getName() + ""
                                + (credentialObject.getClass().isArray()
                                        ? "[" + Array.getLength(credentialObject) + "]"
                                        : "")
                                + "'");

                    // if the attribute value is an array, cast it to byte[] and then convert to
                    // String using proper encoding
                    if (credentialObject.getClass().isArray()) {

                        try {
                            // Try to create a UTF-8 String, we use java.nio to handle errors in a better way.
                            // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is.
                            byte[] credentialData = (byte[]) credentialObject;
                            ByteBuffer in = ByteBuffer.allocate(credentialData.length);
                            in.put(credentialData);
                            in.flip();

                            Charset charset = Charset.forName("UTF-8");
                            CharsetDecoder decoder = charset.newDecoder();
                            CharBuffer charBuffer = decoder.decode(in);

                            credentialValue = charBuffer.toString();

                        } catch (CharacterCodingException e) {
                            if (logger.isDebugEnabled())
                                logger.debug("Can't convert credential value to String using UTF-8");
                        }

                    } else if (credentialObject instanceof String) {
                        // The credential value must be a String ...
                        credentialValue = (String) credentialObject;

                    }

                    // Check what do we have ...
                    List credentials = (List) credentialResultSet.get(credentialName);
                    if (credentials == null) {
                        credentials = new ArrayList();
                    }
                    if (credentialValue != null) {
                        // Remove any schema information from the credential value, like the {md5} prefix for passwords.
                        credentialValue = getSchemeFreeValue(credentialValue);
                        credentials.add(credentialValue);
                    } else {
                        // We have a binary credential, leave it as it is ... probably binary value.
                        credentials.add(credentialObject);
                    }
                    credentialResultSet.put(credentialName, credentials);

                    if (logger.isDebugEnabled())
                        logger.debug("Found user credential '" + credentialName + "' with value '"
                                + (credentialValue != null ? credentialValue : credentialObject) + "'");
                }
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return credentialResultSet;
}