KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > util > MergeIteratorFilter


1 /*
2  * Copyright (c) 2002-2003 by OpenSymphony
3  * All rights reserved.
4  */

5 package com.opensymphony.webwork.util;
6
7 import com.opensymphony.xwork.Action;
8
9 import java.util.ArrayList JavaDoc;
10 import java.util.Iterator JavaDoc;
11 import java.util.List JavaDoc;
12
13
14 /**
15  * A bean that takes several iterators and outputs the merge of them.
16  *
17  * @author Rickard Öberg (rickard@middleware-company.com)
18  * @version $Revision: 1.4 $
19  */

20 public class MergeIteratorFilter extends IteratorFilterSupport implements Iterator JavaDoc, Action {
21     //~ Instance fields ////////////////////////////////////////////////////////
22

23     List JavaDoc iterators = new ArrayList JavaDoc();
24
25     // Attributes ----------------------------------------------------
26
List JavaDoc sources = new ArrayList JavaDoc();
27     int idx = 0;
28
29     //~ Methods ////////////////////////////////////////////////////////////////
30

31     // Public --------------------------------------------------------
32
public void setSource(Object JavaDoc anIterator) {
33         sources.add(anIterator);
34     }
35
36     // Action implementation -----------------------------------------
37
public String JavaDoc execute() {
38         // Make source transformations
39
for (int i = 0; i < sources.size(); i++) {
40             Object JavaDoc source = sources.get(i);
41             iterators.add(getIterator(source));
42         }
43
44         return SUCCESS;
45     }
46
47     // Iterator implementation ---------------------------------------
48
public boolean hasNext() {
49         while (iterators.size() > 0) {
50             if (((Iterator JavaDoc) iterators.get(idx)).hasNext()) {
51                 return true;
52             } else {
53                 iterators.remove(idx);
54
55                 if (iterators.size() > 0) {
56                     idx = idx % iterators.size();
57                 }
58             }
59         }
60
61         return false;
62     }
63
64     public Object JavaDoc next() {
65         try {
66             return ((Iterator JavaDoc) iterators.get(idx)).next();
67         } finally {
68             idx = (idx + 1) % iterators.size();
69         }
70     }
71
72     public void remove() {
73         throw new UnsupportedOperationException JavaDoc("Remove is not supported in MergeIteratorFilter.");
74     }
75 }
76
Popular Tags