Example usage for javax.naming.directory BasicAttributes BasicAttributes

List of usage examples for javax.naming.directory BasicAttributes BasicAttributes

Introduction

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

Prototype

public BasicAttributes(boolean ignoreCase) 

Source Link

Document

Constructs a new instance of Attributes.

Usage

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

/**
 * set attributes of given resource.//from  w  w w.j a va 2 s . c om
 * 
 * @param scope
 *            scope
 * @param id
 *            id of resource
 * @param attributeNames
 *            attribute-names and values to set
 * 
 * @throws NamingException
 * @throws IllegalAccessException
 */
public void setResourceAttributes(Scope scope, String entryDn, Map<String, String> attributes)
        throws NamingException, IllegalAccessException {
    InitialLdapContext ctx = null;
    try {
        ctx = LDAPConnector.getSingletonInstance().takeCtx();
        BasicAttributes saveAttributes = new BasicAttributes(true);
        for (Entry<String, String> entry : attributes.entrySet()) {
            saveAttributes.put(new BasicAttribute(entry.getKey(), entry.getValue()));
        }
        ctx.modifyAttributes(entryDn, DirContext.REPLACE_ATTRIBUTE, saveAttributes);
    } finally {
        if (ctx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(ctx);
            } catch (IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
    }
}

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

@SuppressWarnings("rawtypes")
@Override// ww  w.  j av a  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.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 {/*w ww .j  av  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
        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.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetches the supplied user.// w ww. ja  v  a2s.  c om
 *
 * @param attrValue the user id
 * @return the user id for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 * @throws IOException 
 */
protected String selectUser(String attrId, String attrValue) throws NamingException, IOException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    BasicAttributes matchAttrs = new BasicAttributes(true);

    String uidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    matchAttrs.put(attrId, attrValue);

    // String[] principalAttr = {attrId};

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(uidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'");
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + attrValue + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return uidValue;
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Obtain the properties for the user associated with the given uid using the
 * configured user properties query string.
 *
 * @param uid the user id of the user for whom its user properties are required.
 * @return the hash map containing user properties as name/value pairs.
 * @throws NamingException LDAP error obtaining user properties.
 *///from   w  w  w  . j av  a 2 s  .  com
protected HashMap selectUserProperties(String uid) throws NamingException {
    HashMap userPropertiesResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext();

    BasicAttributes matchAttrs = new BasicAttributes(true);

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    matchAttrs.put(principalUidAttrName, uid);

    String userPropertiesQueryString = getUserPropertiesQueryString();
    HashMap userPropertiesQueryMap = parseQueryString(userPropertiesQueryString);

    Iterator i = userPropertiesQueryMap.keySet().iterator();
    List propertiesAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        propertiesAttrList.add(o);
    }

    String[] propertiesAttr = (String[]) propertiesAttrList.toArray(new String[propertiesAttrList.size()]);

    try {

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            for (int j = 0; j < propertiesAttr.length; j++) {

                Attribute attribute = attrs.get(propertiesAttr[j]);

                if (attribute == null) {
                    logger.warn("Invalid user property attribute '" + propertiesAttr[j] + "'");
                    continue;
                }

                Object propertyObject = attrs.get(propertiesAttr[j]).get();

                if (propertyObject == null) {
                    logger.warn("Found a 'null' value for user property '" + propertiesAttr[j] + "'");
                    continue;
                }

                String propertyValue = propertyObject.toString();
                String propertyName = (String) userPropertiesQueryMap.get(propertiesAttr[j]);

                userPropertiesResultSet.put(propertyName, propertyValue);

                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user property '" + propertyName + "' with value '" + propertyValue + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return userPropertiesResultSet;
}

From source file:org.springframework.ldap.core.DirContextAdapter.java

/**
 * @see javax.naming.directory.DirContext#getAttributes(String, String[])
 *//*from  w w w . j a  v  a  2  s. co m*/
public Attributes getAttributes(String name, String[] attrIds) throws NamingException {
    if (StringUtils.hasLength(name)) {
        throw new NameNotFoundException();
    }

    Attributes a = new BasicAttributes(true);
    Attribute target;
    for (int i = 0; i < attrIds.length; i++) {
        target = originalAttrs.get(attrIds[i]);
        if (target != null) {
            a.put(target);
        }
    }

    return a;
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

/**
 * set modification-properties in LDAP.//from   w ww  . j  av  a  2  s  .  c  o m
 * 
 * @param isCreate
 *            if also createProperties should be set.
 * @param performer
 *            performer.
 * @param id
 *            id to set properties for.
 * @param scope
 *            scope.
 * 
 * @return
 * @throws
 */
public void setModificationPropertiesInLdap(boolean isCreate, AasPrincipal performer, String id, Scope scope)
        throws NamingException, IllegalAccessException {
    String propertiesAttName = null;
    if (scope == Scope.PERSON) {
        propertiesAttName = Constants.ldap_ddbPerson_Properties;
    } else if (scope == Scope.ORGANIZATION) {
        propertiesAttName = Constants.ldap_ddbOrg_Properties;
    } else {
        throw new IllegalAccessException("scope does not match");
    }

    Map<String, String> attributes = getResourceAttributes(scope, id,
            new String[] { propertiesAttName, Constants.ldap_ddb_EntryDN });
    DdbProperties properties = null;
    String entryDn = null;
    if (attributes != null && StringUtils.isNotBlank(attributes.get(Constants.ldap_ddb_EntryDN))) {
        if (StringUtils.isNotBlank(attributes.get(propertiesAttName))) {
            properties = serializer.deserialize(attributes.get(propertiesAttName));
        }
        properties = PropertiesHelper.setModificationProperties(properties, isCreate, performer);
        entryDn = attributes.get(Constants.ldap_ddb_EntryDN);
    } else {
        throw new NameNotFoundException("entry with id=" + id + " not found");
    }
    InitialLdapContext ctx = null;
    try {
        ctx = LDAPConnector.getSingletonInstance().takeCtx();
        Attributes saveAttributes = new BasicAttributes(true);
        saveAttributes.put(new BasicAttribute(propertiesAttName, serializer.serialize(properties)));
        ctx.modifyAttributes(entryDn, DirContext.REPLACE_ATTRIBUTE, saveAttributes);
    } finally {
        if (ctx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(ctx);
            } catch (IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
    }

}

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  www . j a v  a  2  s  .co  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 va2s  .c om
 * @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 w  w  .j a  v  a2s.com
    }
    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);
    }

}