List of usage examples for javax.naming.directory SearchControls setCountLimit
public void setCountLimit(long limit)
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets all persons for a group//from www. j av a2 s .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:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
@SuppressWarnings("unchecked") private SearchResult findUser(String username) throws NamingException, LoginException { SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setDerefLinkFlag(true);//from w w w .ja v a 2 s .com ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = OBJECT_CLASS_FILTER; debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn); Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username }; NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls); debug("Found user?: " + results.hasMoreElements()); if (!results.hasMoreElements()) { throw new LoginException("User not found."); } return (SearchResult) results.nextElement(); }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
/** * attempts to get the users credentials from the users context * <p/>//from ww w . ja va 2 s . c o m * NOTE: this is not an user authenticated operation * * @param username * @return * @throws LoginException */ @SuppressWarnings("unchecked") private String getUserCredentials(String username) throws LoginException { String ldapCredential = null; SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); try { Object[] filterArguments = { _userObjectClass, _userIdAttribute, username }; NamingEnumeration results = _rootContext.search(_userBaseDn, OBJECT_CLASS_FILTER, filterArguments, ctls); debug("Found user?: " + results.hasMoreElements()); if (!results.hasMoreElements()) { throw new LoginException("User not found."); } SearchResult result = findUser(username); Attributes attributes = result.getAttributes(); setDemographicAttributes(attributes); Attribute attribute = attributes.get(_userPasswordAttribute); if (attribute != null) { try { byte[] value = (byte[]) attribute.get(); ldapCredential = new String(value); } catch (NamingException e) { LOG.info("no password available under attribute: " + _userPasswordAttribute); } } } catch (NamingException e) { throw new LoginException("Root context binding failure."); } debug("user cred is present: " + (ldapCredential != null)); return ldapCredential; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildUserSearcher(final String query) { LOGGER.debug("Building user searcher for query {}", query); final SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); userSearchCtls.setReturningAttributes(this.userKeys.getFirst()); // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control userSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0); return (ctx) -> { try {//from w w w . j ava 2s. co m final NamingEnumeration<SearchResult> results = ctx.search(this.userSearchBase, query, userSearchCtls); return results; } catch (final NamingException e) { throw new AlfrescoRuntimeException("Failed to import people.", e); } }; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildGroupSearcher(final String query) { LOGGER.debug("Building group searcher for query {}", query); final SearchControls groupSearchCtls = new SearchControls(); groupSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); groupSearchCtls.setReturningAttributes(this.groupKeys.getFirst()); // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control groupSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0); return (ctx) -> { try {//from ww w. j a v a 2 s . c o m final NamingEnumeration<SearchResult> results = ctx.search(this.groupSearchBase, query, groupSearchCtls); return results; } catch (final NamingException e) { throw new AlfrescoRuntimeException("Failed to import groups.", e); } }; }
From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java
/** * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'. * The user repository must be queried for this because the password is never retrieved from the repository * and the User object does not contain it. * //from w w w. j a va 2 s . c om */ public boolean isPasswordStored(String userId) throws RepositoryException { if (StringUtils.isBlank(userId)) { logger.debug("Insufficient data for getting user info."); throw new IllegalArgumentException(); } String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))"; final String PASSWD_ATTR_NAME = "userPassword"; boolean passwordStored = false; SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ctls.setCountLimit(1); ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME }); try { NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls); while (resultEnum.hasMoreElements()) { SearchResult result = resultEnum.next(); Attributes attrs = result.getAttributes(); if (attrs.get(PASSWD_ATTR_NAME) != null) passwordStored = true; } } catch (NamingException e) { throw new RepositoryException(e); } return passwordStored; }
From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java
/** * {@inheritDoc}//w w w. j a v a2s . com */ public Map<String, String> findByCommonNameStub(String stub, long maxCount) throws RepositoryException { Map<String, String> idNameMap = new LinkedHashMap<String, String>(); String text = censorHumanoidSearchPhrase(stub); String filter = "(&(objectClass=" + getObjectClassName() + ")(cn=" + text + "*))"; SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ctls.setCountLimit(maxCount); ctls.setReturningAttributes(new String[] { "cn", "uid" }); try { NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls); while (resultEnum.hasMoreElements()) { SearchResult result = resultEnum.next(); Attributes attrs = result.getAttributes(); idNameMap.put((String) attrs.get("uid").get(), (String) attrs.get("cn").get()); } } catch (NamingException e) { throw new RepositoryException(e); } return idNameMap; }
From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportDsmlRunnable.java
/** * Returns the {@link SearchControls} object associated with the request. * * @param request/*from w w w. jav a 2 s .com*/ * the search request * @return * the associated {@link SearchControls} object */ private SearchControls getSearchControls(SearchRequest request) { SearchControls controls = new SearchControls(); // Scope switch (request.getScope()) { case OBJECT: controls.setSearchScope(SearchControls.OBJECT_SCOPE); break; case ONELEVEL: controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); break; case SUBTREE: controls.setSearchScope(SearchControls.SUBTREE_SCOPE); break; default: controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); } // Returning attributes List<String> returningAttributes = new ArrayList<String>(); for (String attribute : request.getAttributes()) { returningAttributes.add(attribute); } // If the returning attributes are empty, we need to return the user attributes // [Cf. RFC 2251 - "There are two special values which may be used: an empty // list with no attributes, and the attribute description string '*'. Both of // these signify that all user attributes are to be returned."] if (returningAttributes.size() == 0) { returningAttributes.add("*"); //$NON-NLS-1$ } controls.setReturningAttributes(returningAttributes.toArray(new String[0])); // Size Limit controls.setCountLimit(request.getSizeLimit()); // Time Limit controls.setTimeLimit(request.getTimeLimit()); return controls; }
From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java
/** * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass} * and builds {@link User} based on search result. * * @param name//from w w w . jav a2s. c o m * The userId which should be value of the field {@link #userIdAttribute} * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the * userId of this user and ldap connection information with which * the user was searched. Return null if such a user was not found. * @throws NamingException * Propagated by the underlying LDAP communication layer. */ private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { userIdAttribute }); sc.setCountLimit(1); StringBuilder builderFilter = new StringBuilder("(&("); builderFilter.append(userIdAttribute).append("=").append(name).append(")").append("(objectClass=") .append(userObjectClass).append(")"); if (StringUtils.isNotEmpty(filter)) { builderFilter.append(filter).append(")"); } else { builderFilter.append(")"); } NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, builderFilter.toString(), sc); if (!sr.hasMore()) return null; SearchResult r = sr.next(); Attribute userName = r.getAttributes().get(userIdAttribute); if (!restriction.isActivated() || userInGroupsMembershipList(r.getNameInNamespace(), restriction.getGroupMembershipLists(ldapContext))) return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapContext); return null; }
From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java
/** Function to extract users from LDAP. */ private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) { List<String> userList = new ArrayList<>(); String userDnTemplate = r.getUserDnTemplate(); String userDn[] = userDnTemplate.split(",", 2); String userDnPrefix = userDn[0].split("=")[0]; String userDnSuffix = userDn[1]; JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory(); try {/* w w w.ja v a 2s . c o m*/ LdapContext ctx = cf.getSystemLdapContext(); SearchControls constraints = new SearchControls(); constraints.setCountLimit(numUsersToFetch); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = { userDnPrefix }; constraints.setReturningAttributes(attrIDs); NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints); while (result.hasMore()) { Attributes attrs = ((SearchResult) result.next()).getAttributes(); if (attrs.get(userDnPrefix) != null) { String currentUser = attrs.get(userDnPrefix).toString(); userList.add(currentUser.split(":")[1].trim()); } } } catch (Exception e) { LOGGER.error("Error retrieving User list from Ldap Realm", e); } LOGGER.info("UserList: " + userList); return userList; }