001 /*
002 * Copyright 2002-2004 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005 * use this file except in compliance with the License. You may obtain a copy of
006 * the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations under
014 * the License.
015 */
016 package org.springframework.rules.constraint;
017
018 import java.util.Comparator;
019
020 import org.springframework.util.comparator.ComparableComparator;
021 import org.springframework.util.comparator.NullSafeComparator;
022
023 /**
024 * Abstract helper superclass for binary predicates involved in comparison
025 * operations.
026 *
027 * @author Keith Donald
028 */
029 public abstract class ComparisonBinaryPredicate extends AbstractBinaryConstraint {
030
031 private static final NullSafeComparator COMPARATOR = new NullSafeComparator(new ComparableComparator(), true);
032
033 private Comparator comparator;
034
035 /**
036 * Creates a comparing binary predicate which operates on
037 * <code>Comparable</code> objects.
038 */
039 protected ComparisonBinaryPredicate() {
040
041 }
042
043 /**
044 * Creates a comparing binary predicate which compares using the provided
045 * <code>Comparator</code>.
046 *
047 * @param comparator
048 * the comparator, may be null
049 */
050 protected ComparisonBinaryPredicate(Comparator comparator) {
051 if (!(comparator instanceof NullSafeComparator)) {
052 this.comparator = new NullSafeComparator(comparator, true);
053 }
054 else {
055 this.comparator = comparator;
056 }
057 }
058
059 /**
060 * Returns the comparator which is used to compare the arguments
061 *
062 * @return null if no custom comparator is defined
063 */
064 public Comparator getComparator() {
065 return comparator;
066 }
067
068 /**
069 * Tests two arguments against a comparsion expression. This method
070 * delegates to the {@link testCompareResult(int)}template method to
071 * evaluate the compareTo result.
072 *
073 * @param argument1
074 * the first argument
075 * @param argument2
076 * the second argument
077 * @return true if the comparsion result passes, false otherwise
078 */
079 public boolean test(Object argument1, Object argument2) {
080 if (getComparator() != null)
081 return testCompareResult(getComparator().compare(argument1, argument2));
082
083 return testCompareResult(COMPARATOR.compare(argument1, argument2));
084 }
085
086 /**
087 * Template method for evaluating the compare result.
088 *
089 * @param result
090 * The compare result
091 * @return true or false
092 */
093 protected abstract boolean testCompareResult(int result);
094
095 }