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