Example usage for javax.naming.directory SearchControls setCountLimit

List of usage examples for javax.naming.directory SearchControls setCountLimit

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls setCountLimit.

Prototype

public void setCountLimit(long limit) 

Source Link

Document

Sets the maximum number of entries to be returned as a result of the search.

Usage

From source file:SearchCountLimit.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {//  w ww  . j  a  va2 s . c  o  m
        // Create initial context
        DirContext ctx = new InitialDirContext(env);

        // Set search controls to limit count to 'expected'
        SearchControls ctls = new SearchControls();
        ctls.setCountLimit(expected);

        // Search for objects with those matching attributes
        NamingEnumeration answer = ctx.search("ou=People", "(sn=M*)", ctls);

        // Print the answer
        printSearchEnumeration(answer);

        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:org.apereo.services.persondir.support.ldap.LdaptivePersonAttributeDaoTest.java

public void testVerifyGetPerson() throws Exception {

    final String[] urls = ((LdapContextSource) this.getContextSource()).getUrls();
    final DefaultConnectionFactory df = new DefaultConnectionFactory(urls[0]);
    final BlockingConnectionPool cp = new BlockingConnectionPool(df);
    cp.initialize();//from  w  w w . j a  v  a 2  s  .co  m
    final PooledConnectionFactory factory = new PooledConnectionFactory(cp);

    final Map<String, String> map = new HashMap<>();
    map.put("cn", "commonName");
    map.put("mail", "displayName");
    map.put("givenName", "givenName");

    final SearchControls ctrs = new SearchControls();
    ctrs.setSearchScope(1);
    ctrs.setCountLimit(2);

    final LdaptivePersonAttributeDao dao = new LdaptivePersonAttributeDao();
    dao.setConnectionFactory(factory);
    dao.setBaseDN(getBaseDn());
    dao.setSearchControls(ctrs);
    dao.setSearchFilter("uid={0}");
    dao.setResultAttributeMapping(map);

    IPersonAttributes person = dao.getPerson("edalquist");
    assertTrue(person.getAttributes().size() > 0);
    assertNotNull(person.getAttributeValue("commonName"));
    assertNotNull(person.getAttributeValue("displayName"));
    assertNotNull(person.getAttributeValue("givenName"));

    dao.setSearchFilter("uid={user}");
    person = dao.getPerson("edalquist");
    assertTrue(person.getAttributes().size() > 0);
    assertNotNull(person.getAttributeValue("commonName"));
    assertNotNull(person.getAttributeValue("displayName"));
    assertNotNull(person.getAttributeValue("givenName"));
}

From source file:org.apache.archiva.redback.authentication.ldap.LdapBindAuthenticator.java

public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException {
    PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s;

    if (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ENABLED)
            || (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ALLOW_EMPTY_PASSWORDS, false)
                    && StringUtils.isEmpty(source.getPassword()))) {
        return new AuthenticationResult(false, source.getUsername(), null);
    }/*from w  w  w. j  a  va  2s.c om*/

    SearchControls ctls = new SearchControls();

    ctls.setCountLimit(1);

    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")"
            + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute()
            + "=" + source.getUsername() + "))";

    log.debug("Searching for users with filter: '{}' from base dn: {}", filter, mapper.getUserBaseDn());

    LdapConnection ldapConnection = null;
    LdapConnection authLdapConnection = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        ldapConnection = getLdapConnection();
        // check the cache for user's userDn in the ldap server
        String userDn = ldapCacheService.getLdapUserDn(source.getUsername());

        if (userDn == null) {
            log.debug("userDn for user {} not found in cache. Retrieving from ldap server..",
                    source.getUsername());

            DirContext context = ldapConnection.getDirContext();

            results = context.search(mapper.getUserBaseDn(), filter, ctls);

            log.debug("Found user '{}': {}", source.getUsername(), results.hasMoreElements());

            if (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                userDn = result.getNameInNamespace();

                log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getUsername());

                // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server
                ldapCacheService.addLdapUserDn(source.getUsername(), userDn);
            } else {
                return new AuthenticationResult(false, source.getUsername(), null);
            }
        }

        log.debug("Attempting Authenication: {}", userDn);

        authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword());

        log.info("user '{}' authenticated", source.getUsername());

        return new AuthenticationResult(true, source.getUsername(), null);
    } catch (LdapException e) {
        return new AuthenticationResult(false, source.getUsername(), e);
    } catch (NamingException e) {
        return new AuthenticationResult(false, source.getUsername(), e);
    } finally {
        closeNamingEnumeration(results);
        closeLdapConnection(ldapConnection);
        if (authLdapConnection != null) {
            closeLdapConnection(authLdapConnection);
        }
    }
}

From source file:org.jasig.schedassist.impl.ldap.LDAPCalendarAccountDaoImpl.java

/**
 * //from   w  ww .  ja v  a2 s.c  om
 * @param searchFilter
 * @return
 */
@SuppressWarnings("unchecked")
protected List<ICalendarAccount> executeSearchReturnList(final Filter searchFilter) {
    log.debug("executing search filter: " + searchFilter);

    SearchControls sc = new SearchControls();
    sc.setCountLimit(searchResultsLimit);
    sc.setTimeLimit(searchTimeLimit);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    List<ICalendarAccount> results = Collections.emptyList();
    try {
        results = ldapTemplate.search(baseDn, searchFilter.toString(), sc,
                new DefaultContextMapperImpl(ldapAttributesKey));
    } catch (SizeLimitExceededException e) {
        log.debug("search filter exceeded results size limit(" + searchResultsLimit + "): " + searchFilter);
    } catch (TimeLimitExceededException e) {
        log.warn("search filter exceeded time limit (" + searchTimeLimit + " milliseconds): " + searchFilter);
    }
    return results;
}

From source file:org.jasig.portlet.contacts.adapters.impl.ldap.LdapSearchAdapter.java

/**
 * Construct a new search controls object for our search
 *///from   w  ww  .  j av  a  2 s. c  o m
protected SearchControls getSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setTimeLimit(timeLimit);
    searchControls.setCountLimit(countLimit);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    return searchControls;
}

From source file:net.identio.server.service.authentication.ldap.LdapConnectionFactory.java

@Override
public boolean validateObject(PooledObject<InitialLdapContext> p) {

    LOG.debug("Validating connection to LDAP directory {}", ldapAuthMethod.getName());

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    controls.setCountLimit(1);
    controls.setTimeLimit(500);//from w  w  w  .j av  a  2  s  . co m

    try {
        p.getObject().search("", ldapAuthMethod.getPoolConfig().getTestRequestFilter(), controls);
    } catch (NamingException e) {
        LOG.error("Validation of connection to LDAP directory {} failed", ldapAuthMethod.getName());
        return false;
    }

    return true;
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleLdapCalendarAccountDaoImpl.java

/**
 * //from ww w .ja va 2 s .c o  m
 * @param searchFilter
 * @return
 */
@SuppressWarnings("unchecked")
protected List<ICalendarAccount> executeSearchReturnList(final Filter searchFilter) {
    LOG.debug("searchFilter: " + searchFilter);
    SearchControls searchControls = new SearchControls();
    searchControls.setCountLimit(searchResultsLimit);
    searchControls.setTimeLimit(searchTimeLimit);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    List<ICalendarAccount> results = Collections.emptyList();
    try {
        results = ldapTemplate.search(baseDn, searchFilter.toString(), searchControls,
                new OracleCalendarUserAccountAttributesMapper(this.oracleGUIDSource));
        if (LOG.isDebugEnabled()) {
            LOG.debug("search " + searchFilter + " returned " + results.size() + " results");
        }
        Collections.sort(results, new AccountComparator());
    } catch (SizeLimitExceededException e) {
        LOG.debug("search filter exceeded size limit (" + searchResultsLimit + "): " + searchFilter);
    } catch (TimeLimitExceededException e) {
        LOG.debug("search filter exceeded time limit(" + searchTimeLimit + " milliseconds): " + searchFilter);
    }
    return results;
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleLdapCalendarResourceAccountDaoImpl.java

/**
 * /*ww  w.  jav a 2 s .com*/
 * @param searchFilter
 * @param owner
 * @return
 */
@SuppressWarnings("unchecked")
protected List<IDelegateCalendarAccount> executeSearchReturnList(final Filter searchFilter,
        final ICalendarAccount owner) {
    SearchControls searchControls = new SearchControls();
    searchControls.setCountLimit(searchResultsLimit);
    searchControls.setTimeLimit(searchTimeLimit);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    List<IDelegateCalendarAccount> results = Collections.emptyList();
    try {
        results = ldapTemplate.search(baseDn, searchFilter.toString(), searchControls,
                new OracleCalendarResourceAccountAttributesMapper(this.oracleGUIDSource, owner));
        if (LOG.isDebugEnabled()) {
            LOG.debug("search " + searchFilter + " returned " + results.size() + " results");
        }

        Collections.sort(results, new DelegateDisplayNameComparator());
    } catch (SizeLimitExceededException e) {
        LOG.debug("search filter exceeded size limit (" + searchResultsLimit + "): " + searchFilter);
    } catch (TimeLimitExceededException e) {
        LOG.debug("search filter exceeded time limit(" + searchTimeLimit + " milliseconds): " + searchFilter);
    }
    return results;
}

From source file:se.inera.axel.shs.broker.directory.internal.LdapDirectoryService.java

/**
 * Finds all entries matching filter, mapped with the mapper.
 * If organization is given, it is used as a search base.
 * For instance: list all addresses under a given organization.
 *
 * At most 'limit' entries are returned.
 *
 * @param organization/*from   ww w .j a  v  a  2  s . co m*/
 * @param filter
 * @param mapper
 * @param limit
 * @param dirContextProcessor
 * @param <T>
 * @return
 * @throws DirectoryException
 */
private <T> List<T> findAll(Organization organization, AndFilter filter, ParameterizedContextMapper<T> mapper,
        long limit, DirContextProcessor dirContextProcessor) throws DirectoryException {
    List<T> entries = new ArrayList<T>();
    String base = "";
    try {
        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningObjFlag(true);
        ctrl.setCountLimit(limit);

        if (organization != null) {
            base = "o=" + organization.getOrgName();
        }

        entries = ldapTemplate.search(base, filter.encode(), ctrl, mapper, dirContextProcessor);

        // Remove duplicates...
        HashSet<T> set = new HashSet<T>(entries);
        entries = new ArrayList<T>(set);

    } catch (NameNotFoundException e) {
        log.warn("not found in ldap directory: " + base + "," + filter.encode());
    } catch (RuntimeException e) {
        log.error("error during looking-up", e);
        throw new DirectoryException("error during looking-up", e);
    }

    return entries;
}

From source file:org.jasig.schedassist.impl.ldap.LDAPDelegateCalendarAccountDaoImpl.java

/**
 * /*w ww.  j  a  v a2s  .co m*/
 * @param searchFilter
 * @param owner
 * @return
 */
@SuppressWarnings("unchecked")
protected List<IDelegateCalendarAccount> executeSearchReturnList(final Filter searchFilter,
        final ICalendarAccount owner) {
    SearchControls searchControls = new SearchControls();
    searchControls.setCountLimit(searchResultsLimit);
    searchControls.setTimeLimit(searchTimeLimit);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    List<IDelegateCalendarAccount> results = Collections.emptyList();
    try {
        results = ldapTemplate.search(baseDn, searchFilter.toString(), searchControls,
                new DefaultDelegateAccountAttributesMapperImpl(ldapAttributesKey, owner));
        if (log.isDebugEnabled()) {
            log.debug("search " + searchFilter + " returned " + results.size() + " results");
        }

        if (isTreatOwnerAttributeAsDistinguishedName() && owner != null
                && owner instanceof HasDistinguishedName) {
            HasDistinguishedName ldapOwnerAccount = (HasDistinguishedName) owner;
            enforceDistinguishedNameMatch(results, ldapOwnerAccount);
        }
        Collections.sort(results, new DelegateDisplayNameComparator());
    } catch (SizeLimitExceededException e) {
        log.debug("search filter exceeded size limit (" + searchResultsLimit + "): " + searchFilter);
    } catch (TimeLimitExceededException e) {
        log.debug("search filter exceeded time limit(" + searchTimeLimit + " milliseconds): " + searchFilter);
    }
    return results;
}