01: /*
02: * Copyright 2004 Outerthought bvba and Schaubroeck nv
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
05: * use this file except in compliance with the License. You may obtain a copy of
06: * the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
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, WITHOUT
12: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13: * License for the specific language governing permissions and limitations under
14: * the License.
15: */
16: package org.outerj.daisy.repository;
17:
18: import java.text.Collator;
19: import java.util.Comparator;
20: import java.util.Locale;
21:
22: /**
23: * A comparator which can be used sort the values of Daisy fields.
24: * Includes support for hierarchical values. String values are sorted
25: * using a locale-specific collator.
26: *
27: * <p>This is just an utility class.
28: */
29: public final class ValueComparator<T> implements Comparator<T> {
30: private final boolean ascending;
31: private final Collator collator;
32:
33: public ValueComparator(boolean ascending, Locale locale) {
34: this .ascending = ascending;
35: this .collator = Collator.getInstance(locale);
36: }
37:
38: public int compare(T value1, T value2) {
39: int result;
40: if (value1 instanceof String) {
41: result = collator.compare(value1, value2);
42: } else if (value1 instanceof Boolean) {
43: // Before java 1.5 Boolean was not Comparable. So a homebrewed solution was made where true < false
44: result = ((Boolean) value1).compareTo((Boolean) value2)
45: * -1;
46: } else if (value1 instanceof HierarchyPath) {
47: //result = ((HierarchyPath)value1).compareTo((HierarchyPath)value2,this);
48: result = 0;
49: HierarchyPath path1 = (HierarchyPath) value1;
50: HierarchyPath path2 = (HierarchyPath) value2;
51: int i = 0;
52: while (i < path1.getElements().length
53: && i < path2.getElements().length && result == 0) {
54: result = compare((T) path1.getElements()[i], (T) path2
55: .getElements()[i]);
56: i++;
57: }
58:
59: if (result == 0
60: && path1.getElements().length != path2
61: .getElements().length)
62: result = path1.getElements().length < path2
63: .getElements().length ? -1 : 1;
64: else
65: result = ascending ? result : result * -1;
66: } else if (value1 instanceof Comparable) {
67: result = ((Comparable<T>) value1).compareTo(value2);
68: } else {
69: throw new RuntimeException(
70: "Non-comparable type of object: "
71: + value1.getClass().getName());
72: }
73:
74: return ascending ? result : result * -1;
75: }
76: }
|