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
Related
There is an annotation that should ideally throw an exception if the entity by id is not found for different controllers.
Annotation:
#Target({ElementType.METHOD, ElementType.PARAMETER})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Constraint(validatedBy = CheckExistHandler.class)
public #interface CheckExist {
Class<?> entityClass();
String message() default "Entity with specified id does not exist!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
validator sketches:
#Component
public class CheckExistHandler implements ConstraintValidator<CheckExist, Long> {
#PersistenceContext
private EntityManager entityManager;
#Override
public boolean isValid(Long value, ConstraintValidatorContext context) {
if (value != 0 && entityManager.find(Topic.class, value) != null) {
return true;
} else {
return false;
}
}
}
Method for tests from one controller:
#GetMapping("/{topicId}")
public ResponseEntity<TopicDto> getTopicById(#CheckExist(entityClass = Topic.class) #PathVariable("topicId") Long topicId) {
if (!topicService.isExistByKey(topicId)) {
throw new NotFoundException("topic not found");
}
return new ResponseEntity<>(topicMapper.toDto(topicService.getByKey(topicId)), HttpStatus.OK);
}
In this regard, questions:
How to isolate a class from an annotation in a validator using reflection in order to correctly use the EntityManager?
How to throw an exception without getting 500?
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
I know how to validate #PathVariable from https://stackoverflow.com/a/35404423/4800811
and it worked as expected with standard annotations but not with the customized one using a Repository bean. Maybe the bean is not initialized and I end up with NullPointerException when accessing the end point has #PathVariable validated. So how to get that work?
My Controller:
#RestController
#Validated
public class CustomerGroupController {
#PutMapping(value = "/deactive/{id}")
public HttpEntity<UpdateResult> deactive(#PathVariable #CustomerGroupEmpty String id) {
}
}
My custom validator:
public class CustomerGroupEmptyValidator implements ConstraintValidator<CustomerGroupEmpty, String>{
#Autowired
private CustomerRepository repository;
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
// NullPointerException here (repository == null)
if (value!=null && !repository.existsByCustomerGroup(value)) {
return false;
}
return true;
}
}
My Custom Annotation:
#Documented
#Constraint(validatedBy = CustomerGroupEmptyValidator.class)
#Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
#Retention(RetentionPolicy.RUNTIME)
public #interface CustomerGroupEmpty {
String message() default "The customer group is not empty.";
Class<?>[] groups() default {};
Class<? extends Payload> [] payload() default {};
}
code in this post is correct, only mistake is that validator need to override initialize method as well. Probably user123 incorrect configure repository bean, the simply way to check this is define it manually in configuration class
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;
}
}
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.