LdapGroupProvider.java 31.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/**
 * $RCSfile$
 * $Revision: 3191 $
 * $Date: 2005-12-12 13:41:22 -0300 (Mon, 12 Dec 2005) $
 *
 * Copyright (C) 2005 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

package org.jivesoftware.wildfire.ldap;

14
import org.jivesoftware.util.JiveGlobals;
15
import org.jivesoftware.util.Log;
16 17 18
import org.jivesoftware.wildfire.XMPPServer;
import org.jivesoftware.wildfire.group.Group;
import org.jivesoftware.wildfire.group.GroupNotFoundException;
19
import org.jivesoftware.wildfire.group.GroupProvider;
20 21 22 23 24
import org.jivesoftware.wildfire.user.UserManager;
import org.jivesoftware.wildfire.user.UserNotFoundException;
import org.xmpp.packet.JID;

import javax.naming.NamingEnumeration;
25
import javax.naming.NamingException;
26
import javax.naming.directory.*;
27
import javax.naming.ldap.Control;
28 29
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.LdapName;
30
import javax.naming.ldap.SortControl;
31 32
import java.text.MessageFormat;
import java.util.*;
33 34
import java.util.regex.Matcher;
import java.util.regex.Pattern;
35 36

/**
37 38
 * LDAP implementation of the GroupProvider interface.  All data in the directory is treated as
 * read-only so any set operations will result in an exception.
39
 *
40
 * @author Matt Tucker, Greg Ferguson and Cameron Moore
41 42 43 44 45 46 47 48
 */
public class LdapGroupProvider implements GroupProvider {

    private LdapManager manager;
    private UserManager userManager;
    private String[] standardAttributes;

    /**
49
     * Constructs a new LDAP group provider.
50 51 52 53 54 55 56 57 58 59 60
     */
    public LdapGroupProvider() {
        manager = LdapManager.getInstance();
        userManager = UserManager.getInstance();
        standardAttributes = new String[3];
        standardAttributes[0] = manager.getGroupNameField();
        standardAttributes[1] = manager.getGroupDescriptionField();
        standardAttributes[2] = manager.getGroupMemberField();
    }

    /**
61
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
62 63 64 65 66 67 68 69 70
     *
     * @param name the name of the group to create.
     * @throws UnsupportedOperationException when called.
     */
    public Group createGroup(String name) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
71
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
72 73 74 75 76 77 78 79
     *
     * @param name the name of the group to delete
     * @throws UnsupportedOperationException when called.
     */
    public void deleteGroup(String name) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

80
    public Group getGroup(String groupName) throws GroupNotFoundException {
81
        Collection<Group> groups;
82
        LdapContext ctx = null;
83
        try {
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
            ctx = manager.getContext();

            // Search for the dn based on the group name.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(standardAttributes);
            String filter = MessageFormat.format(manager.getGroupSearchFilter(), groupName);
            NamingEnumeration<SearchResult> answer = ctx.search("", filter, searchControls);

99
            groups = populateGroups(answer);
100 101
            // Close the enumeration.
            answer.close();
102
            if (groups.size() == 1) {
103 104
                return groups.iterator().next();
            }
105
        }
106
        catch (Exception e) {
107 108
            Log.error(e);
            throw new GroupNotFoundException(e);
Matt Tucker's avatar
Matt Tucker committed
109
        }
110 111 112 113 114 115 116 117 118 119
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
120
        }
121 122 123 124 125 126
        if (groups.size() > 1) {
            // If multiple groups found, throw exception.
            throw new GroupNotFoundException(
                    "Too many groups with name " + groupName + " were found.");
        }
        throw new GroupNotFoundException("Group with name " + groupName + " not found.");
127 128 129
    }

    /**
130
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
131 132 133 134 135 136 137 138 139 140
     *
     * @param oldName the current name of the group.
     * @param newName the desired new name of the group.
     * @throws UnsupportedOperationException when called.
     */
    public void setName(String oldName, String newName) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
141
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
142
     *
143
     * @param name the group name.
144 145 146
     * @param description the group description.
     * @throws UnsupportedOperationException when called.
     */
147
    public void setDescription(String name, String description)
148 149
            throws UnsupportedOperationException
    {
150 151 152 153 154 155 156 157
        throw new UnsupportedOperationException();
    }

    public int getGroupCount() {
        if (manager.isDebugEnabled()) {
            Log.debug("Trying to get the number of groups in the system.");
        }

158 159
        int count = 0;
        LdapContext ctx = null;
160
        try {
161
            ctx = manager.getContext();
162

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
            NamingEnumeration answer = ctx.search("", filter, searchControls);
            while (answer.hasMoreElements()) {
                answer.next();
                count++;
            }
178 179
            // Close the enumeration.
            answer.close();
180
        }
181 182 183 184 185 186 187 188 189 190 191 192 193
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
194
        }
195

196 197 198
        return count;
    }

199 200 201
    public Collection<String> getGroupNames() {
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
202
        try {
203 204 205 206 207 208
            ctx = manager.getContext();
            // Sort on group name field.
            Control[] searchControl = new Control[]{
                new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
            };
            ctx.setRequestControls(searchControl);
209

210 211 212 213
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
214 215
            }
            else {
216 217 218 219 220 221 222 223 224 225 226 227
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
            NamingEnumeration answer = ctx.search("", filter, searchControls);
            while (answer.hasMoreElements()) {
                // Get the next group.
                String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                        manager.getGroupNameField()).get();
                // Escape group name and add to results.
                groupNames.add(JID.escapeNode(groupName));
            }
228 229
            // Close the enumeration.
            answer.close();
230 231 232
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
233 234
            }
        }
235 236 237 238
        catch (Exception e) {
            Log.error(e);
        }
        finally {
239
            try {
240 241 242 243
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
244
            }
245 246
            catch (Exception ignored) {
                // Ignore.
247 248
            }
        }
249
        return groupNames;
250 251
    }

252 253 254
    public Collection<String> getGroupNames(int startIndex, int numResults) {
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
255
        try {
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
            ctx = manager.getContext();
            // Sort on group name field.
            Control[] searchControl = new Control[]{
                new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
            };
            ctx.setRequestControls(searchControl);

            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");

Matt Tucker's avatar
Matt Tucker committed
274
            // TODO: used paged results if supported by LDAP server.
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
            NamingEnumeration answer = ctx.search("", filter, searchControls);
            for (int i=0; i < startIndex; i++) {
                if (answer.hasMoreElements()) {
                    answer.next();
                }
                else {
                    return Collections.emptyList();
                }
            }
            // Now read in desired number of results (or stop if we run out of results).
            for (int i = 0; i < numResults; i++) {
                if (answer.hasMoreElements()) {
                    // Get the next group.
                    String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                            manager.getGroupNameField()).get();
                    // Escape group name and add to results.
                    groupNames.add(JID.escapeNode(groupName));
                }
                else {
                    break;
                }
            }
297 298
            // Close the enumeration.
            answer.close();
299 300 301 302
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
            }
303
        }
304
        catch (Exception e) {
305
            Log.error(e);
306
        }
307
        finally {
308
            try {
309 310 311
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
312 313
                }
            }
314
            catch (Exception ignored) {
315 316 317
                // Ignore.
            }
        }
318
        return groupNames;
319 320
    }

321
    public Collection<String> getGroupNames(JID user) {
322 323
        // Get DN of specified user
        XMPPServer server = XMPPServer.getInstance();
324
        String username;
325
        if (!manager.isPosixMode()) {
326 327 328 329 330
            // Check if the user exists (only if user is a local user)
            if (!server.isLocal(user)) {
                return Collections.emptyList();
            }
            username = JID.unescapeNode(user.getNode());
331
            try {
332
                username = manager.findUserDN(username) + "," + manager.getBaseDN();
333 334
            }
            catch (Exception e) {
335
                Log.error("Could not find user in LDAP " + username);
336
                return Collections.emptyList();
337 338
            }
        }
339 340 341
        else {
            username = server.isLocal(user) ? JID.unescapeNode(user.getNode()) : user.toString();
        }
342 343 344 345 346 347 348
        // Do nothing if the user is empty or null
        if (username == null || "".equals(username)) {
            return Collections.emptyList();
        }
        // Perform the LDAP query
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
349
        try {
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
            ctx = manager.getContext();
            // Search for the dn based on the group name.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });

            StringBuilder filter = new StringBuilder();
            filter.append("(&");
            filter.append(MessageFormat.format(manager.getGroupSearchFilter(), "*"));
            filter.append("(").append(manager.getGroupMemberField()).append("=").append(username);
            filter.append("))");
            NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
            while (answer.hasMoreElements()) {
                // Get the next group.
                String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                        manager.getGroupNameField()).get();
                // Escape group name and add to results.
                groupNames.add(JID.escapeNode(groupName));
            }
            // Close the enumeration.
            answer.close();
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
            }
381
        }
382
        catch (Exception e) {
383
            Log.error("Error getting groups for user: " + user, e);
384
            return Collections.emptyList();
385 386 387 388 389 390 391 392 393 394 395 396 397
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
        return groupNames;
398 399 400
    }

    /**
401
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
402
     *
403 404
     * @param groupName name of a group.
     * @param user the JID of the user to add
405 406 407 408
     * @param administrator true if is an administrator.
     * @throws UnsupportedOperationException when called.
     */
    public void addMember(String groupName, JID user, boolean administrator)
409 410
            throws UnsupportedOperationException
    {
411 412 413 414
        throw new UnsupportedOperationException();
    }

    /**
415
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
416
     *
417 418
     * @param groupName the naame of a group.
     * @param user the JID of the user with new privileges
419 420 421 422
     * @param administrator true if is an administrator.
     * @throws UnsupportedOperationException when called.
     */
    public void updateMember(String groupName, JID user, boolean administrator)
423
            throws UnsupportedOperationException {
424 425 426 427
        throw new UnsupportedOperationException();
    }

    /**
428
     * Always throws an UnsupportedOperationException because LDAP groups are read-only.
429 430
     *
     * @param groupName the name of a group.
431
     * @param user the JID of the user to delete.
432 433
     * @throws UnsupportedOperationException when called.
     */
Matt Tucker's avatar
Matt Tucker committed
434
    public void deleteMember(String groupName, JID user) throws UnsupportedOperationException {
435 436 437 438
        throw new UnsupportedOperationException();
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
439
     * Returns true because LDAP groups are read-only.
440 441 442 443 444 445 446
     *
     * @return true because all LDAP functions are read-only.
     */
    public boolean isReadOnly() {
        return true;
    }

447
    public Collection<String> search(String query) {
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        if (query == null || "".equals(query)) {
            return Collections.emptyList();
        }
        // Make the query be a wildcard search by default. So, if the user searches for
        // "Test", make the search be "Test*" instead.
        if (!query.endsWith("*")) {
            query = query + "*";
        }
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
        try {
            ctx = manager.getContext();
            // Sort on username field.
            Control[] searchControl = new Control[]{
                new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
            };
            ctx.setRequestControls(searchControl);

            // Search for the dn based on the group name.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            StringBuilder filter = new StringBuilder();
            filter.append("(").append(manager.getGroupNameField()).append("=").append(query).append(")");
            NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
            while (answer.hasMoreElements()) {
                // Get the next group.
                String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                        manager.getGroupNameField()).get();
                // Escape group name and add to results.
                groupNames.add(JID.escapeNode(groupName));
            }
486 487
            // Close the enumeration.
            answer.close();
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
507
        return groupNames;
508 509
    }

510
    public Collection<String> search(String query, int startIndex, int numResults) {
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        if (query == null || "".equals(query)) {
            return Collections.emptyList();
        }
        // Make the query be a wildcard search by default. So, if the user searches for
        // "Test", make the search be "Test*" instead.
        if (!query.endsWith("*")) {
            query = query + "*";
        }
        List<String> groupNames = new ArrayList<String>();
        LdapContext ctx = null;
        try {
            ctx = manager.getContext();
            // Sort on username field.
            Control[] searchControl = new Control[]{
                new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
            };
            ctx.setRequestControls(searchControl);

            // Search for the dn based on the group name.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
            StringBuilder filter = new StringBuilder();
            filter.append("(").append(manager.getGroupNameField()).append("=").append(query).append(")");

Matt Tucker's avatar
Matt Tucker committed
542
            // TODO: used paged results if supported by LDAP server.
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
            NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
            for (int i=0; i < startIndex; i++) {
                if (answer.hasMoreElements()) {
                    answer.next();
                }
                else {
                    return Collections.emptyList();
                }
            }
            // Now read in desired number of results (or stop if we run out of results).
            for (int i = 0; i < numResults; i++) {
                if (answer.hasMoreElements()) {
                    // Get the next group.
                    String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
                            manager.getGroupNameField()).get();
                    // Escape group name and add to results.
                    groupNames.add(JID.escapeNode(groupName));
                }
                else {
                    break;
                }
            }
565 566
            // Close the enumeration.
            answer.close();
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
            // If client-side sorting is enabled, sort.
            if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
                Collections.sort(groupNames);
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
586
        return groupNames;
587 588 589 590 591 592
    }

    public boolean isSearchSupported() {
        return true;
    }

593
    /**
594
     * An auxilary method used to populate LDAP groups based on a provided LDAP search result.
595 596 597
     *
     * @param answer LDAP search result.
     * @return a collection of groups.
598
     * @throws javax.naming.NamingException
599
     */
600
    private Collection<Group> populateGroups(Enumeration<SearchResult> answer) throws NamingException {
601 602 603
        if (manager.isDebugEnabled()) {
            Log.debug("Starting to populate groups with users.");
        }
604
        DirContext ctx = null;
605
        try {
606 607
            TreeMap<String, Group> groups = new TreeMap<String, Group>();

608
            ctx = manager.getContext();
609

610
            SearchControls searchControls = new SearchControls();
611
            searchControls.setReturningAttributes(new String[] { manager.getUsernameField() });
612 613 614 615 616 617 618
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
619

620 621
            XMPPServer server = XMPPServer.getInstance();
            String serverName = server.getServerInfo().getName();
622 623 624 625 626 627
            // Build 3 groups.
            // group 1: uid=
            // group 2: rest of the text until first comma
            // group 3: rest of the text
            Pattern pattern =
                    Pattern.compile("(?i)(^" + manager.getUsernameField() + "=)([^,]+)(.+)");
628

629 630
            while (answer.hasMoreElements()) {
                String name = "";
631
                try {
632 633 634
                    Attributes a = answer.nextElement().getAttributes();
                    String description;
                    try {
635
                        name = ((String)((a.get(manager.getGroupNameField())).get()));
636
                        description =
637
                                ((String)((a.get(manager.getGroupDescriptionField())).get()));
638 639 640 641
                    }
                    catch (Exception e) {
                        description = "";
                    }
642 643 644 645 646 647 648 649 650 651 652 653 654 655
                    Set<JID> members = new TreeSet<JID>();
                    Attribute memberField = a.get(manager.getGroupMemberField());
                    if (memberField != null) {
                        NamingEnumeration ne = memberField.getAll();
                        while (ne.hasMore()) {
                            String username = (String) ne.next();
                            // If not posix mode, each group member is stored as a full DN.
                            if (!manager.isPosixMode()) {
                                try {
                                    // Try to find the username with a regex pattern match.
                                    Matcher matcher = pattern.matcher(username);
                                    if (matcher.matches() && matcher.groupCount() == 3) {
                                        // The username is in the DN, no additional search needed
                                        username = matcher.group(2);
656
                                    }
657 658 659 660
                                    // The regex pattern match failed. This will happen if the
                                    // the member DN's don't use the standard username field. For
                                    // example, Active Directory has a username field of
                                    // sAMAccountName, but stores group members as "CN=...".
661
                                    else {
662 663 664 665 666 667 668 669 670 671 672 673
                                        // Create an LDAP name with the full DN.
                                        LdapName ldapName = new LdapName(username);
                                        // Turn the LDAP name into something we can use in a
                                        // search by stripping off the comma.
                                        String userDNPart = ldapName.get(ldapName.size() - 1);
                                        NamingEnumeration usrAnswer = ctx.search("",
                                                userDNPart, searchControls);
                                        if (usrAnswer.hasMoreElements()) {
                                            username = (String) ((SearchResult) usrAnswer.next())
                                                    .getAttributes().get(
                                                    manager.getUsernameField()).get();
                                        }
674 675
                                        // Close the enumeration.
                                        usrAnswer.close();
676
                                    }
677
                                }
678 679
                                catch (Exception e) {
                                    Log.error(e);
680 681
                                }
                            }
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
                            // A search filter may have been defined in the LdapUserProvider.
                            // Therefore, we have to try to load each user we found to see if
                            // it passes the filter.
                            try {
                                JID userJID;
                                int position = username.indexOf("@" + serverName);
                                // Create JID of local user if JID does not match a component's JID
                                if (position == -1) {
                                    // In order to lookup a username from the manager, the username
                                    // must be a properly escaped JID node.
                                    String escapedUsername = JID.escapeNode(username);
                                    if (!escapedUsername.equals(username)) {
                                        // Check if escaped username is valid
                                        userManager.getUser(escapedUsername);
                                    }
                                    // No exception, so the user must exist. Add the user as a group
                                    // member using the escaped username.
                                    userJID = server.createJID(escapedUsername, null);
700
                                }
701 702 703 704 705 706 707
                                else {
                                    // This is a JID of a component or node of a server's component
                                    String node = username.substring(0, position);
                                    String escapedUsername = JID.escapeNode(node);
                                    userJID = new JID(escapedUsername + "@" + serverName);
                                }
                                members.add(userJID);
708
                            }
709 710 711 712 713 714 715
                            catch (UserNotFoundException e) {
                                // We can safely ignore this error. It likely means that
                                // the user didn't pass the search filter that's defined.
                                // So, we want to simply ignore the user as a group member.
                                if (manager.isDebugEnabled()) {
                                    Log.debug("User not found: " + username);
                                }
716 717
                            }
                        }
718 719
                        // Close the enumeration.
                        ne.close();
720
                    }
721 722 723
                    if (manager.isDebugEnabled()) {
                        Log.debug("Adding group \"" + name + "\" with " + members.size() +
                                " members.");
724
                    }
725 726 727
                    Collection<JID> admins = Collections.emptyList();
                    Group group = new Group(name, description, members, admins);
                    groups.put(name, group);
728 729
                }
                catch (Exception e) {
730
                    e.printStackTrace();
731 732
                    if (manager.isDebugEnabled()) {
                        Log.debug("Error while populating group, " + name + ".", e);
733 734
                    }
                }
735 736 737 738 739 740 741 742 743 744 745
            }
            if (manager.isDebugEnabled()) {
                Log.debug("Finished populating group(s) with users.");
            }

            return groups.values();
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.close();
746 747 748
                }
            }
            catch (Exception e) {
749
                // Ignore.
750 751 752 753
            }
        }
    }
}