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

com.github.ldeitos.validators.MultiTargetValidator Maven / Gradle / Ivy

Go to download

Extension for BeanValidation API to provide CDI compatible ConstraintValidatorFactory, easy way to set parameters on message constraint and easy API to add non properties file message sources, like DB, external modules, mainframe routines, etc. This version is Java 17 and JakartaEE 10 compatible.

There is a newer version: 3.0
Show newest version
package com.github.ldeitos.validators;

import static java.lang.String.format;
import static java.util.Arrays.asList;
import static org.apache.commons.collections15.CollectionUtils.exists;

import java.lang.annotation.Annotation;
import java.security.InvalidParameterException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.collections15.Predicate;

abstract class MultiTargetValidator implements ConstraintValidator {

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		boolean ret = true;

		if (value != null) {
			ret = validate(value);
		}

		return ret;
	}

	private boolean validate(Object value) {
		final Class valueClass = value.getClass();
		boolean ret = true;
		Predicate> assignableFrom = getMustValidatePredicate(valueClass);

		if (exists(asList(getTargetClasses()), assignableFrom)) {
			ret = doValidation(value);
		} else {
			throw new InvalidParameterException(format(
			    "Invalid target type [%s] to be validated by [%s] validator.", valueClass.getName(), this
			        .getClass().getName()));
		}

		return ret;
	}

	protected Predicate> getMustValidatePredicate(final Class valueClass) {
		Predicate> assignableFrom = new Predicate>() {
			@Override
			public boolean evaluate(Class arg0) {
				return arg0.isAssignableFrom(valueClass);
			}
		};
		return assignableFrom;
	}

	protected abstract boolean doValidation(Object value);

	protected abstract Class[] getTargetClasses();
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy