1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.struts2.util;
22
23 import java.util.Comparator;
24
25 import com.opensymphony.xwork2.util.ValueStack;
26 import com.opensymphony.xwork2.util.ValueStackFactory;
27
28
29 /***
30 * Sorters. Utility sorters for use with the "sort" tag.
31 *
32 * @see org.apache.struts2.views.jsp.iterator.SortIteratorTag
33 * @see SortIteratorFilter
34 */
35 public class Sorter {
36
37 public Comparator getAscending() {
38 return new Comparator() {
39 public int compare(Object o1, Object o2) {
40 if (o1 instanceof Comparable) {
41 return ((Comparable) o1).compareTo(o2);
42 } else {
43 String s1 = o1.toString();
44 String s2 = o2.toString();
45
46 return s1.compareTo(s2);
47 }
48 }
49 };
50 }
51
52 public Comparator getAscending(final String anExpression) {
53 return new Comparator() {
54 private ValueStack stack = ValueStackFactory.getFactory().createValueStack();
55
56 public int compare(Object o1, Object o2) {
57
58 stack.push(o1);
59
60 Object v1 = stack.findValue(anExpression);
61 stack.pop();
62
63
64 stack.push(o2);
65
66 Object v2 = stack.findValue(anExpression);
67 stack.pop();
68
69
70 if (v1 == null) {
71 v1 = "";
72 }
73
74 if (v2 == null) {
75 v2 = "";
76 }
77
78
79 if (v1 instanceof Comparable && v1.getClass().equals(v2.getClass())) {
80 return ((Comparable) v1).compareTo(v2);
81 } else {
82 String s1 = v1.toString();
83 String s2 = v2.toString();
84
85 return s1.compareTo(s2);
86 }
87 }
88 };
89 }
90
91 public Comparator getComparator(String anExpression, boolean ascending) {
92 if (ascending) {
93 return getAscending(anExpression);
94 } else {
95 return getDescending(anExpression);
96 }
97 }
98
99 public Comparator getDescending() {
100 return new Comparator() {
101 public int compare(Object o1, Object o2) {
102 if (o2 instanceof Comparable) {
103 return ((Comparable) o2).compareTo(o1);
104 } else {
105 String s1 = o1.toString();
106 String s2 = o2.toString();
107
108 return s2.compareTo(s1);
109 }
110 }
111 };
112 }
113
114 public Comparator getDescending(final String anExpression) {
115 return new Comparator() {
116 private ValueStack stack = ValueStackFactory.getFactory().createValueStack();
117
118 public int compare(Object o1, Object o2) {
119
120 stack.push(o1);
121
122 Object v1 = stack.findValue(anExpression);
123 stack.pop();
124
125
126 stack.push(o2);
127
128 Object v2 = stack.findValue(anExpression);
129 stack.pop();
130
131
132 if (v1 == null) {
133 v1 = "";
134 }
135
136 if (v2 == null) {
137 v2 = "";
138 }
139
140
141 if (v2 instanceof Comparable && v1.getClass().equals(v2.getClass())) {
142 return ((Comparable) v2).compareTo(v1);
143 } else {
144 String s1 = v1.toString();
145 String s2 = v2.toString();
146
147 return s2.compareTo(s1);
148 }
149 }
150 };
151 }
152 }