1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.struts2.util;
19
20 import java.util.ArrayList;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.StringTokenizer;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28 import com.opensymphony.xwork2.Action;
29
30
31 /***
32 * A bean that generates an iterator filled with a given object depending on the count,
33 * separator and converter defined. It is being used by IteratorGeneratorTag.
34 *
35 */
36 public class IteratorGenerator implements Iterator, Action {
37
38 private static final Log _log = LogFactory.getLog(IteratorGenerator.class);
39
40 List values;
41 Object value;
42 String separator;
43 Converter converter;
44
45
46 int count = 0;
47 int currentCount = 0;
48
49
50 public void setCount(int aCount) {
51 this.count = aCount;
52 }
53
54 public boolean getHasNext() {
55 return hasNext();
56 }
57
58 public Object getNext() {
59 return next();
60 }
61
62 public void setSeparator(String aChar) {
63 separator = aChar;
64 }
65
66 public void setConverter(Converter aConverter) {
67 converter = aConverter;
68 }
69
70
71 public void setValues(Object aValue) {
72 value = aValue;
73 }
74
75
76 public String execute() {
77 if (value == null) {
78 return ERROR;
79 } else {
80 values = new ArrayList();
81
82 if (separator != null) {
83 StringTokenizer tokens = new StringTokenizer(value.toString(), separator);
84
85 while (tokens.hasMoreTokens()) {
86 String token = tokens.nextToken().trim();
87 if (converter != null) {
88 try {
89 Object convertedObj = converter.convert(token);
90 values.add(convertedObj);
91 }
92 catch(Exception e) {
93 _log.warn("unable to convert ["+token+"], skipping this token, it will not appear in the generated iterator", e);
94 }
95 }
96 else {
97 values.add(token);
98 }
99 }
100 } else {
101 values.add(value.toString());
102 }
103
104
105 if (count == 0) {
106 count = values.size();
107 }
108
109 return SUCCESS;
110 }
111 }
112
113
114 public boolean hasNext() {
115 return (value == null) ? false : ((currentCount < count) || (count == -1));
116 }
117
118 public Object next() {
119 try {
120 return values.get(currentCount % values.size());
121 } finally {
122 currentCount++;
123 }
124 }
125
126 public void remove() {
127 throw new UnsupportedOperationException("Remove is not supported in IteratorGenerator.");
128 }
129
130
131
132 /***
133 * Interface for converting each separated token into an Object of choice.
134 */
135 public static interface Converter {
136 Object convert(String token) throws Exception;
137 }
138 }