Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

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

Introduction

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

Prototype

int SUBTREE_SCOPE

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

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from Zeppelin LdapRealm. */
private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    LOGGER.debug("SearchText: " + searchText);
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {//from  w w w . ja  v  a  2s. com
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        constraints.setCountLimit(numUsersToFetch);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=*" + searchText + "*))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOGGER.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOGGER.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                LOGGER.debug("CurrentUser: " + currentUser);
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

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/*from  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:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * /*from   ww w.  j a  v  a 2s .c  om*/
 * @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.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public ServerPrinciple[] listServicePrinciples(String filter) throws DirectoryServerManagerException {

    ServerPrinciple[] serverNames = null;

    int maxItemLimit = Integer.parseInt(
            this.realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);

    if (filter.contains("?") || filter.contains("**")) {
        log.error("Invalid search character " + filter);
        throw new DirectoryServerManagerException(
                "Invalid character sequence entered for service principle search. Please enter valid sequence.");
    }/*  w  w w.java  2s  . co  m*/

    StringBuilder searchFilter;
    searchFilter = new StringBuilder(
            this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    StringBuilder buff = new StringBuilder();
    buff.append("(&").append(searchFilter).append("(")
            .append(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE).append("=").append(filter)
            .append(")").append(getServerPrincipleIncludeString()).append(")");

    String[] returnedAtts = { LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE,
            LDAPServerManagerConstants.LDAP_COMMON_NAME };
    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    try {
        dirContext = connectionSource.getContext();
        NamingEnumeration<SearchResult> answer = dirContext.search(searchBase, buff.toString(), searchCtls);
        List<ServerPrinciple> list = new ArrayList<ServerPrinciple>();
        int i = 0;
        while (answer.hasMoreElements() && i < maxItemLimit) {
            SearchResult sr = answer.next();
            if (sr.getAttributes() != null) {
                Attribute serverNameAttribute = sr.getAttributes()
                        .get(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE);
                Attribute serverDescription = sr.getAttributes()
                        .get(LDAPServerManagerConstants.LDAP_COMMON_NAME);
                if (serverNameAttribute != null) {

                    ServerPrinciple principle;
                    String serviceName;
                    String serverPrincipleFullName = (String) serverNameAttribute.get();

                    if (serverPrincipleFullName.toLowerCase(Locale.ENGLISH)
                            .contains(LDAPServerManagerConstants.KERBEROS_TGT)) {
                        continue;
                    }

                    if (serverPrincipleFullName.contains("@")) {
                        serviceName = serverPrincipleFullName.split("@")[0];
                    } else {
                        serviceName = serverPrincipleFullName;
                    }

                    if (serverDescription != null) {
                        principle = new ServerPrinciple(serviceName, (String) serverDescription.get());
                    } else {

                        principle = new ServerPrinciple(serviceName);
                    }

                    list.add(principle);
                    i++;
                }
            }
        }

        serverNames = list.toArray(new ServerPrinciple[list.size()]);
        Arrays.sort(serverNames);

    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new DirectoryServerManagerException("Unable to list service principles.", e);
    } catch (UserStoreException e) {
        log.error("Unable to retrieve LDAP connection context.", e);
        throw new DirectoryServerManagerException("Unable to list service principles.", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
    return serverNames;

}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.membership.get", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> listMermbershipGroups(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    UserDn userDn = nameHelper.newUserDnFromId(userId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

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

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(
            nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())),
            "(uniqueMember=" + userDn.toString() + ")", controls);

    List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>();
    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) {
            HashMap<String, Object> group = new HashMap<String, Object>();
            group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId());
            groups.add(group);//  w  w w .  j av a2  s  .c  o m
        }
    }

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("groups", groups);

    return response;
}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

@Override
public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }//from w w w .jav  a  2  s .co m

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";
    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);

    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        if (newCredential != null) {
            mods = new ModificationItem[1];
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));

            subDirContext = (DirContext) dirContext.lookup(searchBase);
            subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);
        }

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

/**
 * @see {@link AccountDao#findByEmail(String)}
 *///from w ww  .ja  v a 2  s. c o m
@Override
public Account findByEmail(final String email) throws DataServiceException, NameNotFoundException {

    SearchControls sc = new SearchControls();
    sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectClass", "inetOrgPerson"));
    filter.and(new EqualsFilter("objectClass", "organizationalPerson"));
    filter.and(new EqualsFilter("objectClass", "person"));
    filter.and(new EqualsFilter("mail", email));

    List<Account> accountList = ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), sc,
            attributMapper);
    if (accountList.isEmpty()) {
        throw new NameNotFoundException("There is no user with this email: " + email);
    }
    Account account = accountList.get(0);

    return account;
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public <T> List<T> search(Class<T> clazz, String filter) {
    if (null == filter) {
        return null;
    }//from  ww w.  j  av a  2s .co m

    LogUtils.debug(LOG, "search " + clazz.getName() + " with filter=" + filter);

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(EntityMetaData.getDefinedAttrNames(clazz));

    List<T> retVal = new ArrayList<T>();
    try {
        NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                T entity = null;
                if (sessionCache.containsKey(result.getNameInNamespace())) {
                    // guarantee the reference integrity for one search result
                    entity = (T) sessionCache.get(result.getNameInNamespace());
                } else {
                    entity = fromAttributesToEntity(clazz, result.getAttributes());
                    sessionCache.put(result.getNameInNamespace(), entity);
                }
                retVal.add(entity);
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the entity", e);
            }
        }
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
    return retVal;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username)
        throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();

    if (dirContext == null || _roleBaseDn == null
            || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null)
            || _roleObjectClass == null) {
        LOG.warn(//  www. j  a v a2  s . c  o m
                "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
        addSupplementalRoles(roleList);
        return roleList;
    }

    String[] attrIDs = { _roleNameAttribute };
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(attrIDs);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;
    final NamingEnumeration results;

    if (null != _roleUsernameMemberAttribute) {
        Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    } else {
        Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    }

    while (results.hasMoreElements()) {
        SearchResult result = (SearchResult) results.nextElement();

        Attributes attributes = result.getAttributes();

        if (attributes == null) {
            continue;
        }

        Attribute roleAttribute = attributes.get(_roleNameAttribute);

        if (roleAttribute == null) {
            continue;
        }

        NamingEnumeration roles = roleAttribute.getAll();
        while (roles.hasMore()) {
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                String role = (String) roles.next();
                roleList.add(role.replace(_rolePrefix, ""));
            } else {
                roleList.add((String) roles.next());
            }
        }
    }

    addSupplementalRoles(roleList);

    if (_nestedGroups) {
        roleList = getNestedRoles(dirContext, roleList);
    }

    if (roleList.size() < 1) {
        LOG.warn("JettyCachingLdapLoginModule: User '" + username
                + "' has no role membership; role query configuration may be incorrect");
    } else {
        debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
    }

    return roleList;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * {@inheritDoc}/*from w w  w. j  a  v  a2 s  . c  o  m*/
 */
public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames)
        throws UserStoreException {

    String userAttributeSeparator = ",";
    String userDN = null;

    // read list of patterns from user-mgt.xml
    String patterns = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);

    if (patterns != null && !patterns.isEmpty()) {

        if (log.isDebugEnabled()) {
            log.debug("Using User DN Patterns " + patterns);
        }

        if (patterns.contains(CommonConstants.XML_PATTERN_SEPERATOR)) {
            userDN = getNameInSpaceForUserName(userName);
        } else {
            userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName));
        }
    }

    Map<String, String> values = new HashMap<>();
    DirContext dirContext = this.connectionSource.getContext();
    String userSearchFilter = userStoreProperties.get(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    NamingEnumeration<?> answer = null;
    NamingEnumeration<?> attrs = null;
    NamingEnumeration<?> allAttrs = null;
    try {
        if (userDN != null) {
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            if (propertyNames[0].equals(CommonConstants.WILD_CARD_FILTER)) {
                propertyNames = null;
            }
            searchCtls.setReturningAttributes(propertyNames);

            try {
                answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls);
            } catch (PartialResultException e) {
                // can be due to referrals in AD. so just ignore error
                String errorMessage = "Error occurred while searching directory context for user : " + userDN
                        + " searchFilter : " + searchFilter;
                if (isIgnorePartialResultException()) {
                    if (log.isDebugEnabled()) {
                        log.debug(errorMessage, e);
                    }
                } else {
                    throw new UserStoreException(errorMessage, e);
                }
            } catch (NamingException e) {
                String errorMessage = "Error occurred while searching directory context for user : " + userDN
                        + " searchFilter : " + searchFilter;
                if (log.isDebugEnabled()) {
                    log.debug(errorMessage, e);
                }
                throw new UserStoreException(errorMessage, e);
            }
        } else {
            answer = this.searchForUser(searchFilter, propertyNames, dirContext);
        }
        assert answer != null;
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attributes = sr.getAttributes();
            if (attributes != null) {
                for (allAttrs = attributes.getAll(); allAttrs.hasMore();) {
                    Attribute attribute = (Attribute) allAttrs.next();
                    if (attribute != null) {
                        StringBuilder attrBuffer = new StringBuilder();
                        for (attrs = attribute.getAll(); attrs.hasMore();) {
                            Object attObject = attrs.next();
                            String attr = null;
                            if (attObject instanceof String) {
                                attr = (String) attObject;
                            } else if (attObject instanceof byte[]) {
                                //if the attribute type is binary base64 encoded string will be returned
                                attr = new String(Base64.encodeBase64((byte[]) attObject), "UTF-8");
                            }

                            if (attr != null && attr.trim().length() > 0) {
                                String attrSeparator = userStoreProperties.get(MULTI_ATTRIBUTE_SEPARATOR);
                                if (attrSeparator != null && !attrSeparator.trim().isEmpty()) {
                                    userAttributeSeparator = attrSeparator;
                                }
                                attrBuffer.append(attr).append(userAttributeSeparator);
                            }
                            String value = attrBuffer.toString();

                            /*
                             * Length needs to be more than userAttributeSeparator.length() for a valid
                             * attribute, since we
                             * attach userAttributeSeparator
                             */
                            if (value.trim().length() > userAttributeSeparator.length()) {
                                value = value.substring(0, value.length() - userAttributeSeparator.length());
                                values.put(attribute.getID(), value);
                            }

                        }

                    }
                }
            }
        }

    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user property values for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (UnsupportedEncodingException e) {
        String errorMessage = "Error occurred while Base64 encoding property values for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        // close the naming enumeration and free up resource
        JNDIUtil.closeNamingEnumeration(attrs);
        JNDIUtil.closeNamingEnumeration(answer);
        // close directory context
        JNDIUtil.closeContext(dirContext);
    }
    return values;
}