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.eclipse.skalli.core.user.ldap.LDAPClient.java

@SuppressWarnings("nls")
private SearchControls getSearchControls() {
    SearchControls sc = new SearchControls();
    if ("base".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    } else if ("onelevel".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    } else if ("subtree".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    }//from  w w  w . ja va  2  s  .c  om
    sc.setReturningAttributes(LDAPAttributeNames.getAll());
    return sc;
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapSecurityService.java

@Override
public NamingEnumeration<SearchResult> find(int scope, String path, String filter) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(scope);
    String searchPath = path != null && !path.isEmpty() ? path + "," + baseDN : baseDN;
    return searchContext.search(searchPath, filter, searchControls);
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

@Override
public NamingEnumeration<SearchResult> find(int scope, String path, String filter) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(scope);
    String searchPath = path != null && !path.isEmpty() ? path + "," + baseDN : baseDN;

    InitialDirContext searchContext = new InitialDirContext(searchEnvironment);
    NamingEnumeration<SearchResult> searchResults = searchContext.search(searchPath, filter, searchControls);
    searchContext.close();//from ww  w.  ja v  a  2  s .c  o m
    return searchResults;
}

From source file:org.eurekastreams.server.persistence.mappers.ldap.LdapLookup.java

/**
 * Execute an ldap query based on {@link LdapLookupRequest} parameters and this DAO's configuration.
 * LdapLookupRequest is used for search upper bound, the {@link LdapTemplate}, and the search string. The rest of
 * ldap query functionality is determined by DAO configuration.
 * // w ww.ja v  a  2s.  c  om
 * @param inRequest
 *            {@link LdapLookupRequest}.
 * @return List of objects found as as result of ldap query.
 * 
 */
@Override
public List<Type> execute(final LdapLookupRequest inRequest) {
    // get ldap template.
    LdapTemplate template = ldapTemplateRetriever.getLdapTemplate(inRequest);

    // set up search controls.
    SearchControls searchControls = new SearchControls();
    searchControls.setCountLimit(inRequest.getSearchUpperBound());
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // add passed in attribute criteria to filter.
    AbstractFilter abstractFilter = filterCreator.getFilter(inRequest.getQueryString());

    // get the configured CollectingNameClassPairCallbackHandler to use for query.
    CollectingNameClassPairCallbackHandler collectingHandler = handlerFactory.getCallbackHandler();

    // execute query.
    ldapSearchStrategy.searchLdap(template, abstractFilter.encode(), searchControls, collectingHandler);

    // get results gathered by CollectingNameClassPairCallbackHandler.
    List<Type> rawResults = collectingHandler.getList();

    // Results contain nulls if the context/attribute mappers were unable to create objects, so pull them out.
    List<Type> results = new ArrayList<Type>();
    for (Type t : rawResults) {
        if (t != null) {
            results.add(t);
        }
    }

    return results;
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

/**
 * @see {@link AccountDao#findAll()}/*  ww w . j  av  a  2 s. c  o m*/
 */
@Override
public List<Account> findAll() throws DataServiceException {
    SearchControls sc = new SearchControls();
    sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    EqualsFilter filter = new EqualsFilter("objectClass", "person");
    return ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), sc, attributMapper);
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

@Override
public List<Account> find(final ProtectedUserFilter filterProtected, Filter f) {
    SearchControls sc = new SearchControls();
    sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    AndFilter and = new AndFilter();
    and.and(new EqualsFilter("objectClass", "person"));
    and.and(f);//from   w  w  w  . j  a  v a 2  s .com
    List<Account> l = ldapTemplate.search(DistinguishedName.EMPTY_PATH, and.encode(), sc, attributMapper);
    return filterProtected.filterUsersList(l);
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

/**
 * @see {@link AccountDao#findByEmail(String)}
 *//*from w  ww .  j a  va2 s  .c  o  m*/
@Override
public Account findByEmail(final String email) throws DataServiceException, NameNotFoundException {

    SearchControls sc = new SearchControls();
    sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectClass", "inetOrgPerson"));
    filter.and(new EqualsFilter("objectClass", "organizationalPerson"));
    filter.and(new EqualsFilter("objectClass", "person"));
    filter.and(new EqualsFilter("mail", email));

    List<Account> accountList = ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), sc,
            attributMapper);
    if (accountList.isEmpty()) {
        throw new NameNotFoundException("There is no user with this email: " + email);
    }
    Account account = accountList.get(0);

    return account;
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

@Override
public List<Account> findByShadowExpire() {

    SearchControls sc = new SearchControls();
    sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectClass", "shadowAccount"));
    filter.and(new EqualsFilter("objectClass", "inetOrgPerson"));
    filter.and(new EqualsFilter("objectClass", "organizationalPerson"));
    filter.and(new EqualsFilter("objectClass", "person"));
    filter.and(new PresentFilter("shadowExpire"));

    return ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), sc, attributMapper);

}

From source file:org.geoserver.security.ldap.GeoserverLdapBindAuthenticator.java

/**
 * If userFilter is defined we extract user data using the filter and
 * dnPattern (if defined) to transform username for authentication.
 * /*from ww w .  j  a  va 2 s.c o  m*/
 * @param authentication
 * @return
 */
protected DirContextOperations authenticateUsingFilter(Authentication authentication) {
    DirContextOperations user = null;
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    // format given username if required
    if (userFormat != null && !userFormat.equals("")) {
        username = MessageFormat.format(userFormat, username);
    }
    if (!StringUtils.hasLength(password)) {
        logger.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }

    DirContext ctx = null;
    String userDnStr = "";
    try {
        ctx = getContextSource().getContext(username, password);

        // Check for password policy control
        PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx);

        logger.debug("Retrieving user object using filter...");
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        user = SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, "", userFilter,
                new Object[] { username });
        userDnStr = user.getDn().toString();
        if (ppolicy != null) {
            user.setAttributeValue(ppolicy.getID(), ppolicy);
        }

    } catch (NamingException e) {
        // This will be thrown if an invalid user name is used and the
        // method may
        // be called multiple times to try different names, so we trap the
        // exception
        // unless a subclass wishes to implement more specialized behaviour.
        if ((e instanceof org.springframework.ldap.AuthenticationException)
                || (e instanceof org.springframework.ldap.OperationNotSupportedException)) {
            handleBindException(userDnStr, username, e);
        } else {
            throw e;
        }
    } catch (javax.naming.NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        LdapUtils.closeContext(ctx);
    }

    if (user == null) {
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

private MetricValue getMetric(Metric metric, String tree, String attr)
        throws MetricNotFoundException, NamingException {
    NamingEnumeration enumer = null;
    try {//from  www.j  a  va 2s .  c o m
        String[] a = { attr };
        SearchControls cons = new SearchControls();
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);
        cons.setReturningAttributes(a);
        enumer = getDirContext(metric.getProperties()).search(tree, "(&(objectClass=*))", cons);
        while (enumer.hasMore()) {
            SearchResult searchresult = (SearchResult) enumer.next();
            Attributes attrs = searchresult.getAttributes();
            Attribute val;
            if (null != (val = attrs.get(attr))) {
                return new MetricValue(new Double(val.get().toString()), System.currentTimeMillis());
            }
        }
        throw new MetricNotFoundException("");
    } finally {
        if (enumer != null) {
            enumer.close();
        }
    }
}