001/*
002 * Stallion Core: A Modern Web Framework
003 *
004 * Copyright (C) 2015 - 2016 Stallion Software LLC.
005 *
006 * This program is free software: you can redistribute it and/or modify it under the terms of the
007 * GNU General Public License as published by the Free Software Foundation, either version 2 of
008 * the License, or (at your option) any later version. This program is distributed in the hope that
009 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
011 * License for more details. You should have received a copy of the GNU General Public License
012 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
013 *
014 *
015 *
016 */
017
018package io.stallion.reflection;
019
020import java.io.Serializable;
021import java.util.Comparator;
022
023import static io.stallion.utils.Literals.*;
024import static io.stallion.Context.*;
025
026/**
027 * A comparator that compares objects based on the passed in property name, using
028 * PropertyUtils to look up the parameter.
029 *
030 * @param <T>
031 */
032public class PropertyComparator<T> implements Comparator<T> {
033    private String propertyName = "";
034    public PropertyComparator(String propertyName) {
035        this.propertyName = propertyName;
036    }
037
038    @Override
039    public int compare(T o1, T o2) {
040        if (o1 == null || o2 == null) {
041            return 0;
042        }
043        Comparable val1 = (Comparable)PropertyUtils.getPropertyOrMappedValue(o1, propertyName);
044        Comparable val2 = (Comparable)PropertyUtils.getPropertyOrMappedValue(o2, propertyName);
045        if (val1 == null && val2 == null) {
046            return 0;
047        } else if (val1 == null) {
048            return 1;
049        } else if (val2 == null) {
050            return -1;
051        }
052
053        return val1.compareTo(val2);
054    }
055}