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

dk.apaq.framework.criteria.rules.BetweenRule Maven / Gradle / Ivy

/*
 * CrudContainer
 * Copyright (C) 2011 by Apaq
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see .
 */
package dk.apaq.framework.criteria.rules;

import dk.apaq.framework.criteria.Rule.FiltrationItem;



/**
 *
 */
public class BetweenRule extends AbstractSpecificRule {

    private final T startValue;
    private final T endValue;

    public BetweenRule(String propertyId, T startValue, T endValue) {
        super(propertyId);
        this.startValue = startValue;
        this.endValue = endValue;
    }

    public T getStartValue() {
        return startValue;
    }

    public T getEndValue() {
        return endValue;
    }

    @Override
    public boolean passesRule(FiltrationItem item) {
        Object value = item.getFiltrationProperty(this.getPropertyId());
        int comparedToStart = compareValues(value, startValue);
        int comparedToEnd = compareValues(value, endValue);

        return comparedToStart >= 0 && comparedToEnd <= 0;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected int compareValues(Object value1, Object value2) {
        if (null == value1) {
            return null == value2 ? 0 : -1;
        } else if (null == value2) {
            return 1;
        } else if (value1 instanceof Comparable
                && value2.getClass().isAssignableFrom(value1.getClass())) {
            return ((Comparable) value1 ).compareTo(value2);
        } else if (value1 instanceof Number && value2 instanceof Number) {
            Double tmp = ((Number)value1).doubleValue();
            return tmp.compareTo(((Number)value2).doubleValue());
        }
        throw new IllegalArgumentException("Could not compare the arguments: "
                + value1 + ", " + value2);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy