All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dk.eobjects.metamodel.util.ObjectComparator Maven / Gradle / Ivy

/**
 *  This file is part of MetaModel.
 *
 *  MetaModel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MetaModel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MetaModel.  If not, see .
 */
package dk.eobjects.metamodel.util;

import java.sql.Time;
import java.util.Comparator;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;

/**
 * General purpose comparator to use for objects of various kinds. Prevents
 * NullPointerExceptions and tries to use comparable interface if available and
 * appropriate on incoming objects.
 */
public class ObjectComparator implements Comparator {

	private static Comparator _instance = new ObjectComparator();

	public static Comparator getComparator() {
		return _instance;
	}

	private ObjectComparator() {
	}

	public static Comparable getComparable(final Object o) {
		return new Comparable() {

			public int compareTo(Object o2) {
				return _instance.compare(o, o2);
			}

			@Override
			public String toString() {
				return "ObjectComparable[object=" + o + "]";
			}
		};
	}

	@SuppressWarnings("unchecked")
	public int compare(Object o1, Object o2) {
		if (o1 == null && o2 == null) {
			return -1;
		}
		if (o1 == null) {
			return -1;
		}
		if (o2 == null) {
			return 1;
		}
		if (o1 instanceof Comparable && o2 instanceof Comparable) {
			Comparable c1 = (Comparable) o1;
			Comparable c2 = (Comparable) o2;
			// We can only count on using the comparable interface if o1 and o2
			// are within of the same class or if one is a subclass of the other
			if (c1.getClass().isAssignableFrom(c2.getClass())) {
				return c1.compareTo(o2);
			}
			if (o2.getClass().isAssignableFrom(c1.getClass())) {
				return -1 * c2.compareTo(o1);
			}
		}
		if (o1 instanceof Number || o1 instanceof Number) {
			return NumberComparator.getComparator().compare(o1, o2);
		}
		if (isTimeBased(o1) || isTimeBased(o2)) {
			return TimeComparator.getComparator().compare(o1, o2);
		}
		return ToStringComparator.getComparator().compare(o1, o2);
	}

	private boolean isTimeBased(Object o) {
		if (o instanceof java.util.Date || o instanceof java.sql.Date
				|| o instanceof Time || o instanceof DateTime
				|| o instanceof LocalDate || o instanceof LocalTime) {
			return true;
		}
		return false;
	}

}