Example usage for javax.naming.directory SearchControls setSearchScope

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

Introduction

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

Prototype

public void setSearchScope(int scope) 

Source Link

Document

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Usage

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

/**
 * //www .j  a  va 2 s . c  om
 * @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:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

@SuppressWarnings("deprecation")
private DirContextOperations searchForUser(DirContext ctx, String username) throws NamingException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String searchFilter = "(&(objectClass=user)(userPrincipalName={0}))";

    final String bindPrincipal = createBindPrincipal(username);

    String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);

    try {//ww  w. ja  v  a  2  s .  c  o  m
        return SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, searchRoot,
                searchFilter, new Object[] { bindPrincipal });
    } catch (IncorrectResultSizeDataAccessException incorrectResults) {
        if (incorrectResults.getActualSize() == 0) {
            UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException(
                    "User " + username + " not found in directory.", username);
            userNameNotFoundException.initCause(incorrectResults);
            throw badCredentials(userNameNotFoundException);
        }
        // Search should never return multiple results if properly configured, so just rethrow
        throw incorrectResults;
    }
}

From source file:org.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);//from   w  w  w . j av a 2s  . c  om
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

protected boolean userExists(String id) {
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {/* w  ww.  j  av a 2  s  .c  om*/
        DirContext ctx = new InitialDirContext(env);

        /*
         * Setup subtree scope to tell LDAP to recursively descend directory structure during searches.
         */
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /*
         * Setup the directory entry attributes we want to search for. In this case it is the user's ID.
         */

        String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))";

        /* Execute the search, starting at the directory level of Users */

        NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls);

        /* All we need to know is if there were any hits at all. */

        if (hits.hasMore()) {
            hits.close();
            ctx.close();
            return true;
        } else {
            hits.close();
            ctx.close();
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

private boolean getUserInf(UserEdit edit, String filter) {

    String id = null;/*from  w w w  .j ava 2s . com*/
    String firstName = null;
    String lastName = null;
    String employeenumber = null;
    String email = null;
    try {
        DirContext ctx = new InitialDirContext(env);

        // Setup subtree scope to tell LDAP to recursively descend directory structure
        // during searches.
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // We want the user's id, first name and last name ...
        searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" });

        // Execute the search, starting at the directory level of Users
        NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls);

        while (results.hasMore()) {
            SearchResult result = (SearchResult) results.next();
            String dn = result.getName().toString() + "," + getBasePath();
            Attributes attrs = ctx.getAttributes(dn);
            id = attrs.get("uid").get().toString();
            String cn = attrs.get("cn").get().toString();
            firstName = cn.substring(0, cn.indexOf(" "));
            lastName = cn.substring(cn.indexOf(" "));
            email = attrs.get("mail").get().toString();
        }

        results.close();
        ctx.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

    edit.setId(id);
    edit.setFirstName(firstName);
    edit.setLastName(lastName);
    edit.setEmail(email);
    return true;
}

From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java

public List<UserCredentials> getAllUsers() {

    List<UserCredentials> userCredentials = new ArrayList<UserCredentials>();

    try {//ww  w.  j a v a2 s  .c  o m

        SearchControls searchCtls = new SearchControls();
        String returnedAtts[] = { "uid" };
        searchCtls.setReturningAttributes(returnedAtts);
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchFilter = "(&(objectClass=person))";

        NamingEnumeration<SearchResult> elements = contextSource.getReadOnlyContext().search("", searchFilter,
                searchCtls);

        while (elements.hasMoreElements()) {
            DistinguishedName dn = new DistinguishedName(elements.nextElement().getName());
            String userName = dn.getValue("uid");
            userCredentials.add(getUserFromDatabase(userName));
        }

    } catch (org.springframework.ldap.NamingException e) {
        e.printStackTrace();
        return null;
    } catch (NamingException e) {
        e.printStackTrace();
        return null;
    }

    return userCredentials;

}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Performs a search for the specified username. Internally, this method queries on
 * the attribute defined by {@link Config.AlpineKey#LDAP_ATTRIBUTE_NAME}.
 * @param ctx the DirContext to use/*from w  ww .  ja  va 2 s.  c  o m*/
 * @param username the username to query on
 * @return a list of SearchResult objects. If the username is found, the list should typically only contain one result.
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public List<SearchResult> searchForUsername(DirContext ctx, String username) throws NamingException {
    final String[] attributeFilter = {};
    final SearchControls sc = new SearchControls();
    sc.setReturningAttributes(attributeFilter);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchFor = LdapConnectionWrapper.ATTRIBUTE_NAME + "="
            + LdapStringSanitizer.sanitize(formatPrincipal(username));
    return Collections.list(ctx.search(LdapConnectionWrapper.BASE_DN, searchFor, sc));
}

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

/**
 * //from   w  w  w.ja v  a  2s.  c  o 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 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:org.jasig.cas.authentication.principal.AbstractLdapPersonDirectoryCredentialsToPrincipalResolver.java

protected final SearchControls getSearchControls() {
    final SearchControls constraints = new SearchControls();
    if (log.isDebugEnabled()) {
        log.debug("returning searchcontrols: scope=" + this.scope + "; search base=" + this.searchBase
                + "; attributes=" + Arrays.toString(this.attributeIds) + "; timeout=" + this.timeout);
    }//from   w ww. ja  v a 2  s  . c  o  m
    constraints.setSearchScope(this.scope);
    constraints.setReturningAttributes(this.attributeIds);
    constraints.setTimeLimit(this.timeout);
    constraints.setCountLimit(DEFAULT_MAX_NUMBER_OF_RESULTS);
    return constraints;
}