Example usage for javax.naming.directory DirContext REMOVE_ATTRIBUTE

List of usage examples for javax.naming.directory DirContext REMOVE_ATTRIBUTE

Introduction

In this page you can find the example usage for javax.naming.directory DirContext REMOVE_ATTRIBUTE.

Prototype

int REMOVE_ATTRIBUTE

To view the source code for javax.naming.directory DirContext REMOVE_ATTRIBUTE.

Click Source Link

Document

This constant specifies to delete the specified attribute values from the attribute.

Usage

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

@Override
public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles)
        throws UserStoreException {

    // get the DN of the user entry
    String userNameDN = this.getNameInSpaceForUserName(userName);
    String membershipAttribute = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
    /*/*w w  w. j a  v  a  2s .c o m*/
     * check deleted roles and delete member entries from relevant groups.
     */
    String errorMessage = null;
    String roleSearchFilter = null;

    DirContext mainDirContext = this.connectionSource.getContext();

    try {
        if (deletedRoles != null && deletedRoles.length != 0) {
            // perform validation for empty role occurrences before
            // updating in LDAP
            // check whether this is shared roles and where shared roles are
            // enable

            for (String deletedRole : deletedRoles) {
                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);
                roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                String[] returningAttributes = new String[] { membershipAttribute };
                String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
                NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                        returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                SearchResult resultedGroup = null;
                if (groupResults.hasMore()) {
                    resultedGroup = groupResults.next();
                }
                if (resultedGroup != null && isOnlyUserInRole(userNameDN, resultedGroup)
                        && !emptyRolesAllowed) {
                    errorMessage = userName + " is the only user in the role: " + deletedRole
                            + ". Hence can not delete user from role.";
                    throw new UserStoreException(errorMessage);
                }

                JNDIUtil.closeNamingEnumeration(groupResults);
            }
            // if empty role violation does not happen, continue
            // updating the LDAP.
            for (String deletedRole : deletedRoles) {

                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);

                if (doCheckExistingRole(deletedRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    modifyUserInRole(userNameDN, groupDN, DirContext.REMOVE_ATTRIBUTE, searchBase);
                    JNDIUtil.closeNamingEnumeration(groupResults);
                } else {
                    errorMessage = "The role: " + deletedRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }
        if (newRoles != null && newRoles.length != 0) {

            for (String newRole : newRoles) {
                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);

                if (doCheckExistingRole(newRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(newRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);

                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    // assume only one group with given group name
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    if (resultedGroup != null && !isUserInRole(userNameDN, resultedGroup)) {
                        modifyUserInRole(userNameDN, groupDN, DirContext.ADD_ATTRIBUTE, searchBase);
                    } else {
                        errorMessage = "User: " + userName + " already belongs to role: " + groupDN;
                        throw new UserStoreException(errorMessage);
                    }

                    JNDIUtil.closeNamingEnumeration(groupResults);

                } else {
                    errorMessage = "The role: " + newRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }

    } catch (NamingException e) {
        errorMessage = "Error occurred while modifying the role list of user: " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(mainDirContext);
    }
}

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 {/* w w w .j a  v a 2  s .co m*/

        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 {/*w  ww.j  a v  a 2  s . co m*/

        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

/**
 * Update role list of user by writing to LDAP.
 *
 * @param userName/*w  w  w.  j  a  va  2  s .c  om*/
 * @param deletedRoles
 * @param newRoles
 * @throws UserStoreException
 */
@SuppressWarnings("deprecation")
@Override
public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles)
        throws UserStoreException {

    // get the DN of the user entry
    String userNameDN = this.getNameInSpaceForUserName(userName);
    String membershipAttribute = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);

    /*
     * check deleted roles and delete member entries from relevant groups.
     */
    String errorMessage = null;
    String roleSearchFilter = null;

    DirContext mainDirContext = this.connectionSource.getContext();

    try {
        if (deletedRoles != null && deletedRoles.length != 0) {
            // perform validation for empty role occurrences before
            // updating in LDAP
            // check whether this is shared roles and where shared roles are
            // enable

            for (String deletedRole : deletedRoles) {
                LDAPRoleContext context = (LDAPRoleContext) createRoleContext(deletedRole);
                deletedRole = context.getRoleName();
                String searchFilter = context.getSearchFilter();
                roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                String[] returningAttributes = new String[] { membershipAttribute };
                String searchBase = context.getSearchBase();
                NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                        returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                SearchResult resultedGroup = null;
                if (groupResults.hasMore()) {
                    resultedGroup = groupResults.next();
                }
                if (resultedGroup != null && isOnlyUserInRole(userNameDN, resultedGroup)
                        && !emptyRolesAllowed) {
                    errorMessage = userName + " is the only user in the role: " + deletedRole
                            + ". Hence can not delete user from role.";
                    throw new UserStoreException(errorMessage);
                }

                JNDIUtil.closeNamingEnumeration(groupResults);
            }
            // if empty role violation does not happen, continue
            // updating the LDAP.
            for (String deletedRole : deletedRoles) {

                LDAPRoleContext context = (LDAPRoleContext) createRoleContext(deletedRole);
                deletedRole = context.getRoleName();
                String searchFilter = context.getSearchFilter();

                if (isExistingRole(deletedRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = context.getSearchBase();
                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    this.modifyUserInRole(userNameDN, groupDN, DirContext.REMOVE_ATTRIBUTE, searchBase);

                    JNDIUtil.closeNamingEnumeration(groupResults);

                    // need to update authz cache of user since roles
                    // are deleted
                    userRealm.getAuthorizationManager().clearUserAuthorization(userName);

                } else {
                    errorMessage = "The role: " + deletedRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }
        if (newRoles != null && newRoles.length != 0) {

            for (String newRole : newRoles) {

                LDAPRoleContext context = (LDAPRoleContext) createRoleContext(newRole);
                newRole = context.getRoleName();
                String searchFilter = context.getSearchFilter();

                if (isExistingRole(newRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(newRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = context.getSearchBase();

                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    // assume only one group with given group name
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    if (resultedGroup != null && !isUserInRole(userNameDN, resultedGroup)) {
                        modifyUserInRole(userNameDN, groupDN, DirContext.ADD_ATTRIBUTE, searchBase);
                    } else {
                        errorMessage = "User: " + userName + " already belongs to role: " + groupDN;
                        throw new UserStoreException(errorMessage);
                    }

                    JNDIUtil.closeNamingEnumeration(groupResults);

                } else {
                    errorMessage = "The role: " + newRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }

    } catch (NamingException e) {
        errorMessage = "Error occurred while modifying the role list of user: " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(mainDirContext);
    }
}

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

/**
 * Update the set of users belong to a LDAP role.
 *
 * @param roleName//from   ww w  .  j  a  va  2 s  .  c  o m
 * @param deletedUsers
 * @param newUsers
 */
@SuppressWarnings("deprecation")
@Override
public void doUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers)
        throws UserStoreException {

    String errorMessage = null;
    NamingEnumeration<SearchResult> groupSearchResults = null;

    LDAPRoleContext ctx = (LDAPRoleContext) createRoleContext(roleName);
    roleName = ctx.getRoleName();

    String searchFilter = ctx.getSearchFilter();

    if (isExistingLDAPRole(ctx)) {

        DirContext mainDirContext = this.connectionSource.getContext();

        try {
            searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(roleName));
            String membershipAttributeName = realmConfig
                    .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
            String[] returningAttributes = new String[] { membershipAttributeName };

            String searchBase = ctx.getSearchBase();
            groupSearchResults = searchInGroupBase(searchFilter, returningAttributes,
                    SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
            SearchResult resultedGroup = null;
            String groupName = null;
            while (groupSearchResults.hasMoreElements()) {
                resultedGroup = groupSearchResults.next();
                groupName = resultedGroup.getName();
            }
            // check whether update operations are going to violate non
            // empty role
            // restriction specified in user-mgt.xml by
            // checking whether all users are trying to be deleted
            // before updating LDAP.
            Attribute returnedMemberAttribute = resultedGroup.getAttributes().get(membershipAttributeName);
            if (!emptyRolesAllowed
                    && newUsers.length - deletedUsers.length + returnedMemberAttribute.size() == 0) {
                errorMessage = "There should be at least one member in the role. "
                        + "Hence can not delete all the members.";
                throw new UserStoreException(errorMessage);

            } else {
                List<String> newUserList = new ArrayList<String>();
                List<String> deleteUserList = new ArrayList<String>();

                if (newUsers != null && newUsers.length != 0) {
                    String invalidUserList = "";
                    String existingUserList = "";

                    for (String newUser : newUsers) {
                        if (StringUtils.isEmpty(newUser)) {
                            continue;
                        }
                        String userNameDN = getNameInSpaceForUserName(newUser);
                        if (userNameDN == null) {
                            invalidUserList += newUser + " ";
                        } else if (isUserInRole(userNameDN, resultedGroup)) {
                            existingUserList += userNameDN + ",";
                        } else {
                            newUserList.add(userNameDN);
                        }
                    }
                    if (!StringUtils.isEmpty(invalidUserList) || !StringUtils.isEmpty(existingUserList)) {
                        errorMessage = (StringUtils.isEmpty(invalidUserList) ? ""
                                : "'" + invalidUserList + "' not in the user store. ")
                                + (StringUtils.isEmpty(existingUserList) ? ""
                                        : "'" + existingUserList + "' already belong to the role : "
                                                + roleName);
                        throw new UserStoreException(errorMessage);
                    }
                }

                if (deletedUsers != null && deletedUsers.length != 0) {
                    String invalidUserList = "";
                    for (String deletedUser : deletedUsers) {
                        if (StringUtils.isEmpty(deletedUser)) {
                            continue;
                        }
                        String userNameDN = getNameInSpaceForUserName(deletedUser);
                        if (userNameDN == null) {
                            invalidUserList += deletedUser + ",";
                        } else {
                            deleteUserList.add(userNameDN);
                        }
                    }
                    if (!StringUtils.isEmpty(invalidUserList)) {
                        errorMessage = "'" + invalidUserList + "' not in the user store.";
                        throw new UserStoreException(errorMessage);
                    }

                }

                for (String userNameDN : newUserList) {
                    modifyUserInRole(userNameDN, groupName, DirContext.ADD_ATTRIBUTE, searchBase);
                }

                for (String userNameDN : deleteUserList) {
                    modifyUserInRole(userNameDN, groupName, DirContext.REMOVE_ATTRIBUTE, searchBase);
                    // needs to clear authz cache for deleted users
                    userRealm.getAuthorizationManager().clearUserAuthorization(userNameDN);
                }
            }
        } catch (NamingException e) {
            errorMessage = "Error occurred while modifying the user list of role: " + roleName;
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
            throw new UserStoreException(errorMessage, e);
        } finally {
            JNDIUtil.closeNamingEnumeration(groupSearchResults);
            JNDIUtil.closeContext(mainDirContext);
        }
    } else {
        errorMessage = "The role: " + roleName + " does not exist.";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage);
        }
        throw new UserStoreException(errorMessage);
    }
}