List of usage examples for javax.naming.directory SearchControls setSearchScope
public void setSearchScope(int scope)
From source file:com.wfp.utils.LDAPUtils.java
public static String getUserImageAsString(String uid) { String base64String = null; if (uid != null && uid != "") { // Specify the attributes to return String searchFilter = "(&" + FILTER_LDAP_USERS + "((uid=" + uid + ")))"; String searchBase = LDAP_FILTER_URL + "uid=" + uid + "," + LDAP_BASE; String returnedAtts[] = { "" + PROPERTY_IMAGE }; // Specify the search scope SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); // Search for objects using the filter try {/*from www . j a v a 2 s. c o m*/ NamingEnumeration results = getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get(PROPERTY_IMAGE); if (attr != null) base64String = new String( org.apache.commons.codec.binary.Base64.encodeBase64((byte[]) attr.get())); } } catch (NamingException e) { Logger.error(" Error occured while fetching user image 1334: getUserImageBytes(String uid):[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } return base64String; }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * Queries Active Directory for attributes defined within the bag. * The LDAP_ACCOUNT_NAME field must be populated prior to invoking * this method. Any site specific fields can be assigned to the * bag will be included in the attribute query. * * @param aUserBag Active Directory user fields. * * @throws NSException Thrown if an LDAP naming exception is occurs. *//*from w w w.j ava2s . c o m*/ public void loadUserByAccountName(DataBag aUserBag) throws NSException { byte[] objectSid; Attribute responseAttribute; String fieldName, fieldValue; Attributes responseAttributes; Logger appLogger = mAppMgr.getLogger(this, "loadUserByAccountName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; String accountName = null; int attrCount = aUserBag.count(); String[] ldapAttrNames = new String[attrCount]; for (DataField dataField : aUserBag.getFields()) { fieldName = dataField.getName(); if (fieldName.equals(LDAP_ACCOUNT_NAME)) accountName = dataField.getValueAsString(); ldapAttrNames[field++] = fieldName; } searchControls.setReturningAttributes(ldapAttrNames); if (accountName == null) { String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME); appLogger.error(msgStr); throw new NSException(msgStr); } String userSearchBaseDN = getPropertyValue("user_searchbasedn", null); String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_ACCOUNT_NAME, accountName); try { NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter, searchControls); if ((searchResponse != null) && (searchResponse.hasMore())) { responseAttributes = ((SearchResult) searchResponse.next()).getAttributes(); for (DataField complexField : aUserBag.getFields()) { fieldName = complexField.getName(); responseAttribute = responseAttributes.get(fieldName); if (responseAttribute != null) { if (fieldName.equals(LDAP_OBJECT_SID)) { objectSid = (byte[]) responseAttribute.get(); fieldValue = objectSidToString2(objectSid); } else fieldValue = (String) responseAttribute.get(); if (StringUtils.isNotEmpty(fieldValue)) complexField.setValue(fieldValue); } } searchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * Queries Active Directory for attributes defined within the bag. * The LDAP_COMMON_NAME field must be populated prior to invoking * this method. Any site specific fields can be assigned to the * bag will be included in the attribute query. * * @param aUserBag Active Directory user fields. * * @throws NSException Thrown if an LDAP naming exception is occurs. *///from w ww. jav a 2s . c o m public void loadUserByCommonName(DataBag aUserBag) throws NSException { byte[] objectSid; Attribute responseAttribute; String fieldName, fieldValue; Attributes responseAttributes; Logger appLogger = mAppMgr.getLogger(this, "loadUserByCommonName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; String commonName = null; int attrCount = aUserBag.count(); String[] ldapAttrNames = new String[attrCount]; for (DataField complexField : aUserBag.getFields()) { fieldName = complexField.getName(); if (fieldName.equals(LDAP_COMMON_NAME)) commonName = complexField.getValueAsString(); ldapAttrNames[field++] = fieldName; } searchControls.setReturningAttributes(ldapAttrNames); if (commonName == null) { String msgStr = String.format("LDAP common name '%s' is unassigned.", LDAP_COMMON_NAME); appLogger.error(msgStr); throw new NSException(msgStr); } String userSearchBaseDN = getPropertyValue("user_searchbasedn", null); String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_COMMON_NAME, commonName); try { NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter, searchControls); if ((searchResponse != null) && (searchResponse.hasMore())) { responseAttributes = ((SearchResult) searchResponse.next()).getAttributes(); for (DataField complexField : aUserBag.getFields()) { fieldName = complexField.getName(); responseAttribute = responseAttributes.get(fieldName); if (responseAttribute != null) { if (fieldName.equals(LDAP_OBJECT_SID)) { objectSid = (byte[]) responseAttribute.get(); fieldValue = objectSidToString2(objectSid); } else fieldValue = (String) responseAttribute.get(); if (StringUtils.isNotEmpty(fieldValue)) complexField.setValue(fieldValue); } } searchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * Queries Active Directory for attributes defined within the bag. * The LDAP_ACCOUNT_NAME field must be populated prior to invoking * this method. Any site specific fields can be assigned to the * bag will be included in the attribute query. * * @param aGroupBag Active Directory group fields. * * @throws NSException Thrown if an LDAP naming exception is occurs. *//*from w w w. j a v a 2 s. c o m*/ public void loadGroupByAccountName(DataBag aGroupBag) throws NSException { byte[] objectSid; Attribute responseAttribute; String fieldName, fieldValue; Attributes responseAttributes; Logger appLogger = mAppMgr.getLogger(this, "loadGroupByAccountName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; String accountName = null; int attrCount = aGroupBag.count(); String[] ldapAttrNames = new String[attrCount]; for (DataField complexField : aGroupBag.getFields()) { fieldName = complexField.getName(); if (fieldName.equals(LDAP_ACCOUNT_NAME)) accountName = complexField.getValueAsString(); ldapAttrNames[field++] = fieldName; } searchControls.setReturningAttributes(ldapAttrNames); if (accountName == null) { String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME); appLogger.error(msgStr); throw new NSException(msgStr); } String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null); String groupSearchFilter = String.format("(&(objectClass=group)(%s=%s))", LDAP_ACCOUNT_NAME, accountName); try { NamingEnumeration<?> searchResponse = mLdapContext.search(groupSearchBaseDN, groupSearchFilter, searchControls); if ((searchResponse != null) && (searchResponse.hasMore())) { responseAttributes = ((SearchResult) searchResponse.next()).getAttributes(); for (DataField complexField : aGroupBag.getFields()) { fieldName = complexField.getName(); responseAttribute = responseAttributes.get(fieldName); if (responseAttribute != null) { if (fieldName.equals(LDAP_OBJECT_SID)) { objectSid = (byte[]) responseAttribute.get(); fieldValue = objectSidToString2(objectSid); } else fieldValue = (String) responseAttribute.get(); if (StringUtils.isNotEmpty(fieldValue)) complexField.setValue(fieldValue); } } searchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", groupSearchFilter, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups//w w w.j a va 2 s.c o m * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap, Map<String, String> groups) throws Exception { HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { LOGGER.debug( "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER); groupMemberAttributName = DEFAULT_GROUP_MEMBER; } LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword); if (baseContext == null) { LOGGER.warn("Context is null for baseURL " + baseURL); return ldapGroupsMap; } for (Map.Entry<String, String> groupEntry : groups.entrySet()) { String groupName = groupEntry.getKey(); String groupDN = groupEntry.getValue(); int index = groupDN.indexOf(","); if (index != -1) { String searchPart = groupDN.substring(0, index); String searchStr = "(" + searchPart + ")"; String parentDNPart = groupDN.substring(index + 1); LdapContext context = (LdapContext) baseContext.lookup(parentDNPart); if (context == null) { LOGGER.warn("Context is null after lookup for " + parentDNPart); continue; } int recordCount = 0; 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 do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls); /* * for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); continue; } TPersonBean personBean = new TPersonBean(); try { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } LOGGER.debug("Member found: " + memberSearchResult); memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed group " + groupName); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++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 { context.close(); } } } return ldapGroupsMap; }
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 {/* ww w . ja v a2 s . c o 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:com.nridge.core.app.ldap.ADQuery.java
/** * This method will perform multiple queries into Active Directory * in order to resolve what groups a user is a member of. The * logic will identify nested groups and add them to the table. * <p>//w ww . j a v a2 s.c o m * The LDAP_ACCOUNT_NAME field must be populated in the user bag * prior to invoking this method. Any site specific fields can be * assigned to the user bag will be included in the attribute query. * </p> * <p> * Any site specific fields can be assigned to the group bag will * be included in the attribute query. * </p> * * @param aUserBag Active Directory user attributes. * @param aGroupBag Active Directory group attributes. * * @return Table of groups that the user is a member of. * * @throws NSException Thrown if an LDAP naming exception is occurs. */ @SuppressWarnings("StringConcatenationInsideStringBufferAppend") public DataTable loadUserGroupsByAccountName(DataBag aUserBag, DataBag aGroupBag) throws NSException { byte[] objectSid; DataBag groupBag; Attribute responseAttribute; String fieldName, fieldValue; Logger appLogger = mAppMgr.getLogger(this, "loadUserGroupsByAccountName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } // First, we will populate our user bag so that we can obtain the distinguished name. loadUserByAccountName(aUserBag); // Now we will use the DN to find all of the groups the user is a member of. String distinguishedName = aUserBag.getValueAsString(LDAP_DISTINGUISHED_NAME); if (StringUtils.isEmpty(distinguishedName)) distinguishedName = getPropertyValue("user_searchbasedn", null); // Next, we will initialize our group membership table. DataTable memberTable = new DataTable(aUserBag); memberTable.setName(String.format("%s Group Membership", aUserBag.getValueAsString(LDAP_COMMON_NAME))); // The next logic section will query AD for all of the groups the user is a member // of. Because we are following tokenGroups, we will gain access to nested groups. String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null); SearchControls userSearchControls = new SearchControls(); userSearchControls.setSearchScope(SearchControls.OBJECT_SCOPE); StringBuffer groupsSearchFilter = null; String ldapAttrNames[] = { "tokenGroups" }; userSearchControls.setReturningAttributes(ldapAttrNames); try { NamingEnumeration<?> userSearchResponse = mLdapContext.search(distinguishedName, "(objectClass=user)", userSearchControls); if ((userSearchResponse != null) && (userSearchResponse.hasMoreElements())) { groupsSearchFilter = new StringBuffer(); groupsSearchFilter.append("(|"); SearchResult userSearchResult = (SearchResult) userSearchResponse.next(); Attributes userResultAttributes = userSearchResult.getAttributes(); if (userResultAttributes != null) { try { for (NamingEnumeration<?> searchResultAttributesAll = userResultAttributes .getAll(); searchResultAttributesAll.hasMore();) { Attribute attr = (Attribute) searchResultAttributesAll.next(); for (NamingEnumeration<?> namingEnumeration = attr.getAll(); namingEnumeration .hasMore();) { objectSid = (byte[]) namingEnumeration.next(); groupsSearchFilter.append("(objectSid=" + objectSidToString2(objectSid) + ")"); } groupsSearchFilter.append(")"); } } catch (NamingException e) { String msgStr = String.format("LDAP Listing Member Exception: %s", e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } } userSearchResponse.close(); // Finally, we will query each group in the search filter and add it to the table. SearchControls groupSearchControls = new SearchControls(); groupSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; int attrCount = aGroupBag.count(); String[] groupsReturnedAtts = new String[attrCount]; for (DataField complexField : aGroupBag.getFields()) { fieldName = complexField.getName(); groupsReturnedAtts[field++] = fieldName; } groupSearchControls.setReturningAttributes(groupsReturnedAtts); NamingEnumeration<?> groupSearchResponse = mLdapContext.search(groupSearchBaseDN, groupsSearchFilter.toString(), groupSearchControls); while ((groupSearchResponse != null) && (groupSearchResponse.hasMoreElements())) { SearchResult groupSearchResult = (SearchResult) groupSearchResponse.next(); Attributes groupResultAttributes = groupSearchResult.getAttributes(); if (groupResultAttributes != null) { groupBag = new DataBag(aGroupBag); for (DataField complexField : groupBag.getFields()) { fieldName = complexField.getName(); responseAttribute = groupResultAttributes.get(fieldName); if (responseAttribute != null) { if (fieldName.equals(LDAP_OBJECT_SID)) { objectSid = (byte[]) responseAttribute.get(); fieldValue = objectSidToString2(objectSid); } else fieldValue = (String) responseAttribute.get(); if (StringUtils.isNotEmpty(fieldValue)) complexField.setValue(fieldValue); } } memberTable.addRow(groupBag); } } if (groupSearchResponse != null) groupSearchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", distinguishedName, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return memberTable; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups//w w w. j a va2s. co m * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean, String baseDnGroup, String ldapFilterGroups, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap) throws Exception { if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) { ldapFilterGroups = "(" + groupAttributeName + "=*)"; } String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword); HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); if (context == null) { LOGGER.warn("Context is null"); return ldapGroupsMap; } int recordCount = 0; SearchControls ctls = null; String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { groupMemberAttributName = DEFAULT_GROUP_MEMBER; } 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 do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); return null; } TPersonBean personBean = new TPersonBean(); try { Attribute groupNameAttribute = attributes.get(groupAttributeName); if (groupNameAttribute != null) { String groupName = (String) groupNameAttribute.get(); LOGGER.debug("Groupname: " + groupName); if (groupName == null || "".equals(groupName)) { LOGGER.info("No value for group name attribute " + groupAttributeName); return null; } else { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); } Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName() + " " + personBean.getLastName() + ")"); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++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 { context.close(); } return ldapGroupsMap; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets all persons for a group/*from w ww. j a v a 2s . c om*/ * * @param groups * @param siteBean * @param filter * @return * @throws Exception */ static List<TPersonBean> getAllLdapUsersDescendants(String providerUrl, String bindDN, String bindPassword, String loginAttributeName, String filter) throws Exception { List<TPersonBean> personBeans = new ArrayList<TPersonBean>(); if (filter == null || "".equals(filter) || "*".equals(filter)) { filter = loginAttributeName + "=*"; } int recordCount = 0; SearchControls ctls = null; LdapContext ctx = null; try { ctx = getInitialContext(providerUrl, bindDN, bindPassword); if (ctx == null) { return personBeans; } // Activate paged results int pageSize = 5; // TODO replace for GROOVY ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; String searchStr = "(" + filter + ")"; // 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 personBeans; } String firstNameAttributeName = ldapMap.get("firstName"); String lastNameAttributName = ldapMap.get("lastName"); String emailAttributeName = ldapMap.get("email"); String phoneAttributName = ldapMap.get("phone"); byte[] cookie = null; // TODO replace for GROOVY cookie = new byte[] {}; // cookie = [] as byte[]; while (cookie != null) { NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { personBeans.add(personBean); ++recordCount; } } // Examine the paged results control response Control[] controls = ctx.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 // TODO replace for GROOVY ctx.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } } 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 (ctx != null) { ctx.close(); } } return personBeans; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
public NamingEnumeration<SearchResult> query(DirContext ctx, String pBaseDn, String filter, String[] attributeFilter, Integer pScope) throws NamingException, IllegalAccessException { NamingEnumeration<SearchResult> vResult; SearchControls sControl = new SearchControls(); if (attributeFilter != null) { sControl.setReturningAttributes(attributeFilter); }//w w w. ja v a2 s. co m int vScope = SearchControls.SUBTREE_SCOPE; if (pScope != null) { vScope = pScope.intValue(); } sControl.setSearchScope(vScope); vResult = ctx.search(((pBaseDn != null) && (pBaseDn.length() > 0) ? pBaseDn : LDAPConnector.getSingletonInstance().getBaseDn()), filter, sControl); return vResult; }