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.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 .  java2s.c o  m

    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:com.aurel.track.util.LdapUtil.java

/**
 * Returns the CN (common name) for a given login name
 * //from w  ww . j  a va 2s .c o m
 * @param loginName
 *            the loginName of the user
 * @return CN as a String(if found), or null (else)
 */
private static String getCn(TSiteBean siteBean, String loginName) throws NamingException {
    String keyDn = null;
    DirContext ctx = getInitialContext(siteBean.getLdapServerURL(), siteBean.getLdapBindDN(),
            siteBean.getLdapBindPassword());
    if (ctx != null) {
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        // Search for the user-id
        String searchStr = "(" + siteBean.getLdapAttributeLoginName() + "=" + loginName + ")";
        NamingEnumeration<SearchResult> answer = ctx.search("", searchStr, ctls);
        if (answer.hasMore()) {
            // retrieve the CN
            SearchResult sr = answer.next();
            keyDn = sr.getName();// + "," + ctx.getNameInNamespace();
            LOGGER.debug("Name = " + keyDn);
            String nameInNamespace = ctx.getNameInNamespace();
            LOGGER.debug("Name in namespace " + nameInNamespace);
            if (nameInNamespace != null && nameInNamespace.trim().length() > 0) {
                keyDn += "," + ctx.getNameInNamespace();
            }
            LOGGER.debug("entry found for LDAP-search >" + searchStr + "<: dn= >" + keyDn + "<!");
            answer.close(); // wo don't need more answers
        } else {
            LOGGER.debug("no entry found for LDAP-search >" + searchStr + "<!");
        }
        ctx.close();
    }
    return keyDn;
}

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

/**
 * /*from  w w w  .  ja va 2 s . co m*/
 * @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:com.aurel.track.util.LdapUtil.java

/**
 * Gets the LDAP users//from  w  ww  . j av  a2  s .  c o  m
 * 
 * @param ctx
 * @param loginAttributeName
 * @param searchStrs
 * @return
 */
static List<TPersonBean> getLdapUsers(LdapContext ctx, String loginAttributeName, List<String> searchStrs) {
    List<TPersonBean> personBeans = new LinkedList<TPersonBean>();
    if (ldapMap == null || ldapMap.isEmpty()) {
        LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
        return personBeans;
    }
    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);
    for (String searchStr : searchStrs) {
        LOGGER.debug("Searching by filter " + searchStr);
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        try {
            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) {
                    LOGGER.debug("Search successful " + searchStr);
                    personBeans.add(personBean);
                }
            }
        } catch (NamingException e) {
            LOGGER.warn("Search failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return personBeans;
}

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;/*from ww w.ja  v  a 2  s .  com*/
    try {
        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:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java

@Test
@Ignore/*from   w  w w. j a  v  a  2s  .  com*/
public void testLdap() throws Exception {
    DirContext ctx = createContext();
    Assert.assertNotNull(ctx);

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls);

    System.out.println(" ==== Search Results ====");
    while (result.hasMore()) {
        SearchResult entry = result.next();
        System.out.println(" ===> " + entry.getName());
    }

}

From source file:org.apache.archiva.redback.users.ldap.LdapUserManagerTest.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 . ja v a 2s. co  m*/
    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);
    // NamingEnumeration<SearchResult> results = context.search( suffix, "(" + attribute + "=" + value + ")", ctls
    // );

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

}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves a list of all the groups in the directory.
 * @param dirContext a DirContext//from  www . jav a 2s .  c  o  m
 * @return A list of Strings representing the fully qualified DN of each group
 * @throws NamingException if an exception if thrown
 * @since 1.4.0
 */
public List<String> getGroups(DirContext dirContext) throws NamingException {
    final List<String> groupDns = new ArrayList<>();
    final SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, GROUPS_FILTER, sc);
    while (hasMoreEnum(ne)) {
        final SearchResult result = ne.next();
        groupDns.add(result.getNameInNamespace());
    }
    closeQuietly(ne);
    return groupDns;
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves a list of all groups the user is a member of.
 * @param dirContext a DirContext//from w ww  .  j  av  a2s . c om
 * @param ldapUser the LdapUser to retrieve group membership for
 * @return A list of Strings representing the fully qualified DN of each group
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public List<String> getGroups(DirContext dirContext, LdapUser ldapUser) throws NamingException {
    final List<String> groupDns = new ArrayList<>();
    final String searchFilter = variableSubstitution(USER_GROUPS_FILTER, ldapUser);
    final SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, searchFilter, sc);
    while (hasMoreEnum(ne)) {
        final SearchResult result = ne.next();
        groupDns.add(result.getNameInNamespace());
    }
    closeQuietly(ne);
    return groupDns;
}