18579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshowardpackage autotest.common.table;
28579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward
38579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshowardimport autotest.common.table.DataSource.SortSpec;
48579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward
58579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshowardimport com.google.gwt.json.client.JSONObject;
68579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward
78579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshowardimport java.util.Comparator;
88579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward
98579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshowardpublic class JSONObjectComparator implements Comparator<JSONObject> {
108579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward    SortSpec[] sortSpecs;
11589cc78019a41fa293d7583a3c1b6dfca42da41bjamesren
128579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward    public JSONObjectComparator(SortSpec[] specs) {
136cff4ad7aa317bab05ab9dc1249dbea652944750showard        sortSpecs = new SortSpec[specs.length];
146cff4ad7aa317bab05ab9dc1249dbea652944750showard        System.arraycopy(specs, 0, sortSpecs, 0, specs.length);
158579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward    }
168579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward
178579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward    public int compare(JSONObject arg0, JSONObject arg1) {
188579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward        int compareValue = 0;
198579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward        for (SortSpec sortSpec : sortSpecs) {
208579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward            String key0 = arg0.get(sortSpec.getField()).toString().toLowerCase();
218579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward            String key1 = arg1.get(sortSpec.getField()).toString().toLowerCase();
228579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward            compareValue = key0.compareTo(key1) * sortSpec.getDirectionMultiplier();
238579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward            if (compareValue != 0) {
2402ed4bd47471fe77270e5507a7f9759955b3753cshoward                return compareValue;
258579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward            }
268579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward        }
27589cc78019a41fa293d7583a3c1b6dfca42da41bjamesren
28589cc78019a41fa293d7583a3c1b6dfca42da41bjamesren        // the given sort keys were all equal, but we'll ensure we're consistent with
2902ed4bd47471fe77270e5507a7f9759955b3753cshoward        // JSONObject.equals()
3002ed4bd47471fe77270e5507a7f9759955b3753cshoward        if (arg0.equals(arg1)) {
3102ed4bd47471fe77270e5507a7f9759955b3753cshoward            return 0;
3202ed4bd47471fe77270e5507a7f9759955b3753cshoward        }
3302ed4bd47471fe77270e5507a7f9759955b3753cshoward        // arbitrary (but consistent) ordering in this case
3402ed4bd47471fe77270e5507a7f9759955b3753cshoward        return arg0.hashCode() > arg1.hashCode() ? 1 : -1;
358579ea343f8d4c74b44d5b5cb2df3ef7552b2f6eshoward    }
36589cc78019a41fa293d7583a3c1b6dfca42da41bjamesren}
37