KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > beans > support > PropertyComparator


1 /*
2  * Copyright 2002-2005 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.beans.support;
18
19 import java.util.Arrays JavaDoc;
20 import java.util.Collections JavaDoc;
21 import java.util.Comparator JavaDoc;
22 import java.util.List JavaDoc;
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 /**
32  * PropertyComparator performs a comparison of two beans,
33  * evaluating the specified bean property via a BeanWrapper.
34  *
35  * @author Juergen Hoeller
36  * @author Jean-Pierre Pawlak
37  * @since 19.05.2003
38  * @see org.springframework.beans.BeanWrapper
39  */

40 public class PropertyComparator implements Comparator JavaDoc {
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     /**
50      * Create a new PropertyComparator for the given SortDefinition.
51      * @see MutableSortDefinition
52      */

53     public PropertyComparator(SortDefinition sortDefinition) {
54         this.sortDefinition = sortDefinition;
55     }
56
57     /**
58      * Create a PropertyComparator for the given settings.
59      * @param property the property to compare
60      * @param ignoreCase whether upper and lower case in String values should be ignored
61      * @param ascending whether to sort ascending (true) or descending (false)
62      */

63     public PropertyComparator(String JavaDoc property, boolean ignoreCase, boolean ascending) {
64         this.sortDefinition = new MutableSortDefinition(property, ignoreCase, ascending);
65     }
66
67     /**
68      * Return the SortDefinition that this comparator uses.
69      */

70     public final SortDefinition getSortDefinition() {
71         return sortDefinition;
72     }
73
74
75     public int compare(Object JavaDoc o1, Object JavaDoc o2) {
76         Object JavaDoc v1 = getPropertyValue(o1);
77         Object JavaDoc v2 = getPropertyValue(o2);
78         if (this.sortDefinition.isIgnoreCase() && (v1 instanceof String JavaDoc) && (v2 instanceof String JavaDoc)) {
79             v1 = ((String JavaDoc) v1).toLowerCase();
80             v2 = ((String JavaDoc) v2).toLowerCase();
81         }
82
83         int result;
84         
85         // Put an object with null property at the end of the sort result.
86
try {
87             if (v1 != null) {
88                 result = (v2 != null ? ((Comparable JavaDoc) v1).compareTo(v2) : -1);
89             }
90             else {
91                 result = (v2 != null ? 1 : 0);
92             }
93         }
94         catch (RuntimeException JavaDoc 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     /**
105      * Get the SortDefinition's property value for the given object.
106      * @param obj the object to get the property value for
107      * @return the property value
108      */

109     private Object JavaDoc getPropertyValue(Object JavaDoc obj) {
110         // If a nested property cannot be read, simply return null
111
// (similar to JSTL EL). If the property doesn't exist in the
112
// first place, let the exception through.
113
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     /**
125      * Sort the given List according to the given sort definition.
126      * <p>Note: Contained objects have to provide the given property
127      * in the form of a bean property, i.e. a getXXX method.
128      * @param source the input List
129      * @param sortDefinition the parameters to sort by
130      * @throws java.lang.IllegalArgumentException in case of a missing propertyName
131      */

132     public static void sort(List JavaDoc source, SortDefinition sortDefinition) throws BeansException {
133         if (StringUtils.hasText(sortDefinition.getProperty())) {
134             Collections.sort(source, new PropertyComparator(sortDefinition));
135         }
136     }
137
138     /**
139      * Sort the given source according to the given sort definition.
140      * <p>Note: Contained objects have to provide the given property
141      * in the form of a bean property, i.e. a getXXX method.
142      * @param source input source
143      * @param sortDefinition the parameters to sort by
144      * @throws java.lang.IllegalArgumentException in case of a missing propertyName
145      */

146     public static void sort(Object JavaDoc[] 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