com.github.thiagogarbazza.domainvalidation.javax.AbstracConstraintValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of domain-validation Show documentation
Show all versions of domain-validation Show documentation
A simple framework to write domain validation.
package com.github.thiagogarbazza.domainvalidation.javax;
import java.util.Collection;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import org.apache.commons.collections4.Closure;
import com.github.thiagogarbazza.domainvalidation.Validator;
import com.github.thiagogarbazza.domainvalidation.Violation;
import com.github.thiagogarbazza.domainvalidation.ViolationContext;
import static org.apache.commons.collections4.IterableUtils.forEach;
public abstract class AbstracConstraintValidator implements Validator {
protected ViolationContext violationContext = new ViolationContext();
private javax.validation.Validator constraintValidator;
public AbstracConstraintValidator() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
constraintValidator = factory.getValidator();
}
protected void constraintValidate(T entity) {
Collection> violations = constraintValidator.validate(entity);
forEach(violations, new ForEachConstraintViolation());
}
private class ForEachConstraintViolation implements Closure> {
@Override
public void execute(final ConstraintViolation violation) {
final String codigo = factoryCode(violation);
final String field = violation.getPropertyPath().toString();
final String message = violation.getMessage();
violationContext.add(field, new Violation(codigo, message));
}
private String factoryCode(final ConstraintViolation violation) {
final String name = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
return name.replaceAll("([^_A-Z])([A-Z])", "$1-$2").toLowerCase();
}
}
}