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.Collections;
26 import java.util.Comparator;
27 import java.util.Iterator;
28 import java.util.List;
29
30 import com.opensymphony.xwork2.Action;
31 import com.opensymphony.xwork2.util.logging.LoggerFactory;
32
33
34 /***
35 * A bean that takes a source and comparator then attempt to sort the source
36 * utilizing the comparator. It is being used in SortIteratorTag.
37 *
38 * @see org.apache.struts2.views.jsp.iterator.SortIteratorTag
39 */
40 public class SortIteratorFilter extends IteratorFilterSupport implements Iterator, Action {
41
42 Comparator comparator;
43 Iterator iterator;
44 List list;
45
46
47 Object source;
48
49
50 public void setComparator(Comparator aComparator) {
51 this.comparator = aComparator;
52 }
53
54 public List getList() {
55 return list;
56 }
57
58
59 public void setSource(Object anIterator) {
60 source = anIterator;
61 }
62
63
64 public String execute() {
65 if (source == null) {
66 return ERROR;
67 } else {
68 try {
69 if (!MakeIterator.isIterable(source)) {
70 LoggerFactory.getLogger(SortIteratorFilter.class.getName()).warn("Cannot create SortIterator for source " + source);
71
72 return ERROR;
73 }
74
75 list = new ArrayList();
76
77 Iterator i = MakeIterator.convert(source);
78
79 while (i.hasNext()) {
80 list.add(i.next());
81 }
82
83
84 Collections.sort(list, comparator);
85 iterator = list.iterator();
86
87 return SUCCESS;
88 } catch (Exception e) {
89 LoggerFactory.getLogger(SortIteratorFilter.class.getName()).warn("Error creating sort iterator.", e);
90
91 return ERROR;
92 }
93 }
94 }
95
96
97 public boolean hasNext() {
98 return (source == null) ? false : iterator.hasNext();
99 }
100
101 public Object next() {
102 return iterator.next();
103 }
104
105 public void remove() {
106 throw new UnsupportedOperationException("Remove is not supported in SortIteratorFilter.");
107 }
108 }