List of usage examples for javax.naming.ldap LdapContext search
public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException;
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will query the LDAP for the supplied dn, matching attributes and * return attributes. This method will always perform a one level search. The * resulting <code>Iterator</code> is a deep copy of the original search * results. If matchAttrs is empty or null then all objects in the target * context are returned. If retAttrs is null then all attributes will be * returned. If retAttrs is an empty array then no attributes will be * returned. See {@link javax.naming.DirContext#search(String, Attributes, * String[])}./*www .j a va2 s . c o m*/ * * @param dn <code>String</code> name to search in * @param matchAttrs <code>Attributes</code> attributes to match * @param retAttrs <code>String[]</code> attributes to return * @param handler <code>SearchResultHandler[]</code> to post process results * * @return <code>Iterator</code> - of LDAP search results * * @throws NamingException if the LDAP returns an error */ protected Iterator<SearchResult> searchAttributes(final String dn, final Attributes matchAttrs, final String[] retAttrs, final SearchResultHandler... handler) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("One level search with the following parameters:"); this.logger.debug(" dn = " + dn); this.logger.debug(" matchAttrs = " + matchAttrs); this.logger.debug(" retAttrs = " + (retAttrs == null ? "all attributes" : Arrays.toString(retAttrs))); this.logger.debug(" handler = " + Arrays.toString(handler)); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<SearchResult> results = null; LdapContext ctx = null; NamingEnumeration<SearchResult> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); en = ctx.search(dn, matchAttrs, retAttrs); if (handler != null && handler.length > 0) { final SearchCriteria sc = new SearchCriteria(); if (ctx != null && !"".equals(ctx.getNameInNamespace())) { sc.setDn(ctx.getNameInNamespace()); } else { sc.setDn(dn); } sc.setMatchAttrs(matchAttrs); sc.setReturnAttrs(retAttrs); if (handler != null && handler.length > 0) { for (int j = 0; j < handler.length; j++) { if (j == 0) { results = handler[j].process(sc, en, this.config.getHandlerIgnoreExceptions()); } else { results = handler[j].process(sc, results); } } } } else { results = SR_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); } break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }
From source file:com.aurel.track.util.LdapUtil.java
static TPersonBean getLdapUser(String providerUrl, String bindDN, String bindPassword, String loginAttributeName, String searchStr) throws Exception { LdapContext ctx = null; try {// w w w . j a va2 s. co m ctx = getInitialContext(providerUrl, bindDN, bindPassword); if (ctx == null) { LOGGER.warn("The context is null"); } // Control the search SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // 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); NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); return getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); } } catch (NamingException e) { LOGGER.warn( "Searching from " + providerUrl + " by filter " + searchStr + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } finally { if (ctx != null) { ctx.close(); } } return null; }
From source file:com.wfp.utils.LDAPUtils.java
/** * Overloaded method used to search the ldap based on the search constraints, search filter & search base * @param attrs// w w w .j a va 2 s . c o m * @param searchFilter * @param searchBase * @return * @throws NamingException */ @SuppressWarnings("unchecked") public static NamingEnumeration getSearchResults(String[] attrs, String searchFilter, String searchBase) { LdapContext ldapCtx = null; try { try { ldapCtx = getLDAPContext(); } catch (NamingException e) { Logger.error("Error occured while creating the connection to LDAP[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } if (ldapCtx == null) { return null; } SearchControls searchCtls = getSimpleSearchControls(attrs); // Search for objects using the filter try { return ldapCtx.search(searchBase, searchFilter, searchCtls); } catch (NamingException e) { Logger.error( "Error occured while searching results :288: getSearchResults(String[] attrs, String searchFilter, String searchBase): [" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } finally { if (ldapCtx != null) { try { ldapCtx.close(); } catch (NamingException e) { Logger.error("Error occured while closing connection to LDAP [" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } } return null; }
From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java
/** * displayName and mail are returned always, the map allows us to support * getting arbitrary properties in the future, hopefully *//* ww w .j av a 2 s . c om*/ public Map<String, String> bind(String loginName, String password) throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); LdapContext ctx = null; if (activeDirectoryDomain != null) { // we are using Active Directory Control[] controls = new Control[] { control }; ctx = new InitialLdapContext(env, controls); logger.debug("Active Directory LDAP context initialized"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); // javax.naming.AuthenticationException ctx.reconnect(controls); logger.debug("Active Directory LDAP bind successful"); } else { // standard LDAP env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase); env.put(Context.SECURITY_CREDENTIALS, password); ctx = new InitialLdapContext(env, null); logger.debug("Standard LDAP bind successful"); } SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(returningAttributes); NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc); while (results.hasMoreElements()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); logger.debug("attributes: " + attrs); Map<String, String> map = new HashMap<String, String>(returningAttributes.length); for (String key : returningAttributes) { Attribute attr = attrs.get(key); if (attr != null) { map.put(key, (String) attr.get()); } } return map; // there should be only one anyway } // if we reached here, there was no search result throw new Exception("no results returned from ldap"); }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Obtain the DistinguishedName for a given user logon name. *@param ctx is the ldap context to use./* www .j a va2s . c om*/ *@param userName (Domain Logon Name) is the user name or identifier. *@param searchBase (Full Domain Name for the search ie: DC=qa-ad-76,DC=metacarta,DC=com) *@return DistinguishedName for given domain user logon name. * (Should throws an exception if user is not found.) */ protected String getDistinguishedName(LdapContext ctx, String userName, String searchBase, String userACLsUsername) throws ManifoldCFException { String returnedAtts[] = { "distinguishedName" }; String searchFilter = "(&(objectClass=user)(" + userACLsUsername + "=" + userName + "))"; SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(returnedAtts); //Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); try { NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { String dn = attrs.get("distinguishedName").get().toString(); return dn; } } return null; } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups/*from w ww .j ava2 s . com*/ * * @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:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups//www .java2 s.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:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Get the AD-derived access tokens for a user and domain */ protected List<String> getADTokens(String userPart, String domainPart, String userName) throws NameNotFoundException, NamingException, ManifoldCFException { // Now, look through the rules for the matching domain controller String domainController = null; for (DCRule rule : dCRules) { String suffix = rule.getSuffix(); if (suffix.length() == 0 || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT)) && (suffix.length() == domainPart.length() || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) { domainController = rule.getDomainControllerName(); break; }//w w w . j a v a2 s . c o m } if (domainController == null) // No AD user return null; // Look up connection parameters DCConnectionParameters dcParams = dCConnectionParameters.get(domainController); if (dcParams == null) // No AD user return null; // Use the complete fqn if the field is the "userPrincipalName" String userBase; String userACLsUsername = dcParams.getUserACLsUsername(); if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) { userBase = userName; } else { userBase = userPart; } //Build the DN searchBase from domain part StringBuilder domainsb = new StringBuilder(); int j = 0; while (true) { if (j > 0) domainsb.append(","); int k = domainPart.indexOf(".", j); if (k == -1) { domainsb.append("DC=").append(ldapEscape(domainPart.substring(j))); break; } domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k))); j = k + 1; } // Establish a session with the selected domain controller LdapContext ctx = createDCSession(domainController); //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com") String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername); if (searchBase == null) return null; //specify the LDAP search filter String searchFilter = "(objectClass=user)"; //Create the search controls for finding the access tokens SearchControls searchCtls = new SearchControls(); //Specify the search scope, must be base level search for tokenGroups searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE); //Specify the attributes to return String returnedAtts[] = { "tokenGroups", "objectSid" }; searchCtls.setReturningAttributes(returnedAtts); //Search for tokens. Since every user *must* have a SID, the "no user" detection should be safe. NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); List<String> theGroups = new ArrayList<String>(); String userToken = userTokenFromLoginName(domainPart + "\\" + userPart); if (userToken != null) theGroups.add(userToken); //Loop through the search results while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); //the sr.GetName should be null, as it is relative to the base object Attributes attrs = sr.getAttributes(); if (attrs != null) { try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore();) { String sid = sid2String((byte[]) e.next()); String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid) : groupTokenFromSID(sid); theGroups.add(token); } } } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } } } if (theGroups.size() == 0) return null; // User is in AD, so add the 'everyone' group theGroups.add(everyoneGroup()); return theGroups; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets all persons for a group/*from www . ja v a 2 s . c o m*/ * * @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: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. * /*from ww w .j a v a2s. 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; }