Index: src/main/java/org/apache/james/user/ldap/ReadOnlyUsersLDAPRepository.java =================================================================== --- src/main/java/org/apache/james/user/ldap/ReadOnlyUsersLDAPRepository.java (revision 1308299) +++ src/main/java/org/apache/james/user/ldap/ReadOnlyUsersLDAPRepository.java (working copy) @@ -333,6 +333,44 @@ return results; } + + /** + * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass} + * and builds {@link User} based on search result. + * + * @param name + * The userId which should be value of the field {@link #userIdAttribute} + * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the + * userId of this user and ldap connection information with which + * the user was searched. Return null if such a user was not found. + * @throws NamingException + * Propagated by the underlying LDAP communication layer. + */ + private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException { + SearchControls sc = new SearchControls(); + sc.setSearchScope(SearchControls.SUBTREE_SCOPE); + sc.setReturningAttributes(new String[] { userIdAttribute }); + sc.setCountLimit(1); + + StringBuilder builderFilter = new StringBuilder("(&("); + builderFilter.append(userIdAttribute).append("=").append(name).append(")") + .append("(objectClass=").append(userObjectClass).append("))"); + + NamingEnumeration sr = ldapConnection.getLdapContext().search(userBase, builderFilter.toString(), + sc); + + if (!sr.hasMore()) + return null; + + SearchResult r = sr.next(); + Attribute userName = r.getAttributes().get(userIdAttribute); + + if (!restriction.isActivated() + || userInGroupsMembershipList(r.getNameInNamespace(), restriction.getGroupMembershipLists(ldapConnection))) + return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapHost); + + return null; + } /** * Given a userDN, this method retrieves the user attributes from the LDAP @@ -425,21 +463,12 @@ */ public User getUserByName(String name) throws UsersRepositoryException { try { - Iterator userIt = buildUserCollection(getValidUsers()).iterator(); - while (userIt.hasNext()) { - ReadOnlyLDAPUser u = userIt.next(); - if (u.getUserName().equals(name)) { - return u; - } - } + return searchAndBuildUser(name); } catch (NamingException e) { log.error("Unable to retrieve user from ldap", e); throw new UsersRepositoryException("Unable to retrieve user from ldap", e); - } - return null; - } /*