01: /*
02: * Copyright 2007 The Kuali Foundation.
03: *
04: * Licensed under the Educational Community License, Version 1.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.opensource.org/licenses/ecl1.php
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.kuali.core.web.comparator;
17:
18: import java.io.Serializable;
19: import java.util.Comparator;
20:
21: import org.apache.commons.lang.StringUtils;
22: import org.kuali.core.util.KualiDecimal;
23:
24: public class NumericValueComparator implements Serializable, Comparator {
25:
26: static final long serialVersionUID = 3449202365486147519L;
27:
28: private static final NumericValueComparator theInstance = new NumericValueComparator();
29:
30: public NumericValueComparator() {
31: }
32:
33: public static NumericValueComparator getInstance() {
34: return theInstance;
35: }
36:
37: public int compare(Object o1, Object o2) {
38:
39: // null guard. non-null value is greater. equal if both are null
40: if (null == o1 || null == o2) {
41: return (null == o1 && null == o2) ? 0 : ((null == o1) ? -1
42: : 1);
43: }
44:
45: String numericCompare1 = (String) o1;
46: String numericCompare2 = (String) o2;
47:
48: numericCompare1 = StringUtils.replace(numericCompare1, ",", "");
49: numericCompare1 = StringUtils.replace(numericCompare1, "$", "");
50: numericCompare1 = StringUtils.replace(numericCompare1,
51: " ", "");
52: numericCompare2 = StringUtils.replace(numericCompare2, ",", "");
53: numericCompare2 = StringUtils.replace(numericCompare2, "$", "");
54: numericCompare2 = StringUtils.replace(numericCompare2,
55: " ", "");
56:
57: // handle negatives
58: if (StringUtils.contains(numericCompare1, "(")) {
59: numericCompare1 = StringUtils.replace(numericCompare1, "(",
60: "");
61: numericCompare1 = StringUtils.replace(numericCompare1, ")",
62: "");
63: numericCompare1 = "-" + numericCompare1;
64: }
65:
66: if (StringUtils.contains(numericCompare2, "(")) {
67: numericCompare2 = StringUtils.replace(numericCompare2, "(",
68: "");
69: numericCompare2 = StringUtils.replace(numericCompare2, ")",
70: "");
71: numericCompare2 = "-" + numericCompare2;
72: }
73:
74: KualiDecimal k1 = null;
75: try {
76: k1 = new KualiDecimal(numericCompare1);
77: } catch (Throwable t) {
78: k1 = new KualiDecimal(0);
79: }
80:
81: KualiDecimal k2 = null;
82: try {
83: k2 = new KualiDecimal(numericCompare2);
84: } catch (Throwable t) {
85: k2 = new KualiDecimal(0);
86: }
87:
88: double d1 = k1.doubleValue();
89: double d2 = k2.doubleValue();
90:
91: return (d1 == d2) ? 0 : ((d1 < d2) ? -1 : 1);
92: }
93: }
|