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.archone.ad.domain.UserHelper.java

public List<String> lookupMembershipGroups(DirContext dirContext, String userDn)
        throws javax.naming.NamingException {

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getMembershipSearchFilter(), new String[] { userDn }, controls);

    List<String> roles = new LinkedList<String>();
    while (searchResults.hasMore()) {
        GroupDn groupDn = new GroupDn(searchResults.next().getNameInNamespace(),
                adConfiguration.getGroupsRdn());
        roles.add(groupDn.getAsGroupId());
    }/* w  ww .  ja va 2s  .com*/

    return roles;
}

From source file:ca.aedwards.ldap.compnent.LdapClConsumer.java

public List<LdapSearchResult> getAllPersonNames() {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningObjFlag(true);/*from ww w. j a  va2s.c  o  m*/
    AndFilter filter = new AndFilter();
    //filter.and(new EqualsFilter("objectclass", "person"));
    filter.and(new GreaterThanOrEqualsFilter("changeNumber", Long.toString(clLast)));
    List<LdapSearchResult> results = endpoint.getLdapTemplate().search(DistinguishedName.EMPTY_PATH,
            filter.encode(), sc, new LdapResultContextMapper());
    //System.out.println("results: " + results.toString());
    System.out.println("Filter: " + filter.toString());
    return results;
}

From source file:com.swdouglass.joid.server.DirectoryUserManagerImpl.java

private Attributes findAttributes(String inUsername, InitialDirContext ctx) throws NamingException {

    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // perform the search
    NamingEnumeration results = ctx.search("", "(uid={0})", new Object[] { inUsername }, ctls);

    Attributes outAttrs = null;/*from ww  w.  j  av a  2s .  co  m*/
    if (results.hasMore()) {
        log.info("Found username \"" + inUsername + "\" in directory");
        outAttrs = ((SearchResult) results.next()).getAttributes();
    } else {
        log.info("Could NOT find username \"" + inUsername + "\" in directory");
    }
    return outAttrs;
}

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 www . j  a  v  a2  s  .  c  o 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:com.marklogic.samplestack.integration.web.LDAPIT.java

private SearchResult findAccountByAccountName(String accountName) throws NamingException {

    String searchFilter = "(&(objectclass=person)(cn=" + accountName + "))";

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls);

    SearchResult searchResult = null;
    if (results.hasMoreElements()) {
        searchResult = (SearchResult) results.nextElement();

        // make sure there is not another item available, there should be
        // only 1 match
        if (results.hasMoreElements()) {
            System.err.println("Matched multiple users for the accountName: " + accountName);
            return null;
        }/*from   ww  w .  j a va2s . c om*/
    }

    return searchResult;
}

From source file:org.archone.ad.authentication.ShoadRealm.java

private String getUserDn(String username) throws javax.naming.NamingException {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext dirContext = contextSource.getReadOnlyContext();
    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getUserDnSearchFilter(), new String[] { username }, controls);

    SearchResult sr = searchResults.next();

    if (sr == null || searchResults.hasMore()) {
        throw new AuthenticationException();
    }//from  www  .ja  v  a  2s. c o m

    return sr.getNameInNamespace();
}

From source file:org.archone.ad.authentication.ShoadRealm.java

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }//from  w  ww . ja va2  s  .  c o  m

    String username = (String) getAvailablePrincipal(principals);

    Set<String> roleNames = null;
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContextAdapter context = (DirContextAdapter) contextSource.getReadOnlyContext();
    try {
        String userDn = (String) getUserDn(username);

        DirContextAdapter superuserGroup = (DirContextAdapter) new LdapTemplate(contextSource)
                .lookup("cn=administrator,cn=shoad");
        Set<String> superusers = superuserGroup.getAttributeSortedStringSet("uniqueMember");

        Logger.getLogger("AUTH").log(Level.INFO, "THE SIZE IS {0}", new Integer(superusers.size()).toString());

        if (superusers.contains(userDn)) {
            Logger.getLogger("AUTH").log(Level.INFO, "SUPERUSER LOGGED IN");
            roleNames.add("SUPERUSER");
        }

        NamingEnumeration<SearchResult> searchResults = context.search("",
                adConfiguration.getMembershipSearchFilter(), new String[] { userDn }, controls);
        while (searchResults.hasMore()) {
            GroupDn groupDn = new GroupDn(searchResults.next().getNameInNamespace(),
                    adConfiguration.getGroupsRdn());
            roleNames.add(groupDn.getAsGroupId());
        }

    } catch (javax.naming.NamingException ex) {
        Logger.getLogger(ShoadRealm.class.getName()).log(Level.SEVERE, null, ex);
        throw new AuthorizationException(ex);
    }

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);

    return info;
}

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);//from   w ww  .ja v  a2 s .c  o  m
    controls.setTimeLimit(500);

    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:egovframework.com.ext.ldapumt.service.impl.DeptManageLdapDAO.java

/**
 *    ?.// www.jav  a2  s .c om
 * @param vo  vo
 */
public boolean hasChildren(String dn) throws NamingException {
    ContextSource contextSource = ldapTemplate.getContextSource();
    DirContext ctx = contextSource.getReadOnlyContext();

    String filter = "objectclass=*";
    SearchControls control = new SearchControls();
    control.setSearchScope(SearchControls.ONELEVEL_SCOPE);

    NamingEnumeration<SearchResult> n = ctx.search(dn, filter, control);

    if (n != null && n.hasMore()) {
        return true;
    }

    return false;
}

From source file:com.surevine.chat.auth.GroupAuthorisationFilter.java

/**
 * Get a list of the members of a group, searching for the group using an
 * LDAP filter expression and scope.//from ww  w  . j  ava 2s  . c  o  m
 * 
 * @param filter
 *            LDAP search filter (see RFC2254)
 * @param scope
 *            One of SearchControls.OBJECT_SCOPE,
 *            SearchControls.ONELEVEL_SCOPE, or SearchControls.SUBTREE_SCOPE
 *            (see javax.naming.directory.SearchControls)
 * @return List of usernames
 * @throws NamingException
 * @throws LdapException
 *             On any LDAP error
 */
private Collection<String> getGroupMembers(final String groupName) throws NamingException {
    _logger.debug("Looking for members of " + groupName);
    String filter = "cn=" + groupName;
    Collection<String> memberList = new HashSet<String>(20);

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> objects;
    DirContext ctx = getLdapConnection();

    objects = ctx.search("ou=groups", filter, controls);

    while (objects.hasMore()) {
        SearchResult sr = (SearchResult) objects.next();
        Attributes attributes = sr.getAttributes();
        Attribute attribute = attributes.get("member");

        if (attribute != null) {
            NamingEnumeration<?> valueEnum = attribute.getAll();

            while (valueEnum.hasMore()) {
                String value = valueEnum.next().toString();

                final String searchFor = "cn=";
                int start = value.indexOf(searchFor);
                int end = value.indexOf(',', start);

                if (start >= 0 && end >= 0) {
                    String name = value.substring(start + searchFor.length(), end);
                    _logger.debug(name + " is a chatter");
                    memberList.add(name);
                }
            }
        }
    }
    _logger.debug("Returning a total of " + memberList.size() + " chatters");
    return memberList;
}