1 5 package com.opensymphony.webwork.util; 6 7 import com.opensymphony.xwork.util.OgnlValueStack; 8 9 import java.util.Comparator ; 10 11 12 20 public class Sorter { 21 23 public Comparator getAscending() { 24 return new Comparator () { 25 public int compare(Object o1, Object o2) { 26 if (o1 instanceof Comparable ) { 27 return ((Comparable ) o1).compareTo(o2); 28 } else { 29 String s1 = o1.toString(); 30 String s2 = o2.toString(); 31 32 return s1.compareTo(s2); 33 } 34 } 35 }; 36 } 37 38 public Comparator getAscending(final String anExpression) { 39 return new Comparator () { 40 private OgnlValueStack stack = new OgnlValueStack(); 41 42 public int compare(Object o1, Object o2) { 43 stack.push(o1); 45 46 Object v1 = stack.findValue(anExpression); 47 stack.pop(); 48 49 stack.push(o2); 51 52 Object v2 = stack.findValue(anExpression); 53 stack.pop(); 54 55 if (v1 == null) { 57 v1 = ""; 58 } 59 60 if (v2 == null) { 61 v2 = ""; 62 } 63 64 if (v1 instanceof Comparable && v1.getClass().equals(v2.getClass())) { 66 return ((Comparable ) v1).compareTo(v2); 67 } else { 68 String s1 = v1.toString(); 69 String s2 = v2.toString(); 70 71 return s1.compareTo(s2); 72 } 73 } 74 }; 75 } 76 77 public Comparator getComparator(String anExpression, boolean ascending) { 78 if (ascending) { 79 return getAscending(anExpression); 80 } else { 81 return getDescending(anExpression); 82 } 83 } 84 85 public Comparator getDescending() { 86 return new Comparator () { 87 public int compare(Object o1, Object o2) { 88 if (o2 instanceof Comparable ) { 89 return ((Comparable ) o2).compareTo(o1); 90 } else { 91 String s1 = o1.toString(); 92 String s2 = o2.toString(); 93 94 return s2.compareTo(s1); 95 } 96 } 97 }; 98 } 99 100 public Comparator getDescending(final String anExpression) { 101 return new Comparator () { 102 private OgnlValueStack stack = new OgnlValueStack(); 103 104 public int compare(Object o1, Object o2) { 105 stack.push(o1); 107 108 Object v1 = stack.findValue(anExpression); 109 stack.pop(); 110 111 stack.push(o2); 113 114 Object v2 = stack.findValue(anExpression); 115 stack.pop(); 116 117 if (v1 == null) { 119 v1 = ""; 120 } 121 122 if (v2 == null) { 123 v2 = ""; 124 } 125 126 if (v2 instanceof Comparable && v1.getClass().equals(v2.getClass())) { 128 return ((Comparable ) v2).compareTo(v1); 129 } else { 130 String s1 = v1.toString(); 131 String s2 = v2.toString(); 132 133 return s2.compareTo(s1); 134 } 135 } 136 }; 137 } 138 } 139 | Popular Tags |