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:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }// w ww. j a va 2 s. c o m SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } } }
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];//w ww.j av a 2s .c o m } 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:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildUserSearcher(final String query) { LOGGER.debug("Building user searcher for query {}", query); final SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); userSearchCtls.setReturningAttributes(this.userKeys.getFirst()); // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control userSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0); return (ctx) -> { try {/*from w w w .j a v a 2s . com*/ final NamingEnumeration<SearchResult> results = ctx.search(this.userSearchBase, query, userSearchCtls); return results; } catch (final NamingException e) { throw new AlfrescoRuntimeException("Failed to import people.", e); } }; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }//w w w. j a v a 2 s . c om SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); InitialDirContext ctx = null; for (String userSearchBase : this.userSearchBases) { String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPMultiBaseUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); } if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } // failed to search // Object[] args = {e.getLocalizedMessage()}; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic); }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildGroupSearcher(final String query) { LOGGER.debug("Building group searcher for query {}", query); final SearchControls groupSearchCtls = new SearchControls(); groupSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); groupSearchCtls.setReturningAttributes(this.groupKeys.getFirst()); // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control groupSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0); return (ctx) -> { try {/* w w w .j a v a 2s.co m*/ final NamingEnumeration<SearchResult> results = ctx.search(this.groupSearchBase, query, groupSearchCtls); return results; } catch (final NamingException e) { throw new AlfrescoRuntimeException("Failed to import groups.", e); } }; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/*from w ww . j a va 2 s. c o m*/ */ @Override public boolean doCheckExistingRole(String roleName) throws UserStoreException { boolean debug = log.isDebugEnabled(); boolean isExisting = false; if (debug) { log.debug("Searching for role: " + roleName); } String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); if (debug) { log.debug("Using search filter: " + searchFilter); } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(new String[] { roleNameProperty }); NamingEnumeration<SearchResult> answer = null; DirContext dirContext = null; try { dirContext = connectionSource.getContext(); String[] roleSearchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : roleSearchBaseArray) { if (debug) { log.debug("Searching in " + searchBase); } try { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMoreElements()) { isExisting = true; break; } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e); } } } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { log.debug("Is role: " + roleName + " exist: " + isExisting); } return isExisting; }
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 {/* ww w . jav a2s.com*/ returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI String attributeName = null; attributeName = getClaimAtrribute(claimURI, userName, null); Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); updatedAttributes.put(currentUpdatedAttribute); subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:com.aurel.track.util.LdapUtil.java
/** * Returns a HashMap <login name, TPersonBean> for all LDAP objects found in * the directory und the DN configured in the Genji server configuration. * // w w w . ja v a 2 s.c o m * @return Map with <login name, TPersonBean> */ public static HashMap<String, TPersonBean> getAllLdapPersonsPaged(TSiteBean siteBean, String filter) throws Exception { if (filter == null || "".equals(filter) || "*".equals(filter)) { filter = siteBean.getLdapAttributeLoginName() + "=*"; } if (!(filter.startsWith("(") && filter.endsWith(")"))) { filter = "(" + filter + ")"; } LOGGER.debug("User filter expression " + filter); String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); HashMap<String, TPersonBean> ldapPersonsMap = new HashMap<String, TPersonBean>(); LdapContext context = getInitialContext(siteBean.getLdapServerURL(), bindDN, bindPassword); if (context == null) { return ldapPersonsMap; } int recordCount = 0; // Create initial context // Control the search SearchControls ctls = null; try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return null; } String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME); String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME); String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL); String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE); String loginAttributeName = siteBean.getLdapAttributeLoginName(); do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", filter, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { ldapPersonsMap.put(personBean.getLoginName(), personBean); } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { if (context != null) { context.close(); } } return ldapPersonsMap; }
From source file:org.apache.syncope.fit.core.GroupITCase.java
@Test public void issueSYNCOPE632() { DerSchemaTO orig = schemaService.read(SchemaType.DERIVED, "displayProperty"); DerSchemaTO modified = SerializationUtils.clone(orig); modified.setExpression("icon + '_' + show"); GroupTO groupTO = GroupITCase.getSampleTO("lastGroup"); try {// w w w. j a v a2 s. co m schemaService.update(SchemaType.DERIVED, modified); // 0. create group groupTO.getPlainAttrs().add(attrTO("icon", "anIcon")); groupTO.getPlainAttrs().add(attrTO("show", "true")); groupTO.getResources().clear(); groupTO = createGroup(groupTO).getEntity(); assertNotNull(groupTO); // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP); newLDAP.setKey("new-ldap"); newLDAP.setPropagationPriority(0); for (ProvisionTO provision : newLDAP.getProvisions()) { provision.getVirSchemas().clear(); } MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).get().getMapping(); ItemTO connObjectKey = mapping.getConnObjectKeyItem(); connObjectKey.setIntAttrName("displayProperty"); connObjectKey.setPurpose(MappingPurpose.PROPAGATION); mapping.setConnObjectKeyItem(connObjectKey); mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'"); ItemTO description = new ItemTO(); description.setIntAttrName("key"); description.setExtAttrName("description"); description.setPurpose(MappingPurpose.PROPAGATION); mapping.add(description); newLDAP = createResource(newLDAP); assertNotNull(newLDAP); // 2. update group and give the resource created above GroupPatch patch = new GroupPatch(); patch.setKey(groupTO.getKey()); patch.getResources().add( new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value("new-ldap").build()); groupTO = updateGroup(patch).getEntity(); assertNotNull(groupTO); // 3. update the group GroupPatch groupPatch = new GroupPatch(); groupPatch.setKey(groupTO.getKey()); groupPatch.getPlainAttrs().add(attrAddReplacePatch("icon", "anotherIcon")); groupTO = updateGroup(groupPatch).getEntity(); assertNotNull(groupTO); // 4. check that a single group exists in LDAP for the group created and updated above int entries = 0; DirContext ctx = null; try { ctx = getLdapResourceDirContext(null, null); SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[] { "*", "+" }); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp", "(description=" + groupTO.getKey() + ")", ctls); while (result.hasMore()) { result.next(); entries++; } } catch (Exception e) { // ignore } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // ignore } } } assertEquals(1, entries); } finally { schemaService.update(SchemaType.DERIVED, orig); if (groupTO.getKey() != null) { groupService.delete(groupTO.getKey()); } resourceService.delete("new-ldap"); } }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
@Override public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles) throws UserStoreException { // get the DN of the user entry String userNameDN = this.getNameInSpaceForUserName(userName); String membershipAttribute = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); /*/* w w w . j ava 2s . c o m*/ * check deleted roles and delete member entries from relevant groups. */ String errorMessage = null; String roleSearchFilter = null; DirContext mainDirContext = this.connectionSource.getContext(); try { if (deletedRoles != null && deletedRoles.length != 0) { // perform validation for empty role occurrences before // updating in LDAP // check whether this is shared roles and where shared roles are // enable for (String deletedRole : deletedRoles) { String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER); roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole)); String[] returningAttributes = new String[] { membershipAttribute }; String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; if (groupResults.hasMore()) { resultedGroup = groupResults.next(); } if (resultedGroup != null && isOnlyUserInRole(userNameDN, resultedGroup) && !emptyRolesAllowed) { errorMessage = userName + " is the only user in the role: " + deletedRole + ". Hence can not delete user from role."; throw new UserStoreException(errorMessage); } JNDIUtil.closeNamingEnumeration(groupResults); } // if empty role violation does not happen, continue // updating the LDAP. for (String deletedRole : deletedRoles) { String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER); if (doCheckExistingRole(deletedRole)) { roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole)); String[] returningAttributes = new String[] { membershipAttribute }; String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; String groupDN = null; if (groupResults.hasMore()) { resultedGroup = groupResults.next(); groupDN = resultedGroup.getName(); } modifyUserInRole(userNameDN, groupDN, DirContext.REMOVE_ATTRIBUTE, searchBase); JNDIUtil.closeNamingEnumeration(groupResults); } else { errorMessage = "The role: " + deletedRole + " does not exist."; throw new UserStoreException(errorMessage); } } } if (newRoles != null && newRoles.length != 0) { for (String newRole : newRoles) { String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER); if (doCheckExistingRole(newRole)) { roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(newRole)); String[] returningAttributes = new String[] { membershipAttribute }; String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; // assume only one group with given group name String groupDN = null; if (groupResults.hasMore()) { resultedGroup = groupResults.next(); groupDN = resultedGroup.getName(); } if (resultedGroup != null && !isUserInRole(userNameDN, resultedGroup)) { modifyUserInRole(userNameDN, groupDN, DirContext.ADD_ATTRIBUTE, searchBase); } else { errorMessage = "User: " + userName + " already belongs to role: " + groupDN; throw new UserStoreException(errorMessage); } JNDIUtil.closeNamingEnumeration(groupResults); } else { errorMessage = "The role: " + newRole + " does not exist."; throw new UserStoreException(errorMessage); } } } } catch (NamingException e) { errorMessage = "Error occurred while modifying the role list of user: " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeContext(mainDirContext); } }