1 16 17 package org.springframework.beans.support; 18 19 import java.util.Arrays ; 20 import java.util.Collections ; 21 import java.util.Comparator ; 22 import java.util.List ; 23 24 import org.apache.commons.logging.Log; 25 import org.apache.commons.logging.LogFactory; 26 27 import org.springframework.beans.BeanWrapperImpl; 28 import org.springframework.beans.BeansException; 29 import org.springframework.util.StringUtils; 30 31 40 public class PropertyComparator implements Comparator { 41 42 protected final Log logger = LogFactory.getLog(getClass()); 43 44 private final SortDefinition sortDefinition; 45 46 private final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(false); 47 48 49 53 public PropertyComparator(SortDefinition sortDefinition) { 54 this.sortDefinition = sortDefinition; 55 } 56 57 63 public PropertyComparator(String property, boolean ignoreCase, boolean ascending) { 64 this.sortDefinition = new MutableSortDefinition(property, ignoreCase, ascending); 65 } 66 67 70 public final SortDefinition getSortDefinition() { 71 return sortDefinition; 72 } 73 74 75 public int compare(Object o1, Object o2) { 76 Object v1 = getPropertyValue(o1); 77 Object v2 = getPropertyValue(o2); 78 if (this.sortDefinition.isIgnoreCase() && (v1 instanceof String ) && (v2 instanceof String )) { 79 v1 = ((String ) v1).toLowerCase(); 80 v2 = ((String ) v2).toLowerCase(); 81 } 82 83 int result; 84 85 try { 87 if (v1 != null) { 88 result = (v2 != null ? ((Comparable ) v1).compareTo(v2) : -1); 89 } 90 else { 91 result = (v2 != null ? 1 : 0); 92 } 93 } 94 catch (RuntimeException ex) { 95 if (logger.isWarnEnabled()) { 96 logger.warn("Could not sort objects [" + o1 + "] and [" + o2 + "]", ex); 97 } 98 return 0; 99 } 100 101 return (this.sortDefinition.isAscending() ? result : -result); 102 } 103 104 109 private Object getPropertyValue(Object obj) { 110 try { 114 this.beanWrapper.setWrappedInstance(obj); 115 return this.beanWrapper.getPropertyValue(this.sortDefinition.getProperty()); 116 } 117 catch (BeansException ex) { 118 logger.info("PropertyComparator could not access property - treating as null for sorting", ex); 119 return null; 120 } 121 } 122 123 124 132 public static void sort(List source, SortDefinition sortDefinition) throws BeansException { 133 if (StringUtils.hasText(sortDefinition.getProperty())) { 134 Collections.sort(source, new PropertyComparator(sortDefinition)); 135 } 136 } 137 138 146 public static void sort(Object [] source, SortDefinition sortDefinition) throws BeansException { 147 if (StringUtils.hasText(sortDefinition.getProperty())) { 148 Arrays.sort(source, new PropertyComparator(sortDefinition)); 149 } 150 } 151 152 } 153 | Popular Tags |