View Javadoc

1   package net.sf.mmapps.commons.bridge;
2   
3   import org.mmbase.bridge.Field;
4   import org.mmbase.bridge.Node;
5   
6   import java.util.Comparator;
7   
8   /***
9    * Comparator two nodes based on the string value in the specified field.
10   */
11  public class NodeFieldComparator implements Comparator<Node> {
12     protected String field;
13     protected boolean ascending = true;
14  
15     /***
16      * Basic constructor.
17      *
18      * @param field the node field to compare the nodes on
19      */
20     public NodeFieldComparator(String field) {
21        this(field, true);
22     }
23  
24     /***
25      * Basic constructor.
26      *
27      * @param field the node field to compare the nodes on
28      * @param ascending sort the list ascending or descending
29      */
30     public NodeFieldComparator(String field, boolean ascending) {
31        this.field = field;
32        this.ascending = ascending;
33     }
34  
35     /***
36      * Two external source objects are said to be equal only when the two type fields match. The
37      * objects to compare can be of type <code>Node</code>.
38      *
39      * @param o1 the first external source node.
40      * @param o2 the first external source node
41      *
42      * @return a negative integer, zero, or a positive integer as the first argument is less than,
43      *         equal to, or greater than the second.
44      */
45     public int compare(Node n1, Node n2) {
46  
47        int fieldType = n1.getNodeManager().getField(field).getType();
48        int result = 0;
49  
50        switch (fieldType) {
51           case Field.TYPE_INTEGER:
52              result = n1.getIntValue(field) - n2.getIntValue(field);
53  
54              break;
55  
56           case Field.TYPE_STRING: default:
57              result = n1.getStringValue(field).compareTo(n2.getStringValue(field));
58        }
59  
60        if (ascending) {
61           return result;
62        } else {
63           return -result;
64        }
65     }
66  }