Hibernate Validator - Add a Dynamic ConstraintValidator - java

After learning about Hibernate Custom Validators, it has given me an interest in one topic, could I possibly create one base annotation wherein I could set which Validator to use?
#Target({ ElementType.FIELD })
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = validator().class)
public #interface CustomAnnotation {
public String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<? extends ConstraintValidator<? extends CustomAnnotation, Serializable>> validator();
}
So that I could use #CustomAnnotation in this manner
#CustomAnnotation(validator = CustomConstraintValidator.class, message = "validationMessage")
private Object fieldName;

I would not recommend it but you can do it roughly this way:
#Target({ ElementType.FIELD })
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = GenericValidatorBootstrapperValidator.class)
public #interface CustomAnnotation {
public String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<? extends ConstraintValidator<? extends CustomAnnotation, Serializable>> validator();
}
public class GenericValidatorBootstrapperValidator implements ConstraintValidator<CustomAnnotation, Object> {
private final ConstraintValidator validator;
#Override
public void initialize(CustomAnnotation constraintAnnotation) {
Class<? extends ConstraintValidator> validatorClass = constraintAnnotation.validator();
validator = validatorClass.newInstance();
validator.initialize( ... ); //TODO with what?
}
#Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return validator.isValid(value, context);
}
}
But again, prefer specific annotations, they are more expressive.
Edit
After your comment, I think what you want is to be able to set different validators based on the return type of the property
#CustomAnnotation
List<String> foo;
#CustomAnnotation
Table bar;
If that's the case, add several validators implementations in the #Constraint annotation.
#Target({ ElementType.FIELD })
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = {ListValidatorImpl.class, TableValidatorImpl.class, ...})
public #interface CustomAnnotation {
public String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class ListValidatorImpl implements ConstraintValidator<CustomAnnotation, List> {
#Override
public boolean isValid(List value, ConstraintValidatorContext context) {
}
}
public class TableValidatorImpl implements ConstraintValidator<CustomAnnotation, Table> {
#Override
public boolean isValid(Table value, ConstraintValidatorContext context) {
}
}
You can even link a contraint annotation with an implementation via the META/validation.xml file
<constraint-mappings
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.1.xsd"
xmlns="http://jboss.org/xml/ns/javax/validation/mapping" version="1.1">
<constraint-definition annotation="org.mycompany.CustomAnnotation">
<validated-by include-existing-validators="true">
<value>org.mycompany.EnumCustomValidatorImpl</value>
</validated-by>
</constraint-definition>
</constraint-mappings>
If you need something more flexible, I think my initial proposal would work. In the GenericValidatorBootstrapperValidator isValid method, you could call the right validator instance based on the object type of the value parameter (via instanceof for example).

Hibernate Validator also offers now a annotation #ScriptAssert which makes the implementation of custom validations easier and helps to avoid plenty lines of code.
Example of use:
#ScriptAssert(lang = "javascript",
script = "_this.capital.equals(_this.capital.toUpperCase)",
message = "capital has not Capital letters")
public class BigLetters {
private String capital;
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
}

I don't think you can implement a dynamic validator resolver on top of Hibernate Validator support. It's much better to have a dedicated set of annotation-validator pairs so when you annotate a field with a specific Validation annotation, it's clear what Validator will be used.

Related

Use #Value in javax Validator

I actually try to use a #Value into a java Validator, like this
#Value("${necessary-list}")
private List<String> list= new ArrayList<>();
#Override
public boolean isValid(String element, ConstraintValidatorContext constraintValidatorContext) {
return list.contains(element);
}
}
#Documented
#Constraint(validatedBy = CustomValidator.class)
#Target({ElementType.METHOD, ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
public #interface IsInList{
String message() default "test";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
I have put the annotation in a filed of the object "Item"
#Service
public class ItemValidator {
public void validateAddress(Item item) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Item>> constraintViolations = validator.validate(item);
if (isNotEmpty(constraintViolations)) {
throw new ConstraintViolationException(constraintViolations);
}
}
}
In configuration, i have try two method:
necessary-list: item1,item2,item3
necessary-list:
- item1
- item2
- item3
But doesn't work :/ And the #Value work in a Controller
Any tips for this?
I found the solution thanks to a person who unfortunately deleted his comment:
I have add in the configuration:
#Bean
public Validator validatorWithSpringContext(final AutowireCapableBeanFactory autowireCapableBeanFactory) {
ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure()
.constraintValidatorFactory(new SpringConstraintValidatorFactory(autowireCapableBeanFactory))
.buildValidatorFactory();
return validatorFactory.getValidator();
}
And just need to use the validatorWithSpringContext after that
Added on behalf of OP

How to get parameter of my Annotation as a validator?

I created my own Annotation to validate my REST parameter like this:
#PostMapping("/users")
#ResponseStatus(HttpStatus.CREATED)
public User createUser(#UserConstraint("CREATE_MODE") #RequestBody User user)
{ //code }
I got everything working where my ConstraintValidator is called to validate the User input, but I can't figure out how to get the parameter of my own annotation. I want to read the value CREATE_MODE.
#Constraint(validatedBy = UserValidator.class)
#Target(ElementType.PARAMETER )
#Retention(RetentionPolicy.RUNTIME)
public #interface UserConstraint {
String message() default "";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
public String value();
}
How to access??
public class UserValidator implements ConstraintValidator<UserConstraint, User> {
#Override
public boolean isValid(User user,
ConstraintValidatorContext context) {
???
}
#Override
public void initialize(UserConstraint annotation) {
// initialization, probably not needed
mode = annotation.value();
}

Custom parameter validator in spring boot

I have created a custom validator to validate the String passed to the function in converter. However, the custom validator is not being called. Am I missing something?
OperationParameter.java
#Documented
#Constraint(validatedBy = OperationParameterValidation.class)
#Target( { ElementType.PARAMETER
})
#Retention(RetentionPolicy.RUNTIME)
public #interface OperationParameter {
String message() default "Operation Parameter Invalid";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
OperationParameterValidation.java
public class OperationParameterValidation implements ConstraintValidator<OperationParameter, String> {
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
System.out.println("Validator called");
// validation process
// return true / false;
}
}
converter.java
#Component
public class StringToOperation implements Converter<String, Operation> {
#Override
public Operation convert(#Valid #OperationParameter String source) {
// Even I pass wrong String this function is executed successfully, and no print from validator
}
}
Service.java
public class Service {
#Autowired
ConversionService conversionService;
public void action() {
String action = "";
Operation addInsertOperation = conversionService.convert(action, Operation.class);
}
}
Set #SupportedValidationTarget(ValidationTarget.PARAMETERS) on validator class

Spring MVC custom validation issue with interface

I'm trying to do my own validation for category product. It is a task from
Spring MVC: Beginner's Guide book.
I have write a interface where i need to have validation for category where user cannot write diffrent category then is in set.
#Target({METHOD, FIELD, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = CategoryValidator.class)
#Documented
public #interface ICategory {
List<String> allowedCategories;
String message() default "{com.packt.webstore.validator.category.message}";
Class<?>[] groups() default {};
public abstract Class<? extends Payload>[] payload() default {};
}
In the task i should maintain a List<String> allowedCategory. But there i have a warning:
"The blank final field allowedCategories may not have been
initialized"
What am I doing wrong? Can't I use a field in interface? What should I do instead?
And below I show you mine implementation class of that interface:
#Component
public class CategoryValidator implements ConstraintValidator<IProductId, String>{
private List<String> allowedCategories;
public CategoryValidator() {
allowedCategories = getAllCategories(productService.getAllProducts());
}
private List<String> getAllCategories(List<Product> products) {
List<String> categories = new ArrayList<String>();
for (Product product : products) {
categories.add(product.getCategory());
}
return categories;
}
#Autowired
private IProductService productService;
public void initialize(IProductId constraintAnnotation) {
}
public boolean isValid(String value, ConstraintValidatorContext context) {
for (String category : allowedCategories) {
if(category.equals(value)) {
return true;
}
}
return false;
}
}

Spring 3.2 using cross parameter constraint

I'm trying to use a cross parameter constraint validator targeted on method parameters. The problem is the validation is not triggered for the method parameters instead it is triggered for the method return value.
I'm using Spring's LocalValidatorFactoryBean.
The JSR-303 provider is hibernate-validator 4.2.0.Final.
Spring version is 3.2.0.
Spring configuration excerpt :
<!-- JSR 303 validation -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
<property name="validator" ref="validator"/>
<bean>
Custom Constraint Validator:
#SupportedValidationTarget( ValidationTarget.PARAMETERS )
public class InstanceValidator implements
ConstraintValidator<InstanceCheck, Object[]> {
#Override
public void initialize(InstanceCheck constraintAnnotation) {}
#Override
public boolean isValid(Object[] value, ConstraintValidatorContext context) {
...
}
}
Annotation:
#Target( { METHOD, ANNOTATION_TYPE, CONSTRUCTOR } )
#Retention(RUNTIME)
#Constraint(validatedBy = InstanceValidator.class)
#Documented
public #interface InstanceCheck {
String message() default "{constraint.instance.not.allowed}";
public abstract Class<?>[] groups() default {};
public abstract Class<? extends Payload>[] payload() default {};
}
SomeService:
#Validated
public interface SomeService {
...
#InstanceCheck
public String addContent(String content) throws SomeException;
...
}
SomeServiceImpl :
#Service
public class SomeServiceImpl implements SomeService {
...
public String addContent(String content) throws SomeException {
// do something
}
...
}
: UPDATE :
I have tried adding the "validationAppliesTo" method for the annotation type (see below)
#Target( { METHOD, ANNOTATION_TYPE, CONSTRUCTOR } )
#Retention(RUNTIME)
#Constraint(validatedBy = InstanceValidator.class)
#Documented
public #interface InstanceCheck {
String message() default "{constraint.instance.not.allowed}";
public abstract Class<?>[] groups() default {};
public abstract Class<? extends Payload>[] payload() default {};
ConstraintTarget validationAppliesTo() default ConstraintTarget.PARAMETERS;
}
, and now I get the following error:
"Parameters starting with 'valid' are not allowed in a constraint."
Thanks in advance for any type of advice.
Cross-parameter constraints are only supported in Hibernate Validator 5.x (Bean Validation 1.1). Hibernate Validator 4.2 doesn't know how to deal with such constraints.
This is coding issue or temporary solution in Hibernate Validator.
Remove any field or method starting with 'valid' in custom Annotation.
In your example rename method -
ConstraintTarget validationAppliesTo() default ConstraintTarget.PARAMETERS;
to
ConstraintTarget xxxxxationAppliesTo() default ConstraintTarget.PARAMETERS;
Issue code ConstraintHelper-
private void assertNoParameterStartsWithValid(Class<? extends Annotation> annotationType) {
final Method[] methods = run( GetDeclaredMethods.action( annotationType ) );
for ( Method m : methods ) {
if ( m.getName().startsWith( "valid" ) && !m.getName().equals( VALIDATION_APPLIES_TO ) ) {
throw log.getConstraintParametersCannotStartWithValidException();
}
}
}

Categories

Resources