List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE
int SUBTREE_SCOPE
To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.
Click Source Link
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) { Object[] filterArguments = { _roleObjectClass }; SearchControls ctls = new SearchControls(); ctls.setDerefLinkFlag(true);//from w ww.j av a 2 s . c om ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>(); try { NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls); while (results.hasMoreElements()) { SearchResult result = results.nextElement(); Attributes attributes = result.getAttributes(); if (attributes == null) { continue; } Attribute roleAttribute = attributes.get(_roleNameAttribute); Attribute memberAttribute = attributes.get(_roleMemberAttribute); if (roleAttribute == null || memberAttribute == null) { continue; } NamingEnumeration role = roleAttribute.getAll(); NamingEnumeration members = memberAttribute.getAll(); if (!role.hasMore() || !members.hasMore()) { continue; } String roleName = (String) role.next(); if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) { roleName = roleName.replace(_rolePrefix, ""); } while (members.hasMore()) { String member = (String) members.next(); Matcher roleMatcher = rolePattern.matcher(member); if (!roleMatcher.find()) { continue; } String roleMember = roleMatcher.group(1); List<String> memberOf; if (roleMemberOfMap.containsKey(roleMember)) { memberOf = roleMemberOfMap.get(roleMember); } else { memberOf = new ArrayList<String>(); } memberOf.add(roleName); roleMemberOfMap.put(roleMember, memberOf); } } } catch (NamingException e) { e.printStackTrace(); } return roleMemberOfMap; }
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/* ww w . jav 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.ReadWriteLDAPUserStoreManager.java
@SuppressWarnings("deprecation") @Override/*from w w w . j av a 2 s .c om*/ public void doDeleteUser(String userName) throws UserStoreException { boolean debug = log.isDebugEnabled(); if (debug) { log.debug("Deleting user: " + userName); } // delete user from LDAP group if read-write enabled. String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); String[] returningUserAttributes = new String[] { userNameAttribute }; DirContext mainDirContext = this.connectionSource.getContext(); NamingEnumeration<SearchResult> userResults = searchInUserBase(searchFilter, returningUserAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext); NamingEnumeration<SearchResult> groupResults = null; DirContext subDirContext = null; try { SearchResult userResult = null; String userDN = null; // here we assume only one user // TODO: what to do if there are more than one user while (userResults.hasMore()) { userResult = userResults.next(); userDN = userResult.getName(); log.debug("User DN: " + userDN); } // LDAP roles of user to delete the mapping List<String> roles = new ArrayList<String>(); String[] externalRoles = doGetExternalRoleListOfUser(userName, "*"); roles.addAll(Arrays.asList(externalRoles)); if (isSharedGroupEnabled()) { String[] sharedRoles = doGetSharedRoleListOfUser(null, userName, "*"); if (sharedRoles != null) { roles.addAll(Arrays.asList(sharedRoles)); } } String[] rolesOfUser = roles.toArray(new String[roles.size()]); if (rolesOfUser.length != 0) { String[] returningGroupAttributes = new String[] { realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE) }; for (String role : rolesOfUser) { RoleContext context = createRoleContext(role); String searchBase = ((LDAPRoleContext) context).getSearchBase(); searchFilter = ((LDAPRoleContext) context).getSearchFilter(); role = context.getRoleName(); if (role.indexOf("/") > -1) { role = (role.split("/"))[1]; } String grpSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(role)); groupResults = searchInGroupBase(grpSearchFilter, returningGroupAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult groupResult = null; while (groupResults.hasMore()) { groupResult = groupResults.next(); } if (isOnlyUserInRole(userDN, groupResult) && !emptyRolesAllowed) { String errorMessage = "User: " + userName + " is the only user " + "in " + role + "." + "There should be at " + "least one user" + " in the role. Hence can" + " not delete the user."; throw new UserStoreException(errorMessage); } } // delete role list doUpdateRoleListOfUser(userName, rolesOfUser, new String[] {}); } // delete user entry if it exist if (userResult != null && userResult.getAttributes().get(userNameAttribute).get().toString() .toLowerCase().equals(userName.toLowerCase())) { if (log.isDebugEnabled()) { log.debug("Deleting " + userDN + " with search base " + userSearchBase); } subDirContext = (DirContext) mainDirContext.lookup(userSearchBase); subDirContext.destroySubcontext(userDN); } userCache.remove(userName); } catch (NamingException e) { String errorMessage = "Error occurred while deleting the user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(groupResults); JNDIUtil.closeNamingEnumeration(userResults); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(mainDirContext); } }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
@Override public <T> List<T> searchIndirections(Class<T> clazz, String filter) { if (null == filter) { return null; }// ww w. j a v a 2 s. com LogUtils.debug(LOG, String.format("search %s with filter=%s", clazz.getName(), filter)); OneMetaData oneMetaData = IndirectionsMetaData.get(clazz).getOne(); SearchControls ctrl = new SearchControls(); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); ctrl.setReturningAttributes(new String[] { oneMetaData.getIdAttr(), oneMetaData.getIndirectionAttr() }); try { List<T> retVal = new ArrayList<T>(); NamingEnumeration<SearchResult> results = ctx.search(oneMetaData.getContext(), filter, ctrl); while (results.hasMore()) { SearchResult result = results.next(); retVal.add(fromAttributesToIndirections(clazz, result.getAttributes())); } return retVal; } catch (NamingException e) { throw new SessionException(e.getMessage(), e); } }
From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java
/** * Gets all the user entities taken from the LDAP server, as taken from the * search-context given by the value of the attribute {@link #userBase}. * * @return A set containing all the relevant users found in the LDAP * directory./*from ww w .ja v a 2s .co m*/ * @throws NamingException * Propagated from the LDAP communication layer. */ private Set<String> getAllUsersFromLDAP() throws NamingException { Set<String> result = new HashSet<String>(); SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { "distinguishedName" }); NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, "(objectClass=" + userObjectClass + ")", sc); while (sr.hasMore()) { SearchResult r = sr.next(); result.add(r.getNameInNamespace()); } return result; }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean removeUserRole(String roleName, String username, DirContext context) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { log.warn("no group found for role '{}", roleName); return false; }/*from www .jav a 2 s. c o m*/ NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember()); if (attribute != null) { BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=" + username + "," + getGroupsDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute) }); } return true; } return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * Return a S4J user if successful bind to ldap * null if user or password is wrong/* www.ja v a2 s .co m*/ * * TODO if I don't need to provision user on ldap, I could avoid some of that stuff.. * when binding, it retrieves imap/smtp server data to provision mail push * @param username * @param password * @return the {@link Sync4jUser} created from ldap fields */ public LDAPUser bindUserToLdap(String username, String password) { LDAPUser ldapUser = null; String userDN = null; LdapManagerInterface ldapBindInterface = null; /* TODO * this is now done creating an eventually authenticated context specified in * configuration file. * moreover this context is shared between all ldap connections, * so could be better defined at application server level */ try { TempParams t = new TempParams(); // if username is an email substitute %u e %d in baseDn: expandSearchAndBaseDn(username, t); // setup the default LdapInterface configured with bean data // use a bean configuration file ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName()); ldapInterface.init(t.tmpLdapUrl, t.tmpBaseDn, getSearchBindDn(), getSearchBindPassword(), isFollowReferral(), isConnectionPooling(), null); // set the userDN when custom user search if (!StringUtils.isEmpty(getUserSearch())) { // search the user binding with default ldap credential defined in the Officer.xml ldapInterface.setBaseDn(t.tmpBaseDn); SearchResult sr = ldapInterface.searchOneEntry(t.tmpUserSearch, new String[] { "dn" }, SearchControls.SUBTREE_SCOPE); if (sr != null) { userDN = sr.getNameInNamespace().trim(); log.info("binding with dn:" + userDN); } else { log.info("Username" + username + "not found"); return null; } } else { // use append userDN = "uid=" + username + "," + baseDn; } ldapInterface.close(); ldapBindInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName()); ldapBindInterface.init(t.tmpLdapUrl, userDN, userDN, password, false, false, null); SearchResult sr = ldapBindInterface.searchOneEntry("(objectclass=*)", getLdapAttributesToRetrieve(), SearchControls.OBJECT_SCOPE); if (sr != null) { ldapUser = new LDAPUser(); ldapUser.setUsername(username); ldapUser.setPassword(password); if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_EMAIL))) { ldapUser.setEmail( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_EMAIL))); } if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_FIRSTNAME))) { ldapUser.setFirstname( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_FIRSTNAME))); } if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_LASTNAME))) { ldapUser.setLastname( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_LASTNAME))); } // set attributes to be passed to LDAP and CalDAV connector ldapUser.setUserDn(userDN); if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_ADDRESSBOOK))) { ldapUser.setPsRoot( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_ADDRESSBOOK))); } if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_CALENDAR))) { ldapUser.setPsRoot( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_CALENDAR))); } } else { return null; } } catch (SyncSourceException e1) { log.error("Can't instantiate context: " + e1.getMessage()); ldapUser = null; } catch (NamingException e) { log.warn("Can't retrieve mailserver attributes from ldap: " + e.getMessage()); ldapUser = null; } catch (LDAPAccessException e) { log.error("Can't instantiate context: " + e.getMessage()); ldapUser = null; } finally { if (ldapInterface != null) { ldapInterface.close(); } if (ldapBindInterface != null) { ldapBindInterface.close(); } } return ldapUser; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}// ww w .ja va 2 s . com */ public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException { boolean debug = log.isDebugEnabled(); String[] userNames = new String[0]; if (maxItemLimit == 0) { return userNames; } int givenMax; int searchTime; try { givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = CommonConstants.MAX_USER_LIST; } try { searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = CommonConstants.MAX_SEARCH_TIME; } if (maxItemLimit <= 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); searchCtls.setTimeLimit(searchTime); if (filter.contains("?") || filter.contains("**")) { throw new UserStoreException( "Invalid character sequence entered for user search. Please enter valid sequence."); } StringBuilder searchFilter = new StringBuilder( userStoreProperties.get(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE); String serviceNameAttribute = "sn"; StringBuilder finalFilter = new StringBuilder(); // read the display name attribute - if provided String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAtts; if (StringUtils.isNotEmpty(displayNameAttribute)) { returnedAtts = new String[] { userNameProperty, serviceNameAttribute, displayNameAttribute }; finalFilter.append("(&").append(searchFilter).append("(").append(displayNameAttribute).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); } else { returnedAtts = new String[] { userNameProperty, serviceNameAttribute }; finalFilter.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); } if (debug) { log.debug( "Listing users. SearchBase: " + searchBases + " Constructed-Filter: " + finalFilter.toString()); log.debug("Search controls. Max Limit: " + maxItemLimit + " Max Time: " + searchTime); } searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; List<String> list = new ArrayList<>(); try { dirContext = connectionSource.getContext(); // handle multiple search bases String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : searchBaseArray) { answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); while (answer.hasMoreElements()) { SearchResult sr = answer.next(); if (sr.getAttributes() != null) { log.debug("Result found .."); Attribute attr = sr.getAttributes().get(userNameProperty); // If this is a service principle, just ignore and // iterate rest of the array. The entity is a service if // value of surname is Service Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute); if (attrSurname != null) { if (debug) { log.debug(serviceNameAttribute + " : " + attrSurname); } String serviceName = (String) attrSurname.get(); if (serviceName != null && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) { continue; } } if (attr != null) { String name = (String) attr.get(); list.add(name); } } } } userNames = list.toArray(new String[list.size()]); Arrays.sort(userNames); if (debug) { for (String username : userNames) { log.debug("result: " + username); } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : " + maxItemLimit; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : " + maxItemLimit; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userNames; }
From source file:ldap.SearchUtility.java
/** * A utility method to get a conrols object. May be redundant; the default new Controls() would probably * suffice./*from ww w . j a v a 2 s . co m*/ * @return a new SearchControls object that can be modified and passed to a context.search method. */ private SearchControls getSearchControls() { SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); constraints.setCountLimit(0); constraints.setTimeLimit(0); return constraints; }
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 w w .j a v a 2 s. c o m*/ 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); } } }