Example usage for javax.naming.directory SearchControls SearchControls

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

Introduction

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

Prototype

public SearchControls() 

Source Link

Document

Constructs a search constraints using defaults.

Usage

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeGroups(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws NamingException {
    int changesCount = 0;
    List<Group> existingGroupsList = executorDao.getAllGroups();
    Map<String, Group> existingGroupsByLdapNameMap = Maps.newHashMap();
    for (Group group : existingGroupsList) {
        if (!Strings.isNullOrEmpty(group.getLdapGroupName())) {
            existingGroupsByLdapNameMap.put(group.getLdapGroupName(), group);
        }//from   w w w.j  a  va  2s  . com
    }
    Set<Group> ldapGroupsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        Set<Executor> ldapExecutors = executorDao.getGroupChildren(importGroup);
        for (Executor executor : ldapExecutors) {
            if (executor instanceof Group) {
                ldapGroupsToDelete.add((Group) executor);
            }
        }
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    Map<String, SearchResult> groupResultsByDistinguishedName = Maps.newHashMap();
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_GROUP_FILTER, controls);
        while (list.hasMore()) {
            SearchResult searchResult = list.next();
            if (searchResult.getAttributes().get(ATTR_GROUP_MEMBER) == null) {
                continue;
            }
            groupResultsByDistinguishedName.put(searchResult.getNameInNamespace(), searchResult);
        }
    }
    for (SearchResult searchResult : groupResultsByDistinguishedName.values()) {
        String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
        String description = getStringAttribute(searchResult,
                LdapProperties.getSynchronizationGroupDescriptionAttribute());
        ToStringHelper toStringHelper = MoreObjects.toStringHelper("group info");
        toStringHelper.add("name", name).add("description", description).omitNullValues();
        log.debug("Read " + toStringHelper.toString());
        Group group = existingGroupsByLdapNameMap.get(name);
        if (group == null) {
            if (!LdapProperties.isSynchronizationCreateExecutors()) {
                continue;
            }
            group = new Group(name, description);
            group.setLdapGroupName(name);
            log.info("Creating " + group);
            executorDao.create(group);
            executorDao.addExecutorsToGroup(Lists.newArrayList(group), importGroup);
            permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), group);
            changesCount++;
        } else {
            ldapGroupsToDelete.remove(group);
            if (LdapProperties.isSynchronizationUpdateExecutors()) {
                List<IChange> changes = Lists.newArrayList();
                if (isAttributeNeedsChange(description, group.getDescription())) {
                    changes.add(new AttributeChange("description", group.getDescription(), description));
                    group.setDescription(description);
                    executorDao.update(group);
                }
                if (executorDao.removeExecutorFromGroup(group, wasteGroup)) {
                    changes.add(new Change("waste group removal"));
                }
                if (executorDao.addExecutorToGroup(group, importGroup)) {
                    changes.add(new Change("import group addition"));
                }
                if (!changes.isEmpty()) {
                    log.info("Updating " + group + ": " + changes);
                    changesCount++;
                }
            }
        }

        Set<Actor> actorsToDelete = Sets.newHashSet(executorDao.getGroupActors(group));
        Set<Actor> actorsToAdd = Sets.newHashSet();
        Set<Actor> groupTargetActors = Sets.newHashSet();
        fillTargetActorsRecursively(dirContext, groupTargetActors, searchResult,
                groupResultsByDistinguishedName, actorsByDistinguishedName);
        for (Actor targetActor : groupTargetActors) {
            if (!actorsToDelete.remove(targetActor)) {
                actorsToAdd.add(targetActor);
            }
        }
        if (actorsToAdd.size() > 0) {
            log.info("Adding to " + group + ": " + actorsToAdd);
            executorDao.addExecutorsToGroup(actorsToAdd, group);
            changesCount++;
        }
        if (actorsToDelete.size() > 0) {
            executorDao.removeExecutorsFromGroup(Lists.newArrayList(actorsToDelete), group);
            changesCount++;
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapGroupsToDelete.size() > 0) {
        executorDao.removeExecutorsFromGroup(ldapGroupsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapGroupsToDelete, wasteGroup);
        log.info("Inactivating " + ldapGroupsToDelete);
        changesCount += ldapGroupsToDelete.size();
    }
    return changesCount;
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from Zeppelin LdapRealm. */
private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    LOGGER.debug("SearchText: " + searchText);
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {/*  w  w  w .  j av  a  2  s  .  c  o m*/
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        constraints.setCountLimit(numUsersToFetch);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=*" + searchText + "*))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOGGER.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOGGER.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                LOGGER.debug("CurrentUser: " + currentUser);
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public ServerPrinciple[] listServicePrinciples(String filter) throws DirectoryServerManagerException {

    ServerPrinciple[] serverNames = null;

    int maxItemLimit = Integer.parseInt(
            this.realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);

    if (filter.contains("?") || filter.contains("**")) {
        log.error("Invalid search character " + filter);
        throw new DirectoryServerManagerException(
                "Invalid character sequence entered for service principle search. Please enter valid sequence.");
    }//from  w w  w  . j  a  v a2 s  . co m

    StringBuilder searchFilter;
    searchFilter = new StringBuilder(
            this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    StringBuilder buff = new StringBuilder();
    buff.append("(&").append(searchFilter).append("(")
            .append(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE).append("=").append(filter)
            .append(")").append(getServerPrincipleIncludeString()).append(")");

    String[] returnedAtts = { LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE,
            LDAPServerManagerConstants.LDAP_COMMON_NAME };
    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    try {
        dirContext = connectionSource.getContext();
        NamingEnumeration<SearchResult> answer = dirContext.search(searchBase, buff.toString(), searchCtls);
        List<ServerPrinciple> list = new ArrayList<ServerPrinciple>();
        int i = 0;
        while (answer.hasMoreElements() && i < maxItemLimit) {
            SearchResult sr = answer.next();
            if (sr.getAttributes() != null) {
                Attribute serverNameAttribute = sr.getAttributes()
                        .get(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE);
                Attribute serverDescription = sr.getAttributes()
                        .get(LDAPServerManagerConstants.LDAP_COMMON_NAME);
                if (serverNameAttribute != null) {

                    ServerPrinciple principle;
                    String serviceName;
                    String serverPrincipleFullName = (String) serverNameAttribute.get();

                    if (serverPrincipleFullName.toLowerCase(Locale.ENGLISH)
                            .contains(LDAPServerManagerConstants.KERBEROS_TGT)) {
                        continue;
                    }

                    if (serverPrincipleFullName.contains("@")) {
                        serviceName = serverPrincipleFullName.split("@")[0];
                    } else {
                        serviceName = serverPrincipleFullName;
                    }

                    if (serverDescription != null) {
                        principle = new ServerPrinciple(serviceName, (String) serverDescription.get());
                    } else {

                        principle = new ServerPrinciple(serviceName);
                    }

                    list.add(principle);
                    i++;
                }
            }
        }

        serverNames = list.toArray(new ServerPrinciple[list.size()]);
        Arrays.sort(serverNames);

    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new DirectoryServerManagerException("Unable to list service principles.", e);
    } catch (UserStoreException e) {
        log.error("Unable to retrieve LDAP connection context.", e);
        throw new DirectoryServerManagerException("Unable to list service principles.", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
    return serverNames;

}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

@Override
public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }//www.j a  v a  2s .  c o m

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";
    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);

    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        if (newCredential != null) {
            mods = new ModificationItem[1];
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));

            subDirContext = (DirContext) dirContext.lookup(searchBase);
            subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);
        }

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.membership.get", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> listMermbershipGroups(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    UserDn userDn = nameHelper.newUserDnFromId(userId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

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

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(
            nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())),
            "(uniqueMember=" + userDn.toString() + ")", controls);

    List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>();
    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) {
            HashMap<String, Object> group = new HashMap<String, Object>();
            group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId());
            groups.add(group);//from ww w. j  a  va2  s . c o  m
        }
    }

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("groups", groups);

    return response;
}

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java

/**
 * Search for all users starting at <code>ou=users</code>, looking for objects with <code>objectClass=person</code>,
 * and returning the <code>uniqueMember</code> attribute.
 *//*  w  ww .  j  a va2  s . c o  m*/
@Test
public void testGetAllUserNames2() {
    SearchControls con2 = new SearchControls();
    con2.setReturningAttributes(new String[] { "uid" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=users", "(objectClass=person)", //$NON-NLS-1$//$NON-NLS-2$
            con2);

    Transformer transformer2 = new SearchResultToAttrValueList("uid"); //$NON-NLS-1$

    LdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer2);

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setAllUsernamesSearch(allUsernamesSearch);

    List res = userRoleListService.getAllUsers();

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("admin")); //$NON-NLS-1$

    if (logger.isDebugEnabled()) {
        logger.debug("results of getAllUserNames2(): " + res); //$NON-NLS-1$
    }
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * /*from  ww w.ja  v  a  2  s  .  c om*/
 * @param search
 * @param searchValue
 * @param attributeNames
 * @return naming enumeration
 */
protected NamingEnumeration getLdapResults(Search search, String searchValue, String[] attributeNames) {
    DirContext context = null;
    NamingEnumeration results = null;
    String filter = search.getParam("filter");
    if (filter == null) {
        log.error("Search filter not found for search type:  " + search.getSearchType());
        return results;
    }
    filter = filter.replaceAll("%TERM%", escapeSearchFilter(searchValue));
    String base = search.getParam("base");
    if (base == null) {
        base = "";
        log.error("Search base not found for:  " + search.getSearchType() + ". Using base \"\" ");

    }
    int scopeNum = -1;
    String scope = search.getParam("scope");
    if (scope != null) {
        scopeNum = getScope(scope);
    }
    if (scopeNum == -1) {
        scopeNum = SearchControls.SUBTREE_SCOPE;
        log.error("Search scope not found for: " + search.getSearchType() + ". Using scope SUBTREE_SCOPE.");
    }
    log.debug("searchType: " + search.getSearchType() + " filter: " + filter + " base: " + base + " scope: "
            + scope);
    try {
        context = new InitialDirContext(this.environment);
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(scopeNum);
        constraints.setReturningAttributes(attributeNames);
        results = context.search(base, filter, constraints);
    } catch (AuthenticationException ex) {
        log.error("Ldap Authentication Exception: " + ex.getMessage(), ex);
    } catch (NamingException ex) {
        log.error("Ldap NamingException: " + ex.getMessage(), ex);

    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ne) {
                // squelch, since it is already closed
            }
        }
    }
    return results;

}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public void execute(LookupRequest lookupRequest, LookupResponse lookupResponse) {

    Ldap ldap = null;/*from  w ww  .j  a  v a 2 s  .  c o m*/
    try {
        // will not return AD Range option attrs
        // Attributes attributes = ldap.getAttributes(escapedDn, retAttrs);

        SearchFilter sf = new SearchFilter();
        sf.setFilter("objectclass=*");
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);

        // This lookup requests attributes defined for *all* objects.
        // Perhaps there should be two searches, one for the identifier
        // and a second for attributes.
        String[] retAttrs = getPSP().getNames(getId(), lookupRequest.getReturnData()).toArray(new String[] {});
        sc.setReturningAttributes(retAttrs);

        // TODO logging
        String dn = lookupRequest.getPsoID().getID();
        String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn);

        ldap = ldapPool.checkOut();

        LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(lookupRequest));
        Iterator<SearchResult> searchResults = ldap.search(escapedDn, sf, sc);
        LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(lookupRequest));

        if (!searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
            return;
        }

        SearchResult result = searchResults.next();

        if (searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.CUSTOM_ERROR, "More than one result found.");
            return;
        }
        Attributes attributes = result.getAttributes();

        // return attributes in order defined by config
        OrderedLdapBeanFactory orderedLdapBeanFactory = new OrderedLdapBeanFactory();
        // sort values
        SortedLdapBeanFactory sortedLdapBeanFactory = new SortedLdapBeanFactory();

        LdapAttributes ldapAttributes = orderedLdapBeanFactory.newLdapAttributes();
        for (String retAttr : retAttrs) {
            Attribute attr = attributes.get(retAttr);
            if (attr != null) {
                LdapAttribute ldapAttribute = sortedLdapBeanFactory.newLdapAttribute();
                ldapAttribute.setAttribute(attr);
                ldapAttributes.addAttribute(ldapAttribute);
            }
        }

        LdapEntry entry = sortedLdapBeanFactory.newLdapEntry();
        entry.setDn(dn);
        entry.setLdapAttributes(ldapAttributes);

        if (this.isLogLdif()) {
            LdapResult lr = sortedLdapBeanFactory.newLdapResult();
            lr.addEntry(entry);
            LdifResultConverter lrc = new LdifResultConverter();
            LOG.info("Target '{}' - LDIF\n{}", getId(), lrc.toLdif(lr));
        }

        // build pso
        lookupResponse.setPso(getPSO(entry, lookupRequest.getReturnData()));

    } catch (NameNotFoundException e) {
        fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
    } catch (LdapPoolException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (InvalidNameException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (NamingException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (DSMLProfileException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (Spml2Exception e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        if (ldap != null) {
            ldapPool.checkIn(ldap);
        }
    }
}

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java

/**
 * Search for all users starting at <code>ou=users</code>, looking for objects with <code>objectClass=person</code>,
 * and returning the <code>uniqueMember</code> attribute.
 *//*  w ww .j a v  a  2 s. c o  m*/
@Test
public void testGetAllUserNames2() {
    SearchControls con2 = new SearchControls();
    con2.setReturningAttributes(new String[] { "uid" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=users", "(objectClass=person)", //$NON-NLS-1$//$NON-NLS-2$
            con2);

    Transformer transformer2 = new SearchResultToAttrValueList("uid"); //$NON-NLS-1$

    LdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer2);

    DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService();

    userRoleListService.setAllUsernamesSearch(allUsernamesSearch);

    List res = userRoleListService.getAllUsers();

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("admin")); //$NON-NLS-1$

    if (logger.isDebugEnabled()) {
        logger.debug("results of getAllUserNames2(): " + res); //$NON-NLS-1$
    }
}

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

/**
 * @see org.opentravel.schemacompiler.security.AuthenticationProvider#searchCandidateUsers(java.lang.String, int)
 *//*ww  w  .  j a va 2s . c o  m*/
@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;
}