1 16 package com.blandware.atleap.webapp.taglib.core.grid.util; 17 18 import org.apache.commons.beanutils.PropertyUtils; 19 20 import java.util.Comparator ; 21 22 30 public class EntityFieldComparator implements Comparator { 31 32 34 36 39 protected String property; 40 41 45 protected int order = 1; 46 47 50 public EntityFieldComparator() { 51 } 52 53 58 public EntityFieldComparator(String property) { 59 this.property = property; 60 } 61 62 78 public int compare(Object o1, Object o2) { 79 if ( o1 == null ) { 80 throw new NullPointerException ("First argument must not be null"); 81 } 82 83 if ( o2 == null ) { 84 throw new NullPointerException ("Second argument must not be null"); 85 } 86 87 if ( property == null ) { 90 if ( o1 instanceof Comparable && o2 instanceof Comparable ) { 91 Comparable c1 = (Comparable ) o1; 92 Comparable c2 = (Comparable ) o2; 93 return order * c1.compareTo(c2); 94 } else { 95 return 0; 96 } 97 } 98 99 Object p1 = null; 100 Object p2 = null; 101 try { 102 p1 = PropertyUtils.getProperty(o1, property); 103 } catch ( Exception e ) { 104 throw new IllegalArgumentException ("Exception " + e.getClass().getName() + " with message '" + e.getMessage() + "' while trying to obtain value of property '" + property + "' from instance of " + o1.getClass().getName()); 105 } 106 107 try { 108 p2 = PropertyUtils.getProperty(o2, property); 109 } catch ( Exception e ) { 110 throw new IllegalArgumentException ("Exception " + e.getClass().getName() + " with message '" + e.getMessage() + "' while trying to obtain value of property '" + property + "' from instance of " + o2.getClass().getName()); 111 } 112 113 if ( p1 == null && p2 == null ) { 115 return 0; 116 } else if ( p1 == null && p2 != null ) { 117 return -1 * order; 118 } else if ( p1 != null & p2 == null ) { 119 return order; 120 } 121 122 if ( !(p1 instanceof Comparable ) ) { 123 throw new ClassCastException ("Value of property '" + property + "' must implement java.lang.Comparable interface"); 124 } 125 126 Comparable c1 = (Comparable ) p1; 127 Comparable c2 = (Comparable ) p2; 128 129 return order * (c1.compareTo(c2)); 130 } 131 132 136 public void reverseOrder() { 137 order = -order; 138 } 139 140 } 141 | Popular Tags |