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