List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void getGroups(UserGroupSink sink) throws Throwable { NamingEnumeration<SearchResult> groupSearchResultEnum = null; DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); long highestdeltaSyncGroupTime = deltaSyncGroupTime; try {//from w ww . ja v a2 s .c om createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")"; if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) { String customFilter = groupSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter; } extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>=" + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))"; LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter); for (int ou = 0; ou < groupSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { int paged = 0; do { groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], extendedAllGroupsSearchFilter, groupSearchControls); while (groupSearchResultEnum.hasMore()) { final SearchResult groupEntry = groupSearchResultEnum.next(); if (groupEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("groupEntry null, skipping sync for the entry"); } continue; } counter++; Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute); if (groupNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(groupNameAttribute + " empty for entry " + groupEntry.getNameInNamespace() + ", skipping sync"); } continue; } String gName = (String) groupNameAttr.get(); String transformGroupName = groupNameTransform(gName); // If group based search is enabled, then // update the group name to ranger admin // check for group members and populate userInfo object with user's full name and group mapping if (groupSearchFirstEnabled) { LOG.debug("Update Ranger admin with " + transformGroupName); sink.addOrUpdateGroup(transformGroupName); } Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged"); if (timeStampAttr != null) { String uSNChangedVal = (String) timeStampAttr.get(); long currentDeltaSyncTime = Long.parseLong(uSNChangedVal); if (currentDeltaSyncTime > highestdeltaSyncGroupTime) { highestdeltaSyncGroupTime = currentDeltaSyncTime; } } else { timeStampAttr = groupEntry.getAttributes().get("modifytimestamp"); if (timeStampAttr != null) { String timeStampVal = (String) timeStampAttr.get(); Date parseDate = dateFormat.parse(timeStampVal); long currentDeltaSyncTime = parseDate.getTime(); LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncGroupTime) { highestdeltaSyncGroupTime = currentDeltaSyncTime; deltaSyncGroupTimeStamp = timeStampVal; } } } Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName); int userCount = 0; if (groupMemberAttr == null || groupMemberAttr.size() <= 0) { LOG.info("No members available for " + gName); continue; } NamingEnumeration<?> userEnum = groupMemberAttr.getAll(); while (userEnum.hasMore()) { String originalUserFullName = (String) userEnum.next(); if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) { continue; } userCount++; String userName = getShortUserName(originalUserFullName); originalUserFullName = originalUserFullName.toLowerCase(); if (groupSearchFirstEnabled && !userSearchEnabled) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } userNameMap.put(originalUserFullName, transformUserName); } //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName); if (userNameMap.get(originalUserFullName) != null) { groupUserTable.put(gName, originalUserFullName, userNameMap.get(originalUserFullName)); } else { groupUserTable.put(gName, originalUserFullName, originalUserFullName); } groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName); } LOG.info("No. of members in the group " + gName + " = " + userCount); } // Examine the paged results control response Control[] controls = ldapContext.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) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { LOG.debug(String.format("Fetched paged results round: %s", ++paged)); ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter); } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t); LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter); } } } finally { if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } if (groupHierarchyLevels > 0) { LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime); if (deltaSyncGroupTime > 0) { LOG.info( "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync"); goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1); } } if (deltaSyncGroupTime < highestdeltaSyncGroupTime) { // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle. deltaSyncGroupTime = highestdeltaSyncGroupTime + 1; // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle. deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l)); } }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public List<String> getGroups(String username, DirContext context) throws MappingException { List<String> userGroups = new ArrayList<String>(); NamingEnumeration<SearchResult> namingEnumeration = null; try {//from ww w. j a v a 2 s . co m SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String groupEntry = null; try { //try to look the user up User user = userManager.findUser(username); if (user instanceof LdapUser) { LdapUser ldapUser = LdapUser.class.cast(user); Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute()); if (dnAttribute != null) { groupEntry = String.class.cast(dnAttribute.get()); } } } catch (UserNotFoundException e) { log.warn("Failed to look up user {}. Computing distinguished name manually", username, e); } catch (UserManagerException e) { log.warn("Failed to look up user {}. Computing distinguished name manually", username, e); } if (groupEntry == null) { //failed to look up the user's groupEntry directly StringBuilder builder = new StringBuilder(); String posixGroup = "posixGroup"; if (posixGroup.equals(getLdapGroupClass())) { builder.append(username); } else { builder.append(this.userIdAttribute).append("=").append(username).append(",") .append(getBaseDn()); } groupEntry = builder.toString(); } String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")") .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry)) .append(")").append(")").toString(); log.debug("filter: {}", filter); namingEnumeration = context.search(getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); List<String> allMembers = new ArrayList<String>(); Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember()); if (uniqueMemberAttr != null) { NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr .getAll(); while (allMembersEnum.hasMore()) { String userName = allMembersEnum.next(); //the original dn allMembers.add(userName); // uid=blabla we only want bla bla userName = StringUtils.substringAfter(userName, "="); userName = StringUtils.substringBefore(userName, ","); allMembers.add(userName); } close(allMembersEnum); } if (allMembers.contains(username)) { String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); userGroups.add(groupName); } else if (allMembers.contains(groupEntry)) { String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); userGroups.add(groupName); } } return userGroups; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { close(namingEnumeration); } }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void getUsers(UserGroupSink sink) throws Throwable { NamingEnumeration<SearchResult> userSearchResultEnum = null; NamingEnumeration<SearchResult> groupSearchResultEnum = null; try {// w ww. j a va 2 s.c o m createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); extendedUserSearchFilter = "(objectclass=" + userObjectClass + ")(|(uSNChanged>=" + deltaSyncUserTime + ")(modifyTimestamp>=" + deltaSyncUserTimeStamp + "Z))"; if (userSearchFilter != null && !userSearchFilter.trim().isEmpty()) { String customFilter = userSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } extendedUserSearchFilter = "(&" + extendedUserSearchFilter + customFilter + ")"; } else { extendedUserSearchFilter = "(&" + extendedUserSearchFilter + ")"; } LOG.info("extendedUserSearchFilter = " + extendedUserSearchFilter); long highestdeltaSyncUserTime = deltaSyncUserTime; // When multiple OUs are configured, go through each OU as the user search base to search for users. for (int ou = 0; ou < userSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { int paged = 0; do { userSearchResultEnum = ldapContext.search(userSearchBase[ou], extendedUserSearchFilter, userSearchControls); while (userSearchResultEnum.hasMore()) { // searchResults contains all the user entries final SearchResult userEntry = userSearchResultEnum.next(); if (userEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("userEntry null, skipping sync for the entry"); } continue; } //System.out.println("userEntry = " + userEntry); Attributes attributes = userEntry.getAttributes(); if (attributes == null) { if (LOG.isInfoEnabled()) { LOG.info("attributes missing for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } Attribute userNameAttr = attributes.get(userNameAttribute); if (userNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(userNameAttribute + " missing for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } String userFullName = (userEntry.getNameInNamespace()).toLowerCase(); String userName = (String) userNameAttr.get(); if (userName == null || userName.trim().isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info(userNameAttribute + " empty for entry " + userEntry.getNameInNamespace() + ", skipping sync"); } continue; } Attribute timeStampAttr = attributes.get("uSNChanged"); if (timeStampAttr != null) { String uSNChangedVal = (String) timeStampAttr.get(); long currentDeltaSyncTime = Long.parseLong(uSNChangedVal); LOG.info("uSNChangedVal = " + uSNChangedVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncUserTime) { highestdeltaSyncUserTime = currentDeltaSyncTime; } } else { timeStampAttr = attributes.get("modifytimestamp"); if (timeStampAttr != null) { String timeStampVal = (String) timeStampAttr.get(); Date parseDate = dateFormat.parse(timeStampVal); long currentDeltaSyncTime = parseDate.getTime(); LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime); if (currentDeltaSyncTime > highestdeltaSyncUserTime) { highestdeltaSyncUserTime = currentDeltaSyncTime; deltaSyncUserTimeStamp = timeStampVal; } } } if (!groupSearchFirstEnabled) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } //System.out.println("Adding user fullname = " + userFullName + " username = " + transformUserName); userNameMap.put(userFullName, transformUserName); Set<String> groups = new HashSet<String>(); // Get all the groups from the group name attribute of the user only when group search is not enabled. if (!groupSearchEnabled) { for (String useGroupNameAttribute : userGroupNameAttributeSet) { Attribute userGroupfAttribute = userEntry.getAttributes() .get(useGroupNameAttribute); if (userGroupfAttribute != null) { NamingEnumeration<?> groupEnum = userGroupfAttribute.getAll(); while (groupEnum.hasMore()) { String gName = getShortGroupName((String) groupEnum.next()); String transformGroupName = groupNameTransform(gName); groups.add(transformGroupName); } } } } List<String> groupList = new ArrayList<String>(groups); try { sink.addOrUpdateUser(transformUserName, groupList); } catch (Throwable t) { LOG.error("sink.addOrUpdateUserGroups failed with exception: " + t.getMessage() + ", for user: " + transformUserName + " and groups: " + groupList); } counter++; if (counter <= 2000) { if (LOG.isInfoEnabled()) { LOG.info("Updating user count: " + counter + ", userName: " + userName + ", groupList: " + groupList); } if (counter == 2000) { LOG.info( "===> 2000 user records have been synchronized so far. From now on, only a summary progress log will be written for every 100 users. To continue to see detailed log for every user, please enable Trace level logging. <==="); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Updating user count: " + counter + ", userName: " + userName + ", groupList: " + groupList); } else { if (counter % 100 == 0) { LOG.info("Synced " + counter + " users till now"); } } } } else { // If the user from the search result is present in the group user table, // then addorupdate user to ranger admin. LOG.debug("Chekcing if the user " + userFullName + " is part of the retrieved groups"); if (groupUserTable.containsColumn(userFullName) || groupUserTable.containsColumn(userName)) { String transformUserName = userNameTransform(userName); try { sink.addOrUpdateUser(transformUserName); } catch (Throwable t) { LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName); } userNameMap.put(userFullName, transformUserName); //Also update the username in the groupUserTable with the one from username attribute. Map<String, String> userMap = groupUserTable.column(userFullName); for (Map.Entry<String, String> entry : userMap.entrySet()) { LOG.debug("Updating groupUserTable " + entry.getValue() + " with: " + transformUserName + " for " + entry.getKey()); groupUserTable.put(entry.getKey(), userFullName, transformUserName); } } } } // Examine the paged results control response Control[] controls = ldapContext.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) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { LOG.debug(String.format("Fetched paged results round: %s", ++paged)); ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.getUsers() completed with user count: " + counter); } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.getUsers() failed with exception: " + t); LOG.info("LdapDeltaUserGroupBuilder.getUsers() user count: " + counter); } } if (deltaSyncUserTime < highestdeltaSyncUserTime) { // Incrementing highestdeltaSyncUserTime (for AD) in order to avoid search record repetition for next sync cycle. deltaSyncUserTime = highestdeltaSyncUserTime + 1; // Incrementing the highest timestamp value (for Openldap) with 1sec in order to avoid search record repetition for next sync cycle. deltaSyncUserTimeStamp = dateFormat.format(new Date(highestdeltaSyncUserTime + 60l)); } } finally { if (userSearchResultEnum != null) { userSearchResultEnum.close(); } if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Update the set of users belong to a LDAP role. * * @param roleName// w w w.j a v a 2 s. c o m * @param deletedUsers * @param newUsers */ @SuppressWarnings("deprecation") @Override public void doUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers) throws UserStoreException { String errorMessage = null; NamingEnumeration<SearchResult> groupSearchResults = null; LDAPRoleContext ctx = (LDAPRoleContext) createRoleContext(roleName); roleName = ctx.getRoleName(); String searchFilter = ctx.getSearchFilter(); if (isExistingLDAPRole(ctx)) { DirContext mainDirContext = this.connectionSource.getContext(); try { searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(roleName)); String membershipAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String[] returningAttributes = new String[] { membershipAttributeName }; String searchBase = ctx.getSearchBase(); groupSearchResults = searchInGroupBase(searchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; String groupName = null; while (groupSearchResults.hasMoreElements()) { resultedGroup = groupSearchResults.next(); groupName = resultedGroup.getName(); } // check whether update operations are going to violate non // empty role // restriction specified in user-mgt.xml by // checking whether all users are trying to be deleted // before updating LDAP. Attribute returnedMemberAttribute = resultedGroup.getAttributes().get(membershipAttributeName); if (!emptyRolesAllowed && newUsers.length - deletedUsers.length + returnedMemberAttribute.size() == 0) { errorMessage = "There should be at least one member in the role. " + "Hence can not delete all the members."; throw new UserStoreException(errorMessage); } else { List<String> newUserList = new ArrayList<String>(); List<String> deleteUserList = new ArrayList<String>(); if (newUsers != null && newUsers.length != 0) { String invalidUserList = ""; String existingUserList = ""; for (String newUser : newUsers) { if (StringUtils.isEmpty(newUser)) { continue; } String userNameDN = getNameInSpaceForUserName(newUser); if (userNameDN == null) { invalidUserList += newUser + " "; } else if (isUserInRole(userNameDN, resultedGroup)) { existingUserList += userNameDN + ","; } else { newUserList.add(userNameDN); } } if (!StringUtils.isEmpty(invalidUserList) || !StringUtils.isEmpty(existingUserList)) { errorMessage = (StringUtils.isEmpty(invalidUserList) ? "" : "'" + invalidUserList + "' not in the user store. ") + (StringUtils.isEmpty(existingUserList) ? "" : "'" + existingUserList + "' already belong to the role : " + roleName); throw new UserStoreException(errorMessage); } } if (deletedUsers != null && deletedUsers.length != 0) { String invalidUserList = ""; for (String deletedUser : deletedUsers) { if (StringUtils.isEmpty(deletedUser)) { continue; } String userNameDN = getNameInSpaceForUserName(deletedUser); if (userNameDN == null) { invalidUserList += deletedUser + ","; } else { deleteUserList.add(userNameDN); } } if (!StringUtils.isEmpty(invalidUserList)) { errorMessage = "'" + invalidUserList + "' not in the user store."; throw new UserStoreException(errorMessage); } } for (String userNameDN : newUserList) { modifyUserInRole(userNameDN, groupName, DirContext.ADD_ATTRIBUTE, searchBase); } for (String userNameDN : deleteUserList) { modifyUserInRole(userNameDN, groupName, DirContext.REMOVE_ATTRIBUTE, searchBase); // needs to clear authz cache for deleted users userRealm.getAuthorizationManager().clearUserAuthorization(userNameDN); } } } catch (NamingException e) { errorMessage = "Error occurred while modifying the user list of role: " + roleName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(groupSearchResults); JNDIUtil.closeContext(mainDirContext); } } else { errorMessage = "The role: " + roleName + " does not exist."; if (log.isDebugEnabled()) { log.debug(errorMessage); } throw new UserStoreException(errorMessage); } }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param sr/*from www . j a v a2 s . c om*/ * @param groupAttributeName * @return */ private List<String> parseSearchResult(SearchResult sr, String groupAttributeName) { List<String> list = new ArrayList<String>(); Attributes attrs = sr.getAttributes(); if (attrs != null) { try { NamingEnumeration ae = null; for (ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); if (groupAttributeName == null || groupAttributeName.equals(attr.getID())) { NamingEnumeration e = null; for (e = attr.getAll(); e.hasMore();) { String value = e.next().toString(); int begin = value.indexOf("=") + 1; int end = value.indexOf(","); if (begin > -1 && end > -1) { value = value.substring(begin, end); } list.add(value); } JNDIUtil.closeNamingEnumeration(e); } } JNDIUtil.closeNamingEnumeration(ae); } catch (NamingException e) { log.debug(e.getMessage(), e); } } return list; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * Returns the list of role names for the given search base and other * parameters// w w w. j a v a2s .c om * * @param searchTime * @param filter * @param maxItemLimit * @param searchFilter * @param roleNameProperty * @param searchBase * @param appendTenantDomain * @return * @throws UserStoreException */ protected List<String> getLDAPRoleNames(int searchTime, String filter, int maxItemLimit, String searchFilter, String roleNameProperty, String searchBase, boolean appendTenantDomain) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> roles = new ArrayList<String>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); searchCtls.setTimeLimit(searchTime); String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); // / search filter TODO StringBuffer finalFilter = new StringBuffer(); finalFilter.append("(&").append(searchFilter).append("(").append(roleNameProperty).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); if (debug) { log.debug("Listing roles. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString()); } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { dirContext = connectionSource.getContext(); answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); // append the domain if exist String domain = this.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(roleNameProperty); if (attr != null) { String name = (String) attr.get(); name = UserCoreUtil.addDomainToName(name, domain); if (appendTenantDomain) { String dn = sr.getNameInNamespace(); name = UserCoreUtil.addTenantDomainToEntry(name, getTenantDomainFromRoleDN(dn, name)); } roles.add(name); } } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString(); if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { Iterator<String> rolesIte = roles.iterator(); while (rolesIte.hasNext()) { log.debug("result: " + rolesIte.next()); } } return roles; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
public String[] getUserListFromProperties(String property, String value, String profileName) throws UserStoreException { boolean debug = log.isDebugEnabled(); String userAttributeSeparator = ","; String serviceNameAttribute = "sn"; List<String> values = new ArrayList<String>(); String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER); String userPropertyName = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); searchFilter = "(&" + searchFilter + "(" + property + "=" + escapeSpecialCharactersForFilterWithStarAsRegex(value) + "))"; DirContext dirContext = this.connectionSource.getContext(); NamingEnumeration<?> answer = null; NamingEnumeration<?> attrs = null; if (debug) {//from www . ja v a 2 s . c om log.debug("Listing users with Property: " + property + " SearchFilter: " + searchFilter); } String[] returnedAttributes = new String[] { userPropertyName, serviceNameAttribute }; try { answer = this.searchForUser(searchFilter, returnedAttributes, dirContext); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attributes = sr.getAttributes(); if (attributes != null) { Attribute attribute = attributes.get(userPropertyName); if (attribute != null) { StringBuffer attrBuffer = new StringBuffer(); for (attrs = attribute.getAll(); attrs.hasMore();) { String attr = (String) attrs.next(); if (attr != null && attr.trim().length() > 0) { String attrSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (attrSeparator != null && !attrSeparator.trim().isEmpty()) { userAttributeSeparator = attrSeparator; } attrBuffer.append(attr + userAttributeSeparator); if (debug) { log.debug(userPropertyName + " : " + attr); } } } String propertyValue = attrBuffer.toString(); // Length needs to be more than userAttributeSeparator.length() for a valid // attribute, since we // attach userAttributeSeparator. if (propertyValue != null && propertyValue.trim().length() > userAttributeSeparator.length()) { if (attributes.get(serviceNameAttribute).get() .equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) { continue; } propertyValue = propertyValue.substring(0, propertyValue.length() - userAttributeSeparator.length()); values.add(propertyValue); } } } } } catch (NamingException e) { String errorMessage = "Error occurred while getting user list from property : " + property + " & value : " + value + " & profile name : " + profileName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { // close the naming enumeration and free up resources JNDIUtil.closeNamingEnumeration(attrs); JNDIUtil.closeNamingEnumeration(answer); // close directory context JNDIUtil.closeContext(dirContext); } if (debug) { String[] results = values.toArray(new String[values.size()]); for (String result : results) { log.debug("result: " + result); } } return values.toArray(new String[values.size()]); }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * *///from w w w .j a v a2 s .c o m 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 = UserCoreConstants.MAX_USER_ROLE_LIST; int searchTime = UserCoreConstants.MAX_SEARCH_TIME; try { givenMax = Integer.parseInt( realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = UserCoreConstants.MAX_USER_ROLE_LIST; } try { searchTime = Integer.parseInt( realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = UserCoreConstants.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 serch. Please enter valid sequence."); } StringBuffer searchFilter = new StringBuffer( realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String serviceNameAttribute = "sn"; StringBuffer finalFilter = new StringBuffer(); // read the display name attribute - if provided String displayNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAtts = null; if (displayNameAttribute != null) { 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<String>(); try { dirContext = connectionSource.getContext(); // handle multiple search bases String[] searchBaseArray = searchBases.split("#"); for (String searchBase : searchBaseArray) { answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) 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 display name is provided, read that attribute */ Attribute displayName = null; if (displayNameAttribute != null) { displayName = sr.getAttributes().get(displayNameAttribute); if (debug) { log.debug(displayNameAttribute + " : " + displayName); } } if (attr != null) { String name = (String) attr.get(); String display = null; if (displayName != null) { display = (String) displayName.get(); } // append the domain if exist String domain = this.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); // get the name in the format of // domainName/userName|domainName/displayName name = UserCoreUtil.getCombinedName(domain, name, display); 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:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/*from www . j ava2 s .c om*/ */ public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames) throws UserStoreException { String userAttributeSeparator = ","; String userDN = null; // read list of patterns from user-mgt.xml String patterns = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN); if (patterns != null && !patterns.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Using User DN Patterns " + patterns); } if (patterns.contains(CommonConstants.XML_PATTERN_SEPERATOR)) { userDN = getNameInSpaceForUserName(userName); } else { userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName)); } } Map<String, String> values = new HashMap<>(); DirContext dirContext = this.connectionSource.getContext(); String userSearchFilter = userStoreProperties.get(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); NamingEnumeration<?> answer = null; NamingEnumeration<?> attrs = null; NamingEnumeration<?> allAttrs = null; try { if (userDN != null) { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (propertyNames[0].equals(CommonConstants.WILD_CARD_FILTER)) { propertyNames = null; } searchCtls.setReturningAttributes(propertyNames); try { answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } } else { answer = this.searchForUser(searchFilter, propertyNames, dirContext); } assert answer != null; while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attributes = sr.getAttributes(); if (attributes != null) { for (allAttrs = attributes.getAll(); allAttrs.hasMore();) { Attribute attribute = (Attribute) allAttrs.next(); if (attribute != null) { StringBuilder attrBuffer = new StringBuilder(); for (attrs = attribute.getAll(); attrs.hasMore();) { Object attObject = attrs.next(); String attr = null; if (attObject instanceof String) { attr = (String) attObject; } else if (attObject instanceof byte[]) { //if the attribute type is binary base64 encoded string will be returned attr = new String(Base64.encodeBase64((byte[]) attObject), "UTF-8"); } if (attr != null && attr.trim().length() > 0) { String attrSeparator = userStoreProperties.get(MULTI_ATTRIBUTE_SEPARATOR); if (attrSeparator != null && !attrSeparator.trim().isEmpty()) { userAttributeSeparator = attrSeparator; } attrBuffer.append(attr).append(userAttributeSeparator); } String value = attrBuffer.toString(); /* * Length needs to be more than userAttributeSeparator.length() for a valid * attribute, since we * attach userAttributeSeparator */ if (value.trim().length() > userAttributeSeparator.length()) { value = value.substring(0, value.length() - userAttributeSeparator.length()); values.put(attribute.getID(), value); } } } } } } } catch (NamingException e) { String errorMessage = "Error occurred while getting user property values for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } catch (UnsupportedEncodingException e) { String errorMessage = "Error occurred while Base64 encoding property values for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { // close the naming enumeration and free up resource JNDIUtil.closeNamingEnumeration(attrs); JNDIUtil.closeNamingEnumeration(answer); // close directory context JNDIUtil.closeContext(dirContext); } return values; }