List of usage examples for javax.naming.directory DirContext REPLACE_ATTRIBUTE
int REPLACE_ATTRIBUTE
To view the source code for javax.naming.directory DirContext REPLACE_ATTRIBUTE.
Click Source Link
From source file:org.swordess.ldap.util.ModUtils.java
public static <T> ModificationItem replace(String id, Object[] values, Evaluator<T> evaluator) { return create(DirContext.REPLACE_ATTRIBUTE, id, values, evaluator); }
From source file:org.swordess.ldap.util.ModUtils.java
public static ModificationItem replace(String id, Collection<?> values) { return create(DirContext.REPLACE_ATTRIBUTE, id, values, null); }
From source file:org.swordess.ldap.util.ModUtils.java
public static <T> ModificationItem replace(String id, Collection<?> values, Evaluator<T> evaluator) { return create(DirContext.REPLACE_ATTRIBUTE, id, values, evaluator); }
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 {/*from ww w .j a va2 s . com*/ 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;//from w ww . j a v a 2 s. c om try { 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.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * *///from w ww . j ava2s.c o m public void doAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims, String profileName, boolean requirePasswordChange) throws UserStoreException { boolean isUserBinded = false; /* getting search base directory context */ DirContext dirContext = getSearchBaseDirectoryContext(); /* getting add user basic attributes */ BasicAttributes basicAttributes = getAddUserBasicAttributes(userName); if (!isADLDSRole) { // creating a disabled user account in AD DS BasicAttribute userAccountControl = new BasicAttribute( LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL); userAccountControl.add(LDAPConstants.ACTIVE_DIRECTORY_DISABLED_NORMAL_ACCOUNT); basicAttributes.put(userAccountControl); } /* setting claims */ setUserClaims(claims, basicAttributes, userName); Name compoundName = null; try { NameParser ldapParser = dirContext.getNameParser(""); compoundName = ldapParser.parse("cn=" + escapeSpecialCharactersForDN(userName)); /* bind the user. A disabled user account with no password */ dirContext.bind(compoundName, null, basicAttributes); isUserBinded = true; /* update the user roles */ doUpdateRoleListOfUser(userName, null, roleList); /* reset the password and enable the account */ if (!isSSLConnection) { logger.warn("Unsecured connection is being used. Enabling user account operation will fail"); } ModificationItem[] mods = new ModificationItem[2]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, createUnicodePassword((String) credential))); if (isADLDSRole) { mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_MSDS_USER_ACCOUNT_DISSABLED, "FALSE")); } else { mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute( LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL, userAccountControl)); } dirContext.modifyAttributes(compoundName, mods); } catch (NamingException e) { String errorMessage = "Error while adding the user to the Active Directory for user : " + userName; if (isUserBinded) { try { dirContext.unbind(compoundName); } catch (NamingException e1) { errorMessage = "Error while accessing the Active Directory for user : " + userName; throw new UserStoreException(errorMessage, e); } errorMessage = "Error while enabling the user account. Please check password policy at DC for user : " + userName; } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * *//*ww w. j a v a2s . c om*/ public void doUpdateCredential(String userName, Object newCredential, Object oldCredential) throws UserStoreException { if (!isSSLConnection) { logger.warn("Unsecured connection is being used. Password operations will fail"); } DirContext dirContext = this.connectionSource.getContext(); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER); String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); // String searchFilter = // realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "=" + escapeSpecialCharactersForFilter(userName) + "))"; SearchControls searchControl = new SearchControls(); String[] returningAttributes = { "CN" }; searchControl.setReturningAttributes(returningAttributes); searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE); DirContext subDirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { // search the user with UserNameAttribute and obtain its CN attribute searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl); SearchResult user = null; int count = 0; while (searchResults.hasMore()) { if (count > 0) { throw new UserStoreException( "There are more than one result in the user store " + "for user: " + userName); } user = searchResults.next(); count++; } String userCNValue = null; if (user.getAttributes() != null) { Attribute cnAttribute = user.getAttributes().get("CN"); if (cnAttribute != null) { userCNValue = (String) cnAttribute.get(); } else { throw new UserStoreException("Can not update credential: CN attribute is null"); } } ModificationItem[] mods = null; // The user tries to change his own password if (oldCredential != null && newCredential != null) { mods = new ModificationItem[1]; /* * byte[] oldUnicodePassword = createUnicodePassword((String) oldCredential); byte[] * newUnicodePassword = createUnicodePassword((String) newCredential); */ mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, createUnicodePassword((String) newCredential))); /* * mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute( * LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, newUnicodePassword)); */ } subDirContext = (DirContext) dirContext.lookup(searchBase); subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods); } catch (NamingException e) { String error = "Can not access the directory service for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(error, e); } throw new UserStoreException(error, e); } finally { JNDIUtil.closeNamingEnumeration(searchResults); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
@Override public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException { if (!isSSLConnection) { logger.warn("Unsecured connection is being used. Password operations will fail"); }/*from w w w . ja v a 2 s. c o m*/ DirContext dirContext = this.connectionSource.getContext(); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER); String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "=" + escapeSpecialCharactersForFilter(userName) + "))"; SearchControls searchControl = new SearchControls(); String[] returningAttributes = { "CN" }; searchControl.setReturningAttributes(returningAttributes); searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE); DirContext subDirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { // search the user with UserNameAttribute and obtain its CN attribute searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl); SearchResult user = null; int count = 0; while (searchResults.hasMore()) { if (count > 0) { throw new UserStoreException( "There are more than one result in the user store " + "for user: " + userName); } user = searchResults.next(); count++; } String userCNValue = null; if (user.getAttributes() != null) { Attribute cnAttribute = user.getAttributes().get("CN"); if (cnAttribute != null) { userCNValue = (String) cnAttribute.get(); } else { throw new UserStoreException("Can not update credential: CN attribute is null"); } } ModificationItem[] mods = null; if (newCredential != null) { mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, createUnicodePassword((String) newCredential))); subDirContext = (DirContext) dirContext.lookup(searchBase); subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods); } } catch (NamingException e) { String error = "Can not access the directory service for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(error, e); } throw new UserStoreException(error, e); } finally { JNDIUtil.closeNamingEnumeration(searchResults); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * This method overwrites the method in LDAPUserStoreManager. This implements the functionality * of updating user's profile information in LDAP user store. * * @param userName/* w ww . j a v a 2s. com*/ * @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 {//w ww .j ava 2s. 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); } }