KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > content > comparators > OrderedCompositeComparator


1 package org.jahia.content.comparators;
2
3 import java.util.Comparator JavaDoc;
4 import java.util.ArrayList JavaDoc;
5 import java.util.Iterator JavaDoc;
6
7 /**
8  * <p>Title: A comparator that can contains multiple sub-comparators, that
9  * are used in sequence while objects are equal.</p>
10  * <p>Description: This comparator allows object to be sorted by multiple
11  * comparators, starting with the most relevant comparator first, and going
12  * down to the least important. This class is often sub-classed for different
13  * type of JahiaObjects descendants, in order to offer a framework for
14  * flexible comparator that reduce hard-coding.</p>
15  * <p>Copyright: Copyright (c) 2002</p>
16  * <p>Company: Jahia Ltd</p>
17  * @author Serge Huber
18  * @version 1.0
19  */

20
21 public class OrderedCompositeComparator implements Comparator JavaDoc {
22
23     private static org.apache.log4j.Logger logger =
24         org.apache.log4j.Logger.getLogger(OrderedCompositeComparator.class);
25
26     ArrayList JavaDoc orderedComparators = new ArrayList JavaDoc();
27
28     public OrderedCompositeComparator() {
29     }
30
31     public void addComparator(Comparator JavaDoc comparator) {
32         orderedComparators.add(comparator);
33     }
34
35     public void addComparator(int index, Comparator JavaDoc comparator) {
36         orderedComparators.add(index, comparator);
37     }
38
39     public int compare(Object JavaDoc o1, Object JavaDoc o2) {
40         if (orderedComparators.size() < 1) {
41             logger.warn("No configured comparators in ordered comparator, returning objects by toString comparison");
42             return o1.toString().compareTo(o2.toString());
43         }
44         Iterator JavaDoc comparatorIter = orderedComparators.iterator();
45         int curCompareResult = 0;
46         while (comparatorIter.hasNext()) {
47             Comparator JavaDoc curComparator = (Comparator JavaDoc) comparatorIter.next();
48             curCompareResult = curComparator.compare(o1, o2);
49             if (curCompareResult != 0) {
50                 return curCompareResult;
51             }
52         }
53         return curCompareResult;
54     }
55
56     public boolean equals(Object JavaDoc obj) {
57         if (obj instanceof OrderedCompositeComparator) {
58             OrderedCompositeComparator otherComparator = (OrderedCompositeComparator) obj;
59             return orderedComparators.equals(otherComparator.orderedComparators);
60         } else {
61             return false;
62         }
63     }
64
65 }
Popular Tags