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.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * @see org.opentravel.schemacompiler.security.AuthenticationProvider#searchCandidateUsers(java.lang.String, int)
 *//*from   ww w  . j a v a  2  s.com*/
@Override
public List<UserPrincipal> searchCandidateUsers(String searchCriteria, int maxResults)
        throws RepositoryException {
    List<UserPrincipal> userList = new ArrayList<>();

    if ((searchCriteria != null) && (searchCriteria.length() > 0)) {
        List<String> searchAttributes = Arrays.asList(userLastNameAttribute, userFirstNameAttribute,
                userFullNameAttribute);
        StringBuilder searchFilter = new StringBuilder("(&(objectCategory=person)(").append(userIdAttribute)
                .append("=*)(|");
        SearchControls constraints = new SearchControls();
        DirContext context = null;

        for (String searchAttr : searchAttributes) {
            if ((searchAttr != null) && (searchAttr.length() > 0)) {
                searchFilter.append("(").append(searchAttr).append("=*").append(searchCriteria).append("*)");
            }
        }
        searchFilter.append("))");
        constraints.setSearchScope(
                searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
        constraints.setTimeLimit(userSearchTimeout);
        constraints.setCountLimit(maxResults);
        constraints.setReturningAttributes(new String[] { userIdAttribute, userLastNameAttribute,
                userFirstNameAttribute, userEmailAttribute });

        try {
            context = openConnection(connectionPrincipal, connectionPassword);
            NamingEnumeration<SearchResult> searchResults = context.search(userSearchBase,
                    searchFilter.toString(), constraints);

            while (searchResults.hasMore()) {
                SearchResult resultItem = searchResults.next();
                Attributes itemAttrs = resultItem.getAttributes();
                String userId = getAttributeValue(itemAttrs, userIdAttribute);
                String lastName = getAttributeValue(itemAttrs, userLastNameAttribute);
                String firstName = getAttributeValue(itemAttrs, userFirstNameAttribute);
                String email = getAttributeValue(itemAttrs, userEmailAttribute);
                UserPrincipal user = new UserPrincipal();

                user.setUserId(userId);
                user.setLastName(lastName);
                user.setFirstName(firstName);
                user.setEmailAddress(email);
                userList.add(user);
            }

        } catch (PartialResultException | SizeLimitExceededException e) {
            // Ignore - this means we have reached the end of the list and that any remaining
            // items are aliased referrals which cannot be resolved.

        } catch (NamingException e) {
            throw new RepositoryException("Error encountered during directory search.", e);
        }
    }
    return userList;
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Searches the remote directory for the user's entry and returns its distinguished name
 * string.//ww  w . ja va 2s .  c  o  m
 * 
 * @param userId
 *            the ID of the user whose DN is to be retrieved
 * @param context
 *            the directory context from which to retrieve the user's DN
 * @return String
 * @throws NamingException
 */
protected String findUserDn(String userId, DirContext context) throws NamingException {
    String userDn = null;

    for (MessageFormat userSearchPattern : userSearchPatterns) {
        try {
            String searchFilter = userSearchPattern.format(new String[] { userId });
            SearchControls constraints = new SearchControls();

            constraints.setSearchScope(
                    searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
            constraints.setTimeLimit(userSearchTimeout);

            NamingEnumeration<SearchResult> results = context.search(userSearchBase, searchFilter, constraints);
            SearchResult result = null;

            try {
                if ((results != null) && results.hasMore()) {
                    result = results.next();

                    // Make sure only one entry exists for the requested user
                    if (results.hasMore()) {
                        log.warn("Multiple entries found for user: " + userId);
                        result = null;
                    }
                }
            } catch (PartialResultException e) {
                // Ignore partial result errors - most likely due to ActiveDirectory referrals
            }

            if (result != null) {
                userDn = result.getNameInNamespace();
                break;
            }

        } catch (NameNotFoundException e) {
            // Ignore and keep searching
        }
    }
    return userDn;
}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

private List search(DirContext ctx, String rootDN, String scope, String filter, String[] attributes) {
    try {/*from  w ww . jav  a  2 s  .  c  o  m*/
        List listResults = new ArrayList();
        SearchControls constraints = new SearchControls();

        constraints.setSearchScope(convertSearchScope(scope));
        constraints.setReturningAttributes(attributes);

        try {
            if (scope != null && scope.toUpperCase().equals("ALLLEVELS")) {
                String[] levels = rootDN.split(",");
                for (int i = 0; i < levels.length; i++) {
                    String[] currentLevels = new String[levels.length - i];
                    System.arraycopy(levels, i, currentLevels, 0, levels.length - i);
                    String levelRootDN = StringUtils.join(currentLevels, ",");
                    if (logger.isDebugEnabled())
                        logger.debug("LDAP Search on level " + levelRootDN);
                    NamingEnumeration results = ctx.search(levelRootDN, filter, constraints);
                    for (; results.hasMore();) {
                        SearchResult result = (SearchResult) results.next();
                        listResults.add(result);
                    }
                }
            } else {
                NamingEnumeration results = ctx.search(rootDN, filter, constraints);
                for (; results.hasMore();) {
                    SearchResult result = (SearchResult) results.next();
                    listResults.add(result);
                }
            }

        } catch (NameNotFoundException e) {
            // for example in case of ALLLEVELS scope, if the LDAP database suffix has more than one component, the last iteration would result in NameNotFoundException
        }
        return listResults;
    } catch (NamingException e) {
        throw new OXFException("LDAP Search Failed", e);
    }
}

From source file:org.projectforge.business.ldap.LdapDao.java

public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException {
    final LinkedList<T> list = new LinkedList<T>();
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnit);
    results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
    while (results.hasMore()) {
        final SearchResult searchResult = (SearchResult) results.next();
        final String dn = searchResult.getName();
        final Attributes attributes = searchResult.getAttributes();
        list.add(mapToObject(dn, searchBase, attributes));
    }// w w  w. j  a  v a 2s.  c  om
    return list;
}

From source file:org.projectforge.business.ldap.LdapDao.java

public T findById(final DirContext ctx, final Object id, final String... organizationalUnits)
        throws NamingException {
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnits);
    final String args = "(&(objectClass=" + getObjectClass() + ")(" + getIdAttrId() + "=" + buildId(id) + "))";
    results = ctx.search(searchBase, args, controls);
    if (results.hasMore() == false) {
        return null;
    }/*w w w.  j  av  a 2 s . co  m*/
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    if (results.hasMore() == true) {
        log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + id);
    }
    return mapToObject(dn, searchBase, attributes);
}

From source file:org.projectforge.business.ldap.LdapUserDao.java

public LdapUser findByUsername(final Object username, final String... organizationalUnits) {
    return (LdapUser) new LdapTemplate(ldapConnector) {
        @Override/*from  ww  w . j  av a 2  s  .  co  m*/
        protected Object call() throws NameNotFoundException, Exception {
            NamingEnumeration<?> results = null;
            final SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            final String searchBase = getSearchBase(organizationalUnits);
            results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))",
                    controls);
            if (results.hasMore() == false) {
                return null;
            }
            final SearchResult searchResult = (SearchResult) results.next();
            final String dn = searchResult.getName();
            final Attributes attributes = searchResult.getAttributes();
            if (results.hasMore() == true) {
                log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username);
            }
            return mapToObject(dn, searchBase, attributes);
        }
    }.excecute();
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapImportManagerImpl.java

private void runSearch(NameClassPairCallbackHandler handler, long limit, int connectionId) {
    SearchControls sc = new SearchControls();
    sc.setCountLimit(limit);/*  w  ww.  j a v a  2 s .co m*/
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    AttrMap attrMap = m_ldapManager.getAttrMap(connectionId);
    if (!attrMap.verified()) {
        m_ldapManager.verify(m_ldapManager.getConnectionParams(connectionId), attrMap);
    }

    sc.setReturningAttributes(attrMap.getLdapAttributesArray());

    String base = attrMap.getSearchBase();
    String filter = attrMap.getSearchFilter();

    LdapTemplate template = m_templateFactory.getLdapTemplate(m_ldapManager.getConnectionParams(connectionId));
    try {
        template.search(base, filter, sc, handler, LdapManager.NULL_PROCESSOR);
    } catch (Exception e) {
        if (e instanceof SearchLimitExceededException) {
            // See http://forum.springframework.org/archive/index.php/t-27836.html
            LOG.info("Normal overflow, requesting to preview more records then exist");
        } else {
            LOG.error("LDAP search failed", e);
            throw new UserException("LDAP search failed : " + e.getCause().getMessage());
        }
    }
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapManagerImpl.java

public Schema getSchema(String subschemaSubentry, LdapConnectionParams params) {
    try {//from  w w w. j  a  v a  2  s  . c o  m
        SearchControls cons = new SearchControls();
        // only interested in the first result
        cons.setCountLimit(1);
        // set time limit for this search to 30 sec, should be sufficient even for large LDAPs
        cons.setTimeLimit(30000);

        SchemaMapper mapper = new SchemaMapper();
        cons.setReturningAttributes(mapper.getReturningAttributes());
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);

        Schema schema = (Schema) m_templateFactory.getLdapTemplate(params).search(subschemaSubentry,
                LdapManager.FILTER_ALL_CLASSES, cons, new SchemaMapper(), LdapManager.NULL_PROCESSOR).get(0);

        return schema;
    } catch (DataIntegrityViolationException e) {
        LOG.debug("Retrieving schema failed.", e);
        throw new UserException("searchSchema.violation.error");
    } catch (UncategorizedLdapException e) {
        LOG.debug("Retrieving schema failed. Anonymous-binding may be disabled", e);
        throw new UserException("searchSchema.anonymousBinding.error");
    }
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapManagerImpl.java

/**
 * Connects to LDAP to retrieve the namingContexts attribute from root. Good
 * way to verify if LDAP is accessible. Command line anologue is:
 *
 * ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts
 *
 * @param attrNames//w  w w . j  a  v  a  2  s .  com
 *            TODO
 *
 * @return namingContext value - can be used as the search base for user if
 *         nothing more specific is provided
 * @throws NamingException
 */
private Map<String, String> retrieveDefaultSearchBase(LdapConnectionParams params, String[] attrNames)
        throws NamingException {

    SearchControls cons = new SearchControls();

    cons.setReturningAttributes(attrNames);
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    cons.setTimeLimit(30000);

    List<Map<String, String>> results = m_templateFactory.getLdapTemplate(params).search("", FILTER_ALL_CLASSES,
            cons, new AttributesToValues(attrNames), NULL_PROCESSOR);
    // only interested in the first result
    if (results.size() > 0) {
        return results.get(0);
    }
    return null;
}

From source file:org.springframework.ldap.core.LdapTemplate.java

private SearchControls getDefaultSearchControls(int searchScope, boolean returningObjFlag, String[] attrs) {

    SearchControls controls = new SearchControls();
    controls.setSearchScope(searchScope);
    controls.setReturningObjFlag(returningObjFlag);
    controls.setReturningAttributes(attrs);
    return controls;
}