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:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * Returns the list of role names for the given search base and other
 * parameters.//from w  w  w. j a v a 2 s . co  m
 * @param searchTime Maximum search time
 * @param filter Filter for searching role names
 * @param maxItemLimit Maximum number of roles required
 * @param searchFilter Group name search filter
 * @param roleNameProperty Attribute name of the group in LDAP user store.
 * @param searchBase Group search base.
 * @return The list of roles in the given search base.
 * @throws UserStoreException If an error occurs while retrieving the required information.
 */
private List<String> getLDAPRoleNames(int searchTime, String filter, int maxItemLimit, String searchFilter,
        String roleNameProperty, String searchBase) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    List<String> roles = new ArrayList<>();

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

    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    StringBuilder finalFilter = new StringBuilder();
    finalFilter.append("(&").append(searchFilter).append("(").append(roleNameProperty).append("=")
            .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");

    if (debug) {
        log.debug("Listing roles. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString());
    }

    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;

    try {
        dirContext = connectionSource.getContext();
        answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls);

        while (answer.hasMoreElements()) {
            SearchResult sr = answer.next();
            if (sr.getAttributes() != null) {
                Attribute attr = sr.getAttributes().get(roleNameProperty);
                if (attr != null) {
                    String name = (String) attr.get();
                    roles.add(name);
                }
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase
                + " ConstructedFilter: " + finalFilter.toString();
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase
                + " ConstructedFilter: " + finalFilter.toString();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }

    if (debug) {
        for (String role : roles) {
            log.debug("result: " + role);
        }
    }

    return roles;
}

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

/**
 * @param searchFilter Username search filter.
 * @param returnedAtts Required attribute list of the user
 * @param dirContext LDAP connection context.
 * @return Search results for the given user.
 * @throws UserStoreException If an error occurs while searching.
 *//*from  www  . ja va  2s. co  m*/
private NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts,
        DirContext dirContext) throws UserStoreException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE);
    if (returnedAtts[0].equals(CommonConstants.WILD_CARD_FILTER)) {
        returnedAtts = null;
    }
    searchCtls.setReturningAttributes(returnedAtts);

    if (log.isDebugEnabled()) {
        try {
            log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: "
                    + dirContext.getNameInNamespace());
        } catch (NamingException e) {
            log.debug("Error while getting DN of search base", e);
        }
        if (returnedAtts == null) {
            log.debug("No attributes requested");
        } else {
            for (String attribute : returnedAtts) {
                log.debug("Requesting attribute :" + attribute);
            }
        }
    }

    String[] searchBaseAraay = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);
    NamingEnumeration<SearchResult> answer = null;

    try {
        for (String searchBase : searchBaseAraay) {
            answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
            if (answer.hasMore()) {
                return answer;
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while search user for filter : " + searchFilter;
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while search user for filter : " + searchFilter;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return answer;
}

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

/**
 * @param userName Username of the user.
 * @param searchBase Searchbase which the user should be searched for.
 * @param searchFilter Search filter of the username.
 * @return DN of the user whose usename is given.
 * @throws UserStoreException If an error occurs while connecting to the LDAP userstore.
 *///w w w .  j  a v  a2 s  . c o m
private String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter)
        throws UserStoreException {
    boolean debug = log.isDebugEnabled();

    String userDN = null;

    DirContext dirContext = this.connectionSource.getContext();
    NamingEnumeration<SearchResult> answer = null;
    try {
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        if (log.isDebugEnabled()) {
            try {
                log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: "
                        + dirContext.getNameInNamespace());
            } catch (NamingException e) {
                log.debug("Error while getting DN of search base", e);
            }
        }
        SearchResult userObj;
        String[] searchBases = searchBase.split(CommonConstants.XML_PATTERN_SEPERATOR);
        for (String base : searchBases) {
            answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls);
            if (answer.hasMore()) {
                userObj = answer.next();
                if (userObj != null) {
                    //no need to decode since , if decoded the whole string, can't be encoded again
                    //eg CN=Hello\,Ok=test\,test, OU=Industry
                    userDN = userObj.getNameInNamespace();
                    break;
                }
            }
        }
        if (debug) {
            log.debug("Name in space for " + userName + " is " + userDN);
        }
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userDN;
}

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

/**
 * @param userName Username of the user.
 * @param searchBase Search base group search base.
 * @return List of roles of the given user.
 * @throws UserStoreException If an error occurs while retrieving data from LDAP userstore.
 *//* w  ww  .j a v a2  s .  c  o  m*/
private String[] getLDAPRoleListOfUser(String userName, String searchBase) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    List<String> list;

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

    // Load normal roles with the user
    String searchFilter;
    String roleNameProperty;
    searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
    roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);

    String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
    String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);
    String nameInSpace;
    if (userDNPattern != null && userDNPattern.trim().length() > 0
            && !userDNPattern.contains(CommonConstants.XML_PATTERN_SEPERATOR)) {

        nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName));
    } else {
        nameInSpace = this.getNameInSpaceForUserName(userName);
    }

    String membershipValue;
    if (nameInSpace != null) {
        try {
            LdapName ldn = new LdapName(nameInSpace);
            if (MEMBER_UID.equals(userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) {
                // membership value of posixGroup is not DN of the user
                List rdns = ldn.getRdns();
                membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
            } else {
                membershipValue = escapeLdapNameForFilter(ldn);
            }
        } catch (InvalidNameException e) {
            log.error("Error while creating LDAP name from: " + nameInSpace);
            throw new UserStoreException("Invalid naming exception for : " + nameInSpace, e);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (debug) {
        log.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty);

    String[] result = list.toArray(new String[list.size()]);

    for (String rolename : result) {
        log.debug("Found role: " + rolename);
    }
    return result;
}

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

/**
 * Reused method to search groups with various filters.
 *
 * @param searchFilter Group Search Filter
 * @param returningAttributes Attributes which the values needed.
 * @param searchScope Search Scope/*from  w  w  w. j  a v a2 s. com*/
 * @return Group Representation with given returning attributes
 */
protected NamingEnumeration<SearchResult> searchInGroupBase(String searchFilter, String[] returningAttributes,
        int searchScope, DirContext rootContext, String searchBase) throws UserStoreException {
    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setReturningAttributes(returningAttributes);
    userSearchControl.setSearchScope(searchScope);
    NamingEnumeration<SearchResult> groupSearchResults = null;
    try {
        groupSearchResults = rootContext.search(escapeDNForSearch(searchBase), searchFilter, userSearchControl);
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in group base.";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return groupSearchResults;
}

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

/**
 * {@inheritDoc}/*w w w.  j a  v  a  2s . c  om*/
 */
@Override
public boolean doCheckIsUserInRole(String userName, String roleName) throws UserStoreException {

    boolean debug = log.isDebugEnabled();
    String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // read the roles with this membership property
    String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
    String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new UserStoreException("Please set membership attribute");
    }

    String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);
    String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);
    String nameInSpace;
    if (org.apache.commons.lang.StringUtils.isNotEmpty(userDNPattern)
            && !userDNPattern.contains(CommonConstants.XML_PATTERN_SEPERATOR)) {
        nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName));
    } else {
        nameInSpace = this.getNameInSpaceForUserName(userName);
    }

    String membershipValue;
    if (nameInSpace != null) {
        try {
            LdapName ldn = new LdapName(nameInSpace);
            membershipValue = escapeLdapNameForFilter(ldn);
        } catch (InvalidNameException e) {
            log.error("Error while creating LDAP name from: " + nameInSpace);
            throw new UserStoreException(
                    "Invalid naming org.wso2.carbon.identity.agent.outbound.exception for : " + nameInSpace, e);
        }
    } else {
        return false;
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (debug) {
        log.debug("Do check whether the user : " + userName + " is in role: " + roleName);
        log.debug("Search filter : " + searchFilter);
        for (String retAttrib : returnedAtts) {
            log.debug("Requesting attribute: " + retAttrib);
        }
    }

    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    try {
        dirContext = connectionSource.getContext();

        if (debug) {
            log.debug("Do check whether the user: " + userName + " is in role: " + roleName);
            log.debug("Search filter: " + searchFilter);
            for (String retAttrib : returnedAtts) {
                log.debug("Requesting attribute: " + retAttrib);
            }
        }

        searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + ") ("
                + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))";

        // handle multiple search bases
        String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);

        for (String searchBase : searchBaseArray) {
            answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);

            if (answer.hasMoreElements()) {
                if (debug) {
                    log.debug("User: " + userName + " in role: " + roleName);
                }
                return true;
            }

            if (debug) {
                log.debug("User: " + userName + " NOT in role: " + roleName);
            }
        }
    } catch (NamingException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return false;
}

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

/**
 * @param userName Username of the user.
 * @param searchBase Search base group search base.
 * @return List of roles of the given user.
 * @throws UserStoreException If an error occurs while retrieving data from LDAP userstore.
 *//*ww  w  . j a v a2  s.c  o m*/
private String[] getLDAPRoleListOfUser(String userName, String searchBase) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    List<String> list;

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

    // Load normal roles with the user
    String searchFilter;
    String roleNameProperty;
    searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
    roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);

    String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
    String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);
    String nameInSpace;
    if (userDNPattern != null && userDNPattern.trim().length() > 0
            && !userDNPattern.contains(CommonConstants.XML_PATTERN_SEPERATOR)) {

        nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName));
    } else {
        nameInSpace = this.getNameInSpaceForUserName(userName);
    }

    String membershipValue;
    if (nameInSpace != null) {
        try {
            LdapName ldn = new LdapName(nameInSpace);
            if (MEMBER_UID.equals(userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) {
                // membership value of posixGroup is not DN of the user
                List rdns = ldn.getRdns();
                membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
            } else {
                membershipValue = escapeLdapNameForFilter(ldn);
            }
        } catch (InvalidNameException e) {
            log.error("Error while creating LDAP name from: " + nameInSpace);
            throw new UserStoreException(
                    "Invalid naming org.wso2.carbon.identity.agent.outbound.exception for : " + nameInSpace, e);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (debug) {
        log.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty);

    String[] result = list.toArray(new String[list.size()]);

    for (String rolename : result) {
        log.debug("Found role: " + rolename);
    }
    return result;
}

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

/**
 *
 *//* w w w.  ja  v a 2 s. c o m*/
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }

    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 =
    // realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    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;

        // The user tries to change his own password
        if (oldCredential != null && newCredential != null) {
            mods = new ModificationItem[1];
            /*
            * byte[] oldUnicodePassword = createUnicodePassword((String) oldCredential); byte[]
            * newUnicodePassword = createUnicodePassword((String) newCredential);
            */
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));
            /*
             * mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(
             * LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, newUnicodePassword));
             */
        }
        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.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   www . j a v  a2 s .c om

    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.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 * This method overwrites the method in LDAPUserStoreManager. This implements the functionality
 * of updating user's profile information in LDAP user store.
 *
 * @param userName//from ww  w. ja  v a  2 s. c om
 * @param claims
 * @param profileName
 * @throws org.wso2.carbon.user.core.UserStoreException
 */
@Override
public void doSetUserClaimValues(String userName, Map<String, String> claims, String profileName)
        throws UserStoreException {
    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];
    }
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(null);

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    boolean cnModified = false;
    String cnValue = null;

    try {

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        returnedUserEntry = returnedResultList.next().getName();

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    if (profileName == null) {
        profileName = UserCoreConstants.DEFAULT_PROFILE;
    }

    if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) {
        claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);

        String domainName = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > -1
                ? userName.split(UserCoreConstants.DOMAIN_SEPARATOR)[0]
                : realmConfig.getUserStoreProperty(UserStoreConfigConstants.DOMAIN_NAME);
        for (Map.Entry<String, String> claimEntry : claims.entrySet()) {
            String claimURI = claimEntry.getKey();
            // if there is no attribute for profile configuration in LDAP,
            // skip updating it.
            if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) {
                continue;
            }
            // get the claimMapping related to this claimURI
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            //remove user DN from cache if changing username attribute
            if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) {
                userCache.remove(userName);
            }
            // if mapped attribute is CN, then skip treating as a modified
            // attribute -
            // it should be an object rename
            if ("CN".toLowerCase().equals(attributeName.toLowerCase())) {
                cnModified = true;
                cnValue = claimEntry.getValue();
                continue;
            }
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            /* if updated attribute value is null, remove its values. */
            if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) {
                currentUpdatedAttribute.clear();
            } else {
                if (claimEntry.getValue() != null) {
                    String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                    if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                        userAttributeSeparator = claimSeparator;
                    }
                    if (claimEntry.getValue().contains(userAttributeSeparator)) {
                        StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator);
                        while (st.hasMoreElements()) {
                            String newVal = st.nextElement().toString();
                            if (newVal != null && newVal.trim().length() > 0) {
                                currentUpdatedAttribute.add(newVal.trim());
                            }
                        }
                    } else {
                        currentUpdatedAttribute.add(claimEntry.getValue());
                    }
                } else {
                    currentUpdatedAttribute.add(claimEntry.getValue());
                }
            }
            updatedAttributes.put(currentUpdatedAttribute);
        }
        // update the attributes in the relevant entry of the directory
        // store

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes);

        if (cnModified && cnValue != null) {
            subDirContext.rename(returnedUserEntry, "CN=" + escapeSpecialCharactersForDN(cnValue));
        }

    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String errorMessage = "Error in obtaining claim mapping for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (NamingException e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}