NumberFilter.java

/*
 * Copyright 2019 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.blocks.model.filters;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.NumberExpression;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * Utility filtering for numeric types. Matches all constraints.
 *
 * @param <T> the generic type
 */
@Data
@Accessors(fluent = true)
public class NumberFilter<T extends Number & Comparable<?>> implements PropertyFilter<NumberFilter<T>, NumberExpression<T>> {

	private static final long serialVersionUID = -4548157369677617304L;

	/** Equal. */
	public Set<T> eq;
	
	/** Greater than or equal. */
	public T ge;

	/** Greater than. */
	public T gt;

	/** Less than. */
	public T lt;

	/** Less than or equal. */
	public T le;

	public NumberFilter() {
	}

	public NumberFilter(T ge, T le) {
		this.ge = ge;
		this.le = le;
	}

	@Override
	public boolean isEmpty() {
		return ge == null && gt == null && le == null && lt == null && CollectionUtils.isEmpty(eq);
	}

	@Override
	public NumberFilter<T> copyFilter() {
		return new NumberFilter<T>().eq(eq == null ? null : new HashSet<>(eq)).ge(ge).gt(gt).lt(lt).le(le);
	}

	/**
	 * Builds the query.
	 *
	 * @param val the val
	 * @return the boolean builder
	 */
	@Override
	public BooleanBuilder buildQuery(final NumberExpression<T> val) {
		final BooleanBuilder and = new BooleanBuilder();
		if (eq != null && !eq.isEmpty()) {
			and.and(val.isNotNull());
			and.and(val.in(eq));
		}
		if (gt != null) {
			and.and(val.isNotNull());
			and.and(val.gt(gt));
		}
		if (ge != null) {
			and.and(val.isNotNull());
			and.and(val.goe(ge));
		}
		if (lt != null) {
			and.and(val.isNotNull());
			and.and(val.lt(lt));
		}
		if (le != null) {
			and.and(val.isNotNull());
			and.and(val.loe(le));
		}
		return and;
	}

}