Example usage for javax.naming.directory DirContext modifyAttributes

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

Introduction

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

Prototype

public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException;

Source Link

Document

Modifies the attributes associated with a named object.

Usage

From source file:org.wso2.carbon.connector.ldap.UpdateEntry.java

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    String attributesString = (String) getParameter(messageContext, LDAPConstants.ATTRIBUTES);
    String dn = (String) getParameter(messageContext, LDAPConstants.DN);
    String mode = (String) getParameter(messageContext, LDAPConstants.MODE);

    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(LDAPConstants.CONNECTOR_NAMESPACE, LDAPConstants.NAMESPACE);
    OMElement result = factory.createOMElement(LDAPConstants.RESULT, ns);
    OMElement message = factory.createOMElement(LDAPConstants.MESSAGE, ns);

    try {/*  w w w .  j  a  v a  2 s  . c  om*/
        DirContext context = LDAPUtils.getDirectoryContext(messageContext);

        Attributes entry = new BasicAttributes();
        if (StringUtils.isNotEmpty(attributesString)) {
            JSONObject object = new JSONObject(attributesString);
            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String val = object.getString(key);
                Attribute newAttr = new BasicAttribute(key);
                newAttr.add(val);
                entry.put(newAttr);
            }
        }

        try {
            if (mode.equals(LDAPConstants.REPLACE)) {
                context.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, entry);
            } else if (mode.equals(LDAPConstants.ADD)) {
                context.modifyAttributes(dn, DirContext.ADD_ATTRIBUTE, entry);
            } else if (mode.equals(LDAPConstants.REMOVE)) {
                context.modifyAttributes(dn, DirContext.REMOVE_ATTRIBUTE, entry);
            }
            message.setText(LDAPConstants.SUCCESS);
            result.addChild(message);
            LDAPUtils.preparePayload(messageContext, result);
        } catch (NamingException e) { // LDAP Errors are catched
            LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.UPDATE_ENTRY_ERROR, e);
            throw new SynapseException(e);
        }
    } catch (NamingException e) { //Authentication failures are catched
        LDAPUtils.handleErrorResponse(messageContext, LDAPConstants.ErrorConstants.INVALID_LDAP_CREDENTIALS, e);
        throw new SynapseException(e);
    } catch (JSONException e) {
        handleException("Error while passing the JSON object", e, messageContext);
    }
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public void updateServicePrinciplePassword(String serverName, Object oldCredential, Object newCredentials)
        throws DirectoryServerManagerException {

    DirContext dirContext;

    try {/*from ww  w.  j a va 2  s .c  om*/
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    //first search the existing user entry.
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = getServicePrincipleFilter(serverName);

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

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);
        // here we assume only one user
        while (namingEnumeration.hasMore()) {

            BasicAttributes basicAttributes = new BasicAttributes(true);

            SearchResult searchResult = namingEnumeration.next();
            Attributes attributes = searchResult.getAttributes();

            Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD);
            Attribute newPasswordAttribute = getChangePasswordAttribute(userPassword, oldCredential,
                    newCredentials);
            basicAttributes.put(newPasswordAttribute);

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

            dirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }

    } catch (NamingException e) {
        log.error("Unable to update server principle password details. Server name - " + serverName);
        throw new DirectoryServerManagerException("Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}

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

/**
 * Either delete or add user from/to group.
 *
 * @param userNameDN : distinguish name of user entry.
 * @param groupRDN   : relative distinguish name of group entry
 * @param modifyType : modify attribute type in DirCOntext.
 * @throws UserStoreException If an error occurs while updating.
 *//*from   w  ww  .j a  va  2  s .  c  o  m*/
protected void modifyUserInRole(String userNameDN, String groupRDN, int modifyType, String searchBase)
        throws UserStoreException {

    if (log.isDebugEnabled()) {
        log.debug("Modifying role: " + groupRDN + " with type: " + modifyType + " user: " + userNameDN
                + " in search base: " + searchBase);
    }

    DirContext mainDirContext = null;
    DirContext groupContext = null;
    try {
        mainDirContext = this.connectionSource.getContext();
        groupContext = (DirContext) mainDirContext.lookup(searchBase);
        String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
        Attributes modifyingAttributes = new BasicAttributes(true);
        Attribute memberAttribute = new BasicAttribute(memberAttributeName);
        memberAttribute.add(userNameDN);
        modifyingAttributes.put(memberAttribute);

        groupContext.modifyAttributes(groupRDN, modifyType, modifyingAttributes);
        if (log.isDebugEnabled()) {
            log.debug("User: " + userNameDN + " was successfully " + "modified in LDAP group: " + groupRDN);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while modifying user entry: " + userNameDN + " in LDAP role: "
                + groupRDN;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage);
    } finally {
        JNDIUtil.closeContext(groupContext);
        JNDIUtil.closeContext(mainDirContext);
    }
}

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/* w ww  .j  a  va  2 s.  co m*/
 * @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);
    }

}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.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);
    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   ww w  .  ja  v  a2  s  .  c  o 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
        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);
    }

    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 = getClaimAtrribute(claimURI, userName, null);

        if ("CN".equals(attributeName)) {
            subDirContext = (DirContext) dirContext.lookup(userSearchBase);
            subDirContext.rename(returnedUserEntry, "CN=" + value);
            return;
        }

        Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
        /* if updated attribute value is null, remove its values. */
        if (EMPTY_ATTRIBUTE_STRING.equals(value)) {
            currentUpdatedAttribute.clear();
        } else {
            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 (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);
    }

}

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

@SuppressWarnings("rawtypes")
@Override/*from   ww w  . j  a va  2  s.  c  o 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 {//www.  ja va2s. com
        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 w w  w  .j  a  va  2  s  . co  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];/*from w  ww. 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   w w w .  ja va2s. c o 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);
    }
}