1 /*
2 * $Id: MergeIteratorFilter.java 439747 2006-09-03 09:22:46Z mrdon $
3 *
4 * Copyright 2006 The Apache Software Foundation.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.apache.struts2.util;
19
20 import java.util.ArrayList;
21 import java.util.Iterator;
22 import java.util.List;
23
24 import com.opensymphony.xwork2.Action;
25
26
27 /***
28 * A bean that takes several iterators and outputs the merge of them. Used by
29 * MergeIteratorTag.
30 *
31 * @see org.apache.struts2.views.jsp.iterator.MergeIteratorTag
32 * @see org.apache.struts2.components.MergeIterator
33 */
34 public class MergeIteratorFilter extends IteratorFilterSupport implements Iterator, Action {
35
36 List iterators = new ArrayList();
37
38 // Attributes ----------------------------------------------------
39 List sources = new ArrayList();
40 int idx = 0;
41
42
43 // Public --------------------------------------------------------
44 public void setSource(Object anIterator) {
45 sources.add(anIterator);
46 }
47
48 // Action implementation -----------------------------------------
49 public String execute() {
50 // Make source transformations
51 for (int i = 0; i < sources.size(); i++) {
52 Object source = sources.get(i);
53 iterators.add(getIterator(source));
54 }
55
56 return SUCCESS;
57 }
58
59 // Iterator implementation ---------------------------------------
60 public boolean hasNext() {
61 while (iterators.size() > 0) {
62 if (((Iterator) iterators.get(idx)).hasNext()) {
63 return true;
64 } else {
65 iterators.remove(idx);
66
67 if (iterators.size() > 0) {
68 idx = idx % iterators.size();
69 }
70 }
71 }
72
73 return false;
74 }
75
76 public Object next() {
77 try {
78 return ((Iterator) iterators.get(idx)).next();
79 } finally {
80 idx = (idx + 1) % iterators.size();
81 }
82 }
83
84 public void remove() {
85 throw new UnsupportedOperationException("Remove is not supported in MergeIteratorFilter.");
86 }
87 }