001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.beanutils;
019
020import java.io.Serializable;
021import java.util.Comparator;
022
023import org.apache.commons.collections.comparators.ComparableComparator;
024
025/**
026 * <p>
027 * This comparator compares two beans by the specified bean property.
028 * It is also possible to compare beans based on nested, indexed,
029 * combined, mapped bean properties. Please see the {@link PropertyUtilsBean}
030 * documentation for all property name possibilities.
031 *
032 * </p><p>
033 * <strong>Note:</strong> The BeanComparator passes the values of the specified
034 * bean property to a ComparableComparator, if no comparator is
035 * specified in the constructor. If you are comparing two beans based
036 * on a property that could contain "null" values, a suitable <code>Comparator</code>
037 * or <code>ComparatorChain</code> should be supplied in the constructor.
038 * Note that the passed in {@code Comparator} must be able to handle the
039 * passed in objects. Because the type of the property to be compared is not
040 * known at compile time no type checks can be performed by the compiler.
041 * Thus {@code ClassCastException} exceptions can be thrown if unexpected
042 * property values occur.
043 * </p>
044 *
045 * @param <T> the type of beans to be compared by this {@code Comparator}
046 */
047public class BeanComparator<T> implements Comparator<T>, Serializable {
048
049    private static final long serialVersionUID = 1L;
050
051    /**
052     * Method name to call to compare.
053     */
054    private String property;
055
056    /**
057     * BeanComparator will pass the values of the specified bean property to this Comparator. If your bean property is not a comparable or contains null values,
058     * a suitable comparator may be supplied in this constructor.
059     */
060    private final Comparator<?> comparator;
061
062    /**
063     * <p>Constructs a Bean Comparator without a property set.
064     * </p><p>
065     * <strong>Note</strong> that this is intended to be used
066     * only in bean-centric environments.
067     * </p><p>
068     * Until {@link #setProperty} is called with a non-null value.
069     * this comparator will compare the Objects only.
070     * </p>
071     */
072    public BeanComparator() {
073        this(null);
074    }
075
076    /**
077     * <p>Constructs a property-based comparator for beans.
078     * This compares two beans by the property
079     * specified in the property parameter. This constructor creates
080     * a <code>BeanComparator</code> that uses a <code>ComparableComparator</code>
081     * to compare the property values.
082     * </p>
083     *
084     * <p>Passing "null" to this constructor will cause the BeanComparator
085     * to compare objects based on natural order, that is
086     * <code>java.lang.Comparable</code>.
087     * </p>
088     *
089     * @param property String Name of a bean property, which may contain the
090     * name of a simple, nested, indexed, mapped, or combined
091     * property. See {@link PropertyUtilsBean} for property query language syntax.
092     * If the property passed in is null then the actual objects will be compared
093     */
094    public BeanComparator(final String property) {
095        this(property, ComparableComparator.getInstance());
096    }
097
098    /**
099     * Constructs a property-based comparator for beans.
100     * This constructor creates
101     * a BeanComparator that uses the supplied Comparator to compare
102     * the property values.
103     *
104     * @param property Name of a bean property, can contain the name
105     * of a simple, nested, indexed, mapped, or combined
106     * property. See {@link PropertyUtilsBean} for property query language
107     * syntax.
108     * @param comparator BeanComparator will pass the values of the
109     * specified bean property to this Comparator.
110     * If your bean property is not a comparable or
111     * contains null values, a suitable comparator
112     * may be supplied in this constructor.
113     */
114    public BeanComparator(final String property, final Comparator<?> comparator) {
115        setProperty(property);
116        if (comparator != null) {
117            this.comparator = comparator;
118        } else {
119            this.comparator = ComparableComparator.getInstance();
120        }
121    }
122
123    /**
124     * Compares two JavaBeans by their shared property.
125     * If {@link #getProperty} is null then the actual objects will be compared.
126     *
127     * @param  o1 Object The first bean to get data from to compare against
128     * @param  o2 Object The second bean to get data from to compare
129     * @return int negative or positive based on order
130     */
131    @Override
132    public int compare(final T o1, final T o2) {
133        if (property == null) {
134            // compare the actual objects
135            return internalCompare(o1, o2);
136        }
137        try {
138            final Object value1 = PropertyUtils.getProperty(o1, property);
139            final Object value2 = PropertyUtils.getProperty(o2, property);
140            return internalCompare(value1, value2);
141        } catch (final ReflectiveOperationException e) {
142            throw new IllegalArgumentException(e);
143        }
144    }
145
146    /**
147     * Two <code>BeanComparator</code>'s are equals if and only if
148     * the wrapped comparators and the property names to be compared
149     * are equal.
150     * @param  o Comparator to compare to
151     * @return whether the the comparators are equal or not
152     */
153    @Override
154    public boolean equals(final Object o) {
155        if (this == o) {
156            return true;
157        }
158        if (!(o instanceof BeanComparator)) {
159            return false;
160        }
161
162        final BeanComparator<?> beanComparator = (BeanComparator<?>) o;
163
164        if (!comparator.equals(beanComparator.comparator)) {
165            return false;
166        }
167        if (property == null) {
168            return beanComparator.property == null;
169        }
170        if (!property.equals(beanComparator.property)) {
171            return false;
172        }
173
174        return true;
175    }
176
177    /**
178     * Gets the Comparator being used to compare beans.
179     *
180     * @return the Comparator being used to compare beans
181     */
182    public Comparator<?> getComparator() {
183        return comparator;
184    }
185
186    /**
187     * Gets the property attribute of the BeanComparator
188     *
189     * @return String method name to call to compare.
190     * A null value indicates that the actual objects will be compared
191     */
192    public String getProperty() {
193        return property;
194    }
195
196    /**
197     * Hash code compatible with equals.
198     * @return the hash code for this comparator
199     */
200    @Override
201    public int hashCode() {
202        return comparator.hashCode();
203    }
204
205    /**
206     * Compares the given values using the internal {@code Comparator}.
207     * <em>Note</em>: This comparison cannot be performed in a type-safe way; so
208     * {@code ClassCastException} exceptions may be thrown.
209     *
210     * @param val1 the first value to be compared
211     * @param val2 the second value to be compared
212     * @return the result of the comparison
213     */
214    private int internalCompare(final Object val1, final Object val2) {
215        @SuppressWarnings("rawtypes")
216        final
217        // to make the compiler happy
218        Comparator c = comparator;
219        return c.compare(val1, val2);
220    }
221
222    /**
223     * Sets the method to be called to compare two JavaBeans
224     *
225     * @param property String method name to call to compare
226     * If the property passed in is null then the actual objects will be compared
227     */
228    public void setProperty(final String property) {
229        this.property = property;
230    }
231}