001
014
015 package com.liferay.util;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
019
020 import java.lang.reflect.InvocationTargetException;
021
022 import java.util.Comparator;
023
024 import org.apache.commons.beanutils.PropertyUtils;
025
026
030 public class PropertyComparator implements Comparator<Object> {
031
032 public PropertyComparator(String propertyName) {
033 this(new String[] {propertyName}, true, false);
034 }
035
036 public PropertyComparator(
037 String propertyName, boolean ascending, boolean caseSensitive) {
038
039 this(new String[] {propertyName}, ascending, caseSensitive);
040 }
041
042 public PropertyComparator(String[] propertyNames) {
043 this(propertyNames, true, false);
044 }
045
046 public PropertyComparator(
047 String[] propertyNames, boolean ascending, boolean caseSensitive) {
048
049 _propertyNames = propertyNames;
050 _ascending = ascending;
051 _caseSensitive = caseSensitive;
052 }
053
054 @Override
055 public int compare(Object obj1, Object obj2) {
056 try {
057 for (String propertyName : _propertyNames) {
058 Object property1 = PropertyUtils.getProperty(
059 obj1, propertyName);
060 Object property2 = PropertyUtils.getProperty(
061 obj2, propertyName);
062
063 if (!_ascending) {
064 Object temp = property1;
065
066 property1 = property2;
067 property2 = temp;
068 }
069
070 if (property1 instanceof String) {
071 int value = 0;
072
073 if (_caseSensitive) {
074 value = property1.toString().compareTo(
075 property2.toString());
076 }
077 else {
078 value = property1.toString().compareToIgnoreCase(
079 property2.toString());
080 }
081
082 if (value != 0) {
083 return value;
084 }
085 }
086
087 if (property1 instanceof Comparable<?>) {
088 int value = ((Comparable<Object>)property1).compareTo(
089 property2);
090
091 if (value != 0) {
092 return value;
093 }
094 }
095 }
096 }
097 catch (IllegalAccessException iae) {
098 _log.error(iae.getMessage());
099 }
100 catch (InvocationTargetException ite) {
101 _log.error(ite.getMessage());
102 }
103 catch (NoSuchMethodException nsme) {
104 _log.error(nsme.getMessage());
105 }
106
107 return -1;
108 }
109
110 private static Log _log = LogFactoryUtil.getLog(PropertyComparator.class);
111
112 private boolean _ascending;
113 private boolean _caseSensitive;
114 private String[] _propertyNames;
115
116 }