org.kiwiproject.validation.RangeValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kiwi Show documentation
Show all versions of kiwi Show documentation
Kiwi is a utility library. We really like Google's Guava, and also use Apache Commons.
But if they don't have something we need, and we think it is useful, this is where we put it.
package org.kiwiproject.validation;
import static com.google.common.base.Verify.verify;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import static org.kiwiproject.validation.InternalKiwiValidators.TEMPLATE_REQUIRED;
import static org.kiwiproject.validation.InternalKiwiValidators.toComparableOrNull;
import lombok.extern.slf4j.Slf4j;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* Validator for @{@link Range}.
*/
@Slf4j
public class RangeValidator implements ConstraintValidator {
private static final String TEMPLATE_BETWEEN = "{org.kiwiproject.validation.Range.between.message}";
private static final String TEMPLATE_LESS_THAN_OR_EQ = "{org.kiwiproject.validation.Range.lessThanOrEq.message}";
private static final String TEMPLATE_GREATER_THAN_OR_EQ = "{org.kiwiproject.validation.Range.greaterThanOrEq.message}";
private Range range;
@Override
public void initialize(Range constraintAnnotation) {
this.range = constraintAnnotation;
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
Validity validity;
try {
validity = checkNull(value, context);
if (validity == Validity.CONTINUE) {
//noinspection unchecked,rawtypes
validity = checkMinMax((Comparable) value, context);
}
} catch (Exception e) {
KiwiValidations.addError(context, "unknown validation error");
logWarning(value, e);
validity = Validity.INVALID;
}
return validity == Validity.VALID;
}
private Validity checkNull(Object value, ConstraintValidatorContext context) {
if (isNull(value)) {
if (range.allowNull()) {
return Validity.VALID;
}
KiwiValidations.addError(context, TEMPLATE_REQUIRED);
return Validity.INVALID;
}
return Validity.CONTINUE;
}
private Validity checkMinMax(Comparable
© 2015 - 2024 Weber Informatics LLC | Privacy Policy