001: /**
002: * $Revision: 691 $
003: * $Date: 2004-12-13 15:06:54 -0300 (Mon, 13 Dec 2004) $
004: *
005: * Copyright (C) 2004-2006 Jive Software. All rights reserved.
006: *
007: * This software is published under the terms of the GNU Public License (GPL),
008: * a copy of which is included in this distribution.
009: */package org.jivesoftware.openfire.user;
010:
011: import java.util.Iterator;
012: import java.util.NoSuchElementException;
013: import java.util.AbstractCollection;
014:
015: /**
016: * Provides a view of an array of usernames as a Collection of User objects. If
017: * any of the usernames cannot be loaded, they are transparently skipped when
018: * iterating over the collection.
019: *
020: * @author Matt Tucker
021: */
022: public class UserCollection extends AbstractCollection {
023:
024: private String[] elements;
025:
026: /**
027: * Constructs a new UserCollection.
028: */
029: public UserCollection(String[] elements) {
030: this .elements = elements;
031: }
032:
033: public Iterator iterator() {
034: return new UserIterator();
035: }
036:
037: public int size() {
038: return elements.length;
039: }
040:
041: private class UserIterator implements Iterator {
042:
043: private int currentIndex = -1;
044: private Object nextElement = null;
045:
046: public boolean hasNext() {
047: // If we are at the end of the list, there can't be any more elements
048: // to iterate through.
049: if (currentIndex + 1 >= elements.length
050: && nextElement == null) {
051: return false;
052: }
053: // Otherwise, see if nextElement is null. If so, try to load the next
054: // element to make sure it exists.
055: if (nextElement == null) {
056: nextElement = getNextElement();
057: if (nextElement == null) {
058: return false;
059: }
060: }
061: return true;
062: }
063:
064: public Object next() throws java.util.NoSuchElementException {
065: Object element;
066: if (nextElement != null) {
067: element = nextElement;
068: nextElement = null;
069: } else {
070: element = getNextElement();
071: if (element == null) {
072: throw new NoSuchElementException();
073: }
074: }
075: return element;
076: }
077:
078: public void remove() throws UnsupportedOperationException {
079: throw new UnsupportedOperationException();
080: }
081:
082: /**
083: * Returns the next available element, or null if there are no more elements to return.
084: *
085: * @return the next available element.
086: */
087: private Object getNextElement() {
088: while (currentIndex + 1 < elements.length) {
089: currentIndex++;
090: Object element = null;
091: try {
092: element = UserManager.getInstance().getUser(
093: elements[currentIndex]);
094: } catch (UserNotFoundException unfe) {
095: // Ignore.
096: }
097: if (element != null) {
098: return element;
099: }
100: }
101: return null;
102: }
103: }
104: }
|