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.user.core.ldap.ReadWriteLDAPUserStoreManager.java

@SuppressWarnings("rawtypes")
@Override/*from  w  w w . j  a v  a 2  s. co  m*/
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // first search the existing user entry.
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "userPassword" });

    NamingEnumeration<SearchResult> namingEnumeration = null;
    NamingEnumeration passwords = null;

    try {
        namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls);
        // here we assume only one user
        // TODO: what to do if there are more than one user
        SearchResult searchResult = null;
        String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD);
        while (namingEnumeration.hasMore()) {
            searchResult = namingEnumeration.next();

            String dnName = searchResult.getName();
            subDirContext = (DirContext) dirContext.lookup(searchBase);

            Attribute passwordAttribute = new BasicAttribute("userPassword");
            passwordAttribute.add(
                    UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled));
            BasicAttributes basicAttributes = new BasicAttributes(true);
            basicAttributes.put(passwordAttribute);
            subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }
        // we check whether both carbon admin entry and ldap connection
        // entry are the same
        if (searchResult.getNameInNamespace()
                .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) {
            this.connectionSource.updateCredential((String) newCredential);
        }

    } catch (NamingException e) {
        String errorMessage = "Can not access the directory service for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(passwords);
        JNDIUtil.closeNamingEnumeration(namingEnumeration);

        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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

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

    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // first search the existing user entry.
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "userPassword" });

    NamingEnumeration<SearchResult> namingEnumeration = null;
    NamingEnumeration passwords = null;

    try {/*from w ww.  jav a2s.c o  m*/
        namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls);
        // here we assume only one user
        // TODO: what to do if there are more than one user
        // there can be only only on user

        SearchResult searchResult = null;
        while (namingEnumeration.hasMore()) {
            searchResult = namingEnumeration.next();
            String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD);
            if (!UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT
                    .equalsIgnoreCase(passwordHashMethod)) {
                Attributes attributes = searchResult.getAttributes();
                Attribute userPassword = attributes.get("userPassword");
                // When admin changes other user passwords he do not have to
                // provide the old password. Here it is only possible to have one password, if there
                // are more every one should match with the given old password
                passwords = userPassword.getAll();
                if (passwords.hasMore()) {
                    byte[] byteArray = (byte[]) passwords.next();
                    String password = new String(byteArray);

                    if (password.startsWith("{")) {
                        passwordHashMethod = password.substring(password.indexOf('{') + 1,
                                password.indexOf('}'));
                    }
                }
            }

            String dnName = searchResult.getName();
            subDirContext = (DirContext) dirContext.lookup(searchBase);

            Attribute passwordAttribute = new BasicAttribute("userPassword");
            passwordAttribute.add(
                    UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled));
            BasicAttributes basicAttributes = new BasicAttributes(true);
            basicAttributes.put(passwordAttribute);
            subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }
        // we check whether both carbon admin entry and ldap connection
        // entry are the same
        if (searchResult.getNameInNamespace()
                .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) {
            this.connectionSource.updateCredential((String) newCredential);
        }

    } catch (NamingException e) {
        String errorMessage = "Can not access the directory service for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(passwords);
        JNDIUtil.closeNamingEnumeration(namingEnumeration);

        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.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  o  m*/
 * @param claims
 * @param profileName
 * @throws 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;

    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
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (log.isDebugEnabled()) {
            log.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);

        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 uid attribute value contains domain name, remove domain
            // name
            if (attributeName.equals("uid")) {
                // if user name contains domain name, remove domain name
                String uidName = claimEntry.getValue();
                String[] uidNames = uidName.split(CarbonConstants.DOMAIN_SEPARATOR);
                if (uidNames.length > 1) {
                    uidName = uidNames[1];
                    claimEntry.setValue(uidName);
                }
                //                    claimEntry.setValue(escapeISSpecialCharacters(uidName));
            }
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            /* if updated attribute value is null, remove its values. */
            if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) {
                currentUpdatedAttribute.clear();
            } else {
                String userAttributeSeparator = ",";
                if (claimEntry.getValue() != null && !attributeName.equals("uid")
                        && !attributeName.equals("sn")) {
                    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);

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

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

@Override
public void doSetUserClaimValue(String userName, String claimURI, String value, 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];// w w  w .  j a  va2s .c om
    }
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

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

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = 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
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

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

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI
        String attributeName = null;
        attributeName = getClaimAtrribute(claimURI, userName, null);

        Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
        /* if updated attribute value is null, remove its values. */
        if (EMPTY_ATTRIBUTE_STRING.equals(value)) {
            currentUpdatedAttribute.clear();
        } else {
            if (attributeName.equals("uid") || attributeName.equals("sn")) {
                currentUpdatedAttribute.add(value);
            } else {
                String userAttributeSeparator = ",";
                String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                    userAttributeSeparator = claimSeparator;
                }

                if (value.contains(userAttributeSeparator)) {
                    StringTokenizer st = new StringTokenizer(value, userAttributeSeparator);
                    while (st.hasMoreElements()) {
                        String newVal = st.nextElement().toString();
                        if (newVal != null && newVal.trim().length() > 0) {
                            currentUpdatedAttribute.add(newVal.trim());
                        }
                    }
                } else {
                    currentUpdatedAttribute.add(value);
                }

            }
        }
        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);

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

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

@Override
public void doDeleteUserClaimValue(String userName, String claimURI, 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);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

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

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

    try {//from www . j av  a  2  s.com

        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
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

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

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI
        String attributeName = null;
        attributeName = getClaimAtrribute(claimURI, userName, null);

        Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);

        updatedAttributes.put(currentUpdatedAttribute);

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

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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

@Override
public void doDeleteUserClaimValues(String userName, 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);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

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

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

    try {//from   w  w  w .j  av  a2 s  . c om

        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
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

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

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI

        for (String claimURI : claims) {
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            updatedAttributes.put(currentUpdatedAttribute);
        }

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

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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

/**
 * Reused methods to search users with various filters
 *
 * @param searchFilter//ww w.jav  a2 s  .c  o  m
 * @param returningAttributes
 * @param searchScope
 * @return
 */
private NamingEnumeration<SearchResult> searchInUserBase(String searchFilter, String[] returningAttributes,
        int searchScope, DirContext rootContext) throws UserStoreException {

    if (log.isDebugEnabled()) {
        log.debug("Searching user with " + searchFilter);
    }
    String userBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setReturningAttributes(returningAttributes);
    userSearchControl.setSearchScope(searchScope);
    NamingEnumeration<SearchResult> userSearchResults = null;

    try {
        userSearchResults = rootContext.search(escapeDNForSearch(userBase), searchFilter, userSearchControl);
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in user base.";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }

    return userSearchResults;

}

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

/**
 * Reused method to search groups with various filters.
 *
 * @param searchFilter/*from ww w .ja  va  2  s.  co m*/
 * @param returningAttributes
 * @param searchScope
 * @return
 */
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.user.core.tenant.CommonHybridLDAPTenantManager.java

/**
 * Check if organizational unit is created in tenant.
 *
 * @param orgName           Organization name.
 * @param initialDirContext The directory connection.
 * @throws UserStoreException If an error occurred while searching.
 *///w  ww  .  j a v a2 s .  c om
protected boolean isOrganizationalUnitCreated(String orgName, DirContext initialDirContext)
        throws UserStoreException {

    //construct search filter,eg. (&(objectClass=organizationalUnit)(ou=wso2.com))
    String partitionDN = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ROOT_PARTITION);
    String organizationalObjectClass = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_OBJECT_CLASS);
    String organizationalAttribute = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_ATTRIBUTE);
    String searchFilter = "(&(objectClass=" + organizationalObjectClass + ")(" + organizationalAttribute + "="
            + orgName + "))";

    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> userSearchResults = null;

    try {
        userSearchResults = initialDirContext.search(partitionDN, searchFilter, userSearchControl);
        return userSearchResults.hasMore();
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in root partition for organization : " + orgName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeActors(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws Exception {
    int changesCount = 0;
    List<Actor> existingActorsList = executorDao.getAllActors(BatchPresentationFactory.ACTORS.createNonPaged());
    Map<String, Actor> existingActorsMap = Maps.newHashMap();
    for (Actor actor : existingActorsList) {
        existingActorsMap.put(actor.getName().toLowerCase(), actor);
    }//from   w  w w. jav  a 2 s.c  o  m
    Set<Actor> ldapActorsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        ldapActorsToDelete.addAll(executorDao.getGroupActors(importGroup));
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        List<SearchResult> resultList = Lists.newArrayList();
        try {
            NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_USER_FILTER, controls);
            while (list.hasMore()) {
                SearchResult searchResult = list.next();
                resultList.add(searchResult);
            }
            list.close();
        } catch (SizeLimitExceededException e) {
            resultList.clear();
            for (String y : ALPHABETS) {
                NamingEnumeration<SearchResult> list = dirContext.search(ou,
                        MessageFormat.format(LOGIN_FIRST_LETTER_FILTER, ATTR_ACCOUNT_NAME, y, y.toLowerCase(),
                                OBJECT_CLASS_USER_FILTER),
                        controls);
                while (list.hasMore()) {
                    SearchResult searchResult = list.next();
                    resultList.add(searchResult);
                }
                list.close();
            }
        }
        for (SearchResult searchResult : resultList) {
            String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
            String description = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDescriptionAttribute());
            String fullName = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserFullNameAttribute());
            String email = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserEmailAttribute());
            String phone = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserPhoneAttribute());
            String title = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserTitleAttribute());
            String department = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDepartmentAttribute());
            ToStringHelper toStringHelper = MoreObjects.toStringHelper("user info");
            toStringHelper.add("name", name).add("description", description).add("fullName", fullName)
                    .add("email", email);
            toStringHelper.add("phone", phone).add("title", title).add("department", department)
                    .omitNullValues();
            log.debug("Read " + toStringHelper.toString());
            Actor actor = existingActorsMap.get(name.toLowerCase());
            if (actor == null) {
                if (!LdapProperties.isSynchronizationCreateExecutors()) {
                    continue;
                }
                actor = new Actor(name, description, fullName, null, email, phone, title, department);
                log.info("Creating " + actor);
                executorDao.create(actor);
                executorDao.addExecutorsToGroup(Lists.newArrayList(actor), importGroup);
                permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), actor);
                changesCount++;
            } else {
                ldapActorsToDelete.remove(actor);
                if (LdapProperties.isSynchronizationUpdateExecutors()) {
                    List<IChange> changes = Lists.newArrayList();
                    if (isAttributeNeedsChange(description, actor.getDescription())) {
                        changes.add(new AttributeChange("description", actor.getDescription(), description));
                        actor.setDescription(description);
                    }
                    if (isAttributeNeedsChange(fullName, actor.getFullName())) {
                        changes.add(new AttributeChange("fullName", actor.getFullName(), fullName));
                        actor.setFullName(fullName);
                    }
                    if (isAttributeNeedsChange(email, actor.getEmail())) {
                        changes.add(new AttributeChange("email", actor.getEmail(), email));
                        actor.setEmail(email);
                    }
                    if (isAttributeNeedsChange(phone, actor.getPhone())) {
                        changes.add(new AttributeChange("phone", actor.getPhone(), phone));
                        actor.setPhone(phone);
                    }
                    if (isAttributeNeedsChange(title, actor.getTitle())) {
                        changes.add(new AttributeChange("title", actor.getTitle(), title));
                        actor.setTitle(title);
                    }
                    if (isAttributeNeedsChange(department, actor.getDepartment())) {
                        changes.add(new AttributeChange("department", actor.getDepartment(), department));
                        actor.setDepartment(department);
                    }
                    if (!actor.isActive()) {
                        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
                            actor.setActive(true);
                            changes.add(new AttributeChange("active", "false", "true"));
                        }
                        if (executorDao.removeExecutorFromGroup(actor, wasteGroup)) {
                            changes.add(new Change("waste group removal"));
                        }
                        if (executorDao.addExecutorToGroup(actor, importGroup)) {
                            changes.add(new Change("import group addition"));
                        }
                    }
                    if (!changes.isEmpty()) {
                        executorDao.update(actor);
                        log.info("Updating " + actor + ": " + changes);
                        changesCount++;
                    }
                }
            }
            actorsByDistinguishedName.put(searchResult.getNameInNamespace(), actor);
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapActorsToDelete.size() > 0) {
        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
            for (Actor actor : ldapActorsToDelete) {
                actor.setActive(false);
                executorDao.update(actor);
                log.info("Inactivating " + actor);
                changesCount++;
            }
        }
        executorDao.removeExecutorsFromGroup(ldapActorsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapActorsToDelete, wasteGroup);
        changesCount += ldapActorsToDelete.size();
    }
    return changesCount;
}