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