Given multiple REST resources to gather order information.
/order/{id}
/order/{id}/positions
/order/{id}/invoice
/order/{id}/shipment
Within the a Srping Boot 2 application it's implemented across multiple controllers, e.g. OrderController, InvoiceController, etc.
Currently every controller uses the OrderRepository to ensure the the order with the given id exists. Otherwise it throws an exception. It's always the same replicated code.
#RestController
public class OrderController {
// ...
#GetMapping("order/{id}")
public Order getCustomer(#PathVariable final Integer id) {
return this.orderRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("order not found"));
}
}
Does the framework provide a callback to write the order id check just once?
I found the AntPathMatcher but it seems not the right way, since it provides just an boolean interface.
This is usually a good case for bean validation. While there is already builtin support for many cases of validation (#Size, #NotNull, ...), you can also write your own custom constraints.
First of all, you need to define an annotation to validate your ID, for example:
#Documented
#Constraint(validatedBy = OrderIdValidator.class)
#Target({PARAMETER})
#Retention(RUNTIME)
public #interface ValidOrderId {
String message() default "Invalid order ID";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Since your order ID is always a parameter for your controller mappings, you could use ElementType.PARAMETER to only allow the annotation for method parameters.
The next step is to add the #Constraint annotation to it and point to a custom validator class (eg. OrderIdValidator):
#Component
public class OrderIdValidator implements ConstraintValidator<ValidOrderId, Integer> {
private OrderRepository repository;
public OrderIdValidator(OrderRepository repository) {
this.repository = repository;
}
#Override
public boolean isValid(Integer id, ConstraintValidatorContext constraintValidatorContext) {
return repository.existsById(id);
}
}
By implementing the isValid method, you can check whether or not the order exists. If it doesn't exist, an exception will be thrown and the message() property of the #ValidOrderId annotation will be used as a message.
The last step is to add the #Validated annotation to all of your controllers, and to add the #ValidOrderId annotation to all order ID parameters, for example:
#Validated // Add this
#RestController
public class OrderController {
#GetMapping("order/{id}")
public Order getCustomer(#PathVariable #ValidOrderId final Integer id) { // Add #ValidOrderId
// Do stuff
}
}
If you prefer to use a different response status for your validations, you could always add a class annotated with the #ControllerAdvice annotation and use the following method:
#ExceptionHandler(ConstraintViolationException.class)
public void handleConstraints(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value());
}
Related
I have the following classes used for validating a password.
public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword, String> {
#Override
public void initialize(ValidPassword constraintAnnotation) {
}
#Override
public boolean isValid(String password, ConstraintValidatorContext context) {
PasswordValidator validator = new PasswordValidator(Arrays.asList(
// at least 8 characters
new LengthRule(8, 30),
// at least one upper-case character
new CharacterRule(EnglishCharacterData.UpperCase, 1),
// at least one lower-case character
new CharacterRule(EnglishCharacterData.LowerCase, 1),
// at least one digit character
new CharacterRule(EnglishCharacterData.Digit, 1),
// at least one symbol (special character)
new CharacterRule(EnglishCharacterData.Special, 1),
// no whitespace
new WhitespaceRule()
));
RuleResult result = validator.validate(new PasswordData(password));
if (result.isValid()) {
return true;
}
List<String> messages = validator.getMessages(result);
String messageTemplate = messages.stream().collect(Collectors.joining(","));
context.buildConstraintViolationWithTemplate(messageTemplate)
.addConstraintViolation()
.disableDefaultConstraintViolation();
return false;
}
}
#Documented
#Constraint(validatedBy = PasswordConstraintValidator.class)
#Target( {ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.LOCAL_VARIABLE, ElementType.TYPE_PARAMETER, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface ValidPassword {
String message() default "Invalid Password";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Adding the #ValidPassword annotation for a field in a class works.
However when I try adding the annotation to a parameter in a function, the validator is never called/reached.
public void resetUserPassword(Integer userId, #ValidPassword String newPassword) {
}
Also adding the annotation here doesn't work either:
#PostMapping("/user/resetPassword/{id}")
public ResponseEntity<?> resetUserPassword(#PathVariable("userId") Integer userId, #Valid #ValidPassword #RequestBody String newPassword) {
userService.resetUserPassword(userId, newPassword)
return ResponseEntity.ok().build();
}
I don't think I am missing any dependencies, so I'm not sure where the problem is.
The annotation #Validated defined at class-level annotation is
necessary to trigger method validation for a specific bean to begin
with.
Also in other words
The #Validated annotation is a class-level annotation that we can
use to tell Spring to validate parameters that are passed into a
method of the annotated class.
Refer this link https://github.com/spring-projects/spring-framework/issues/11039 to find out the origin for #Validated
Usage:
As you have the below method with your custom annotation #ValidPassword with your #Valid
#PostMapping("/user/resetPassword/{id}")
public ResponseEntity<?> resetUserPassword(#PathVariable("userId") Integer userId, #Valid #ValidPassword #RequestBody String newPassword) {
userService.resetUserPassword(userId, newPassword)
return ResponseEntity.ok().build();
}
#Valid
It is used for enabling the whole object validation As you can see in the below example the #NotNull #Size and #NotBlank will be invoked to validate the user input or supplied values present in the object.
Eg:
public class DummyUser{
#NotNull
#Size(min =8)
private String password;
#NotBlank
private String username;
}
#Validated
But, As per your case you want your custom validation to be invoked on the method parameter , Hence you need to provide the hint to spring to invoke the custom validation. So, to do that you have declare the #Validated annotation at class level in your controller.
So these are the reasons for your validation to start working after you have annotated your controller class with #Validated annotation.
You need to add #Validated annotation on the controller class or another class, where you want to validate method parameter with your custom validation.
There was an explanation in spring-boot 2.1.x documentation about this kind of method-level validation, but I couldn't find it in current 2.7.x docs.
In general it's a spring-framework feature, that can be found here. In a non-boot project you'll need to create a bean of type MethodValidationPostProcessor manually, but spring-boot auto-configurates this bean for you - the autoconfiguration can be found in ValidationAutoConfiguration class.
According to java-docs of MethodValidationPostProcessor, target classes with JSR-303 constraint annotated methods need to be annotated with Spring's #Validated annotation at the type level, for their methods to be searched for inline constraint annotations. Validation groups can be specified through #Validated as well. By default, JSR-303 will validate against its default group only.
I'm working on this springboot application where I need to do some validations on values passed from http call and I'm using class level validation as explained here.
I'm using somethink like this:
#ValidRequest
public class EventRequest {
String date;
}
Response create(#Valid EventRequest request) {
..
}
Response update(Long entityId, #Valid EventRequest request) {
...
}
public class ValidRequestValidator
implements ConstraintValidator<ValidRequest, EventRequest> {
In the class ValidRequestValidator, where I implement the ConstraintValidator interface, I need to check if there is another Event entity in the database that meet some conditions on field date. When I want to create a new entity is simple, I perform a query, but when I need to update I need to exclude the entity I'm currently trying to update.
Is there a way to pass entityId parameter to #ValidRequest custom validator?
I know a way is to add the field entityId to the class EventRequest, but I would like to maintain this separation because entityId is coming from a query parameter.
Thank for your help!
Additional to the field-specific(Single Parameter Constraint) you can implement constraint for the whole method(Cross-Parameter Constraint). This will provide ability to pass all parameters of certain method to validator.
Annotation definition:
Annotation used two validators and can be applied to the Method or Type.
#Constraint(validatedBy = {ValidRequestMethodValidator.class, ValidRequestTypeValidator.class})
#Target({ ElementType.METHOD, ElementType.TYPE })
#Retention(RetentionPolicy.RUNTIME)
public #interface ValidRequest {
String message() default "Request is invalid!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
ConstraintTarget validationAppliesTo() default ConstraintTarget.IMPLICIT;
}
Constraint Validator which will handle single parameter:
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ValidRequestTypeValidator implements ConstraintValidator<ValidRequest, EventRequest> {
#Override
public boolean isValid(EventRequest request, ConstraintValidatorContext constraintValidatorContext) {
// logic here
return false;
}
}
Constraint Validator which will handle all parameters of specific method:
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraintvalidation.SupportedValidationTarget;
import javax.validation.constraintvalidation.ValidationTarget;
#SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class ValidRequestMethodValidator implements ConstraintValidator<ValidRequest, Object[]> {
#Override
public boolean isValid(Object[] objects, ConstraintValidatorContext constraintValidatorContext) {
Long entityId = null;
EventRequest eventRequest = null;
if (objects[0] instanceof Long) {
entityId = (Long) objects[0];
}
if (objects[0] instanceof EventRequest) {
eventRequest = (EventRequest) objects[0];
}
if (objects[1] instanceof EventRequest) {
eventRequest = (EventRequest) objects[1];
}
//logic here
return false;
}
}
Please note, we have to annotate the beans, which shall be validated, with #org.springframework.validation.annotation.Validated annotation to get method validators to work automatically.
Example of usage:
Mixed usage, #ValidRequest annotation defined on method and single parameter level.
#ValidRequest
public class EventRequest {
public String value;
}
#RestController
#Validated
public class Controller {
Response create(#Valid EventRequest request) {
return new Response();
}
#ValidRequest(validationAppliesTo = ConstraintTarget.PARAMETERS)
Response update(Long entityId, EventRequest request) {
return new Response();
}
}
For create method ValidRequestTypeValidator will be executed.
For update method ValidRequestMethodValidator will be executed.
2. Define annotation only for methods
#RestController
#Validated
public class Controller {
#ValidRequest(validationAppliesTo = ConstraintTarget.PARAMETERS)
Response create(EventRequest request) {
return new Response();
}
#ValidRequest(validationAppliesTo = ConstraintTarget.PARAMETERS)
Response update(Long entityId, EventRequest request) {
return new Response();
}
}
For create method ValidRequestMethodValidator will be executed with one element objects array
For update method ValidRequestMethodValidator will be executed with two elements objects array
3. Define annotation for a single parameter and method at the same time
#ValidRequest
public class EventRequest {
public String value;
}
#RestController
#Validated
public class Controller {
#ValidRequest(validationAppliesTo = ConstraintTarget.PARAMETERS)
Response update(Long entityId, #Valid EventRequest request) {
return new Response();
}
}
First will be executed single parameter validator ValidRequestTypeValidator.
If it will passed validation then second method validator ValidRequestMethodValidator will be executed.
Probably only one method-level validation will be sufficient to handle your issue. I described all variants, just for information maybe will be useful.
I want to validate the #RequestBody of an endpoint in my Spring #RestController. So I created a method like this:
#RequestMapping(value = ...)
public ResponseEntity<...> myPostMethod(#RequestBody MyBean myBean) throws Exception {
MyBean is decorated with a custom #Constraint and its respective validation logic is implemented on a ConstraintValidator class that I created. This validator has a method like:
#Override
public boolean isValid(MyBean value, ConstraintValidatorContext context) {
That's where all the validation logic takes place. When it fails, isValid returns false and I can use that context param to build a validation error message the way I want. In addition, myPostMethod also fails with an automatic (because I do not throw it myself) MethodArgumentNotValidException that I'm going to capture on a global handler in order to render a generic ResponseEntity. It all works as expected. The question is: how do I customize not only the validation error message, but also the whole ConstraintViolationException? I want to provide more data (from my business domain) inside the exception to render in the response body json.
I found the answer:
https://docs.jboss.org/hibernate/validator/5.4/api/org/hibernate/validator/constraintvalidation/HibernateConstraintValidatorContext.html#withDynamicPayload-java.lang.Object-
public boolean isValid(MyBean value, ConstraintValidatorContext constraintValidatorContext) {
HibernateConstraintValidatorContext context = constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class);
// (...)
context.buildConstraintViolationWithTemplate( "{foo}" )
.withDynamicPayload(anyAdditionalInfo)
.addConstraintViolation();
return false;
}
Let's assume that the additional parameter you wanted to pass is called myParam.
First, declare an accessor for that parameter in your Constraint interface;
public #interface MyConstraint {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String myParam() default "some.value";
}
Then in the ConstraintValidator, you could access these params like:
public class MyValidator implements ConstraintValidator<MyConstraint, String> {
private String myParam;
#Override
public void initialize(OpcoConstraint parameters) {
code = parameters.myParam();
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
HibernateConstraintValidatorContext hibernateContext = context.unwrap(
HibernateConstraintValidatorContext.class
);
// you can pass any object as the payload
hibernateContext.withDynamicPayload(Map.of("myParam", myParam));
}
}
If you catch the ConstraintViolationException from an exception handler and want to access the parameter from the Exception itself:
To retrieve ConstraintViolation (s) out of ConstraintViolationException use:
constraintViolationException.getConstraintViolations();
Then to retrieve the dynamic payload out of a ConstraintViolation:
(Map) ((ConstraintViolationImpl) constraintViolation).getDynamicPayload(Map.class))
I am newbie in Java world (came from .Net background). I created a RESTful service using Jersey framework. it has couple of methods. Following is the sample code snippet for Customer service. There are couple more services in my code.
#Path("/CustomerService")
public interface ICustomerService {
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/getCustomerInfo")
Response query(String constraints);
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/getCustomerDetails")
Response fetchDetails(String customerID);
}
I have some validation logic which I would like to perform at each API which is exposed to the client. I C# world we can define own validation logic. Something like following, This can be applied at method or controller level.
[MyValdationLogic()]
What is the equivalent in Java? How can I write code which can be applied at multiple places over the method.
Also I do not want to allow admin to play with that configuration. I found there is something called as filters but this gets configured in config file. admin can disable it.
You can create a Validator class and use that Validator class on your bean for validation. Although, the process is bit lengthy.
Following is one example of doing this -
Jersey Resource
#POST
#Path("/addEmp")
#Produces("text/plain")
public String doOrder(#BeanParam final #Valid Employee emp) {
// Some implementation here
}
Sample Bean -
Suppose, I want to apply validation on address i.e. either address or city or postcode must be there.
#Address
public final class Employee {
#FormDataParam("id")
private String id;
#FormDataParam("address")
private String address;
#FormDataParam("city")
private String city;
#FormDataParam("postcode")
private String postcode;
// Other member variables
// Getters and setters
}
Address Annotation -
Define custom Address Annotation
#Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
#Retention(RUNTIME)
#Constraint(validatedBy = AddressValidator.class)
#Documented
public #interface Address {
String message() default "Address required";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Validator Class -
Here is the validator class contains actual validation logic -
public class AddressValidator implements ConstraintValidator<Address, Employee> {
#Override
public boolean isValid(Employee emp, ConstraintValidatorContext constraintValidatorContext) {
// Check for at least one value
if((emp.getAddress() != null && !emp.getAddress().equals("") ||
(emp.getCity() != null && !emp.getCity().equals("")) ||
(emp.getPostcode() != null && !emp.getPostcode().equals("")))) {
return true;
}
return false;
}
public void initialize(Address emp) {
...
}
}
By this way, you can create reusable Validator class. Instead of taking Employee directly in this Validator class, you can take Object class or some parent class and then change the logic accordingly.
You can check more details in bean-validation
I have a REST api written by someone else in which the method that handles the request to a particular url accepts a bunch of parameters that are populated from path parameters.
#POST
#Path("/{classid}/{studentid}/details")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#SuppressWarnings("unchecked")
public Response processFile(#FormDataParam("sourceFile") InputStream aStream, #PathParam("classid") String classId, #PathParam("studentid") String studentId, #Context HttpServletRequest httpRequest) {
// Code to do stuff and return a response
}
The person who wrote this has used DropWizard and I have no previous experience working on it. I have the task of validating the studentId field by comparing it with values in the db. This would be pretty straightforward but I have been told to do it using a custom validator. I am pretty new to writing annotations but after much digging wrote an annotation like this,
#Target(ElementType.PARAMETER)
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Constraint(validatedBy = StudentIdValidator.StudentIdValidation.class)
public #interface StudentIdValidator {
String message() default "{Invalid Id}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class StudentIdValidation implements ConstraintValidator<StudentIdValidator, String> {
#Override
public void initialize(StudentIdValidator constraintAnnotation) {
System.out.println("Annotation initialize !!!!!!!!!");
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
// TODO Auto-generated method stub
System.out.println("Annotation called");
return false;
}
}
}
After this I added the annotation to the field I wanted to run the validation on like this,
public Response processFile(#FormDataParam("sourceFile") InputStream aStream, #PathParam("classid") String classId, #StudentIdValidator #PathParam("studentid") String studentId, #Context HttpServletRequest httpRequest)
Now the problem is that, when the I run/debug the code...this validator is not being called, also I have no idea how to get the value of studentId inside the studentId validation class. So I dug some more and added this to the application file
class MyApplication extends Application<MyConfiguration> {
........
#Override
public void run(MyConfiguration myConfiguration, Environment currentEnvironment) {
currentEnvironment.jersey().register(StudentIdValidator.class);
}
I am literally at the end of my wits. Any help will be very VERY appreciated. Sorry about the poor formatting.
this is pretty straight forward. I will paste my example here since I had it written up and I am lazy and don't want to take your fun experience away :)
Edit: I think your issue is that you didn't annotate your resource with #Valid
so here we go:
You are on the right track with the validator. These are mine:
public class CustomValidator implements ConstraintValidator<CustomValidation, String> {
#Override
public void initialize(CustomValidation constraintAnnotation) {
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
System.out.println("Validation called");
return false;
}
}
And this is the Annotation:
#Constraint(validatedBy = {CustomValidator.class})
#Target({ElementType.FIELD, ElementType.PARAMETER})
#Retention(value = RetentionPolicy.RUNTIME)
public #interface CustomValidation {
String message() default "Some message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
The application:
public class Application extends io.dropwizard.Application<Configuration>{
#Override
public void run(Configuration configuration, Environment environment) throws Exception {
MetricRegistry metrics = environment.metrics();
environment.jersey().register(new HelloResource(metrics));
}
public static void main(String[] args) throws Exception {
new Application().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
}
}
And the resource:
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class HelloResource {
private MetricRegistry service;
public HelloResource(MetricRegistry service) {
this.service = service;
}
#GET
public String hello() {
Timer timer = service.timer("test");
try(Context t = timer.time()) {
return "Hello World";
}
}
#GET
#Path("/test2")
public void test(#Valid #CustomValidation #QueryParam("arg") String test) {
System.out.println(test);
}
}
Don't mind the metrics, they have nothing to do with it. The important part is that you need to tell DW what you want to have validated.
In the resource, see the test method. I annotate the argument I need with #Valid (tells DW to validate) #CustomValidation (tells DW what validator to use).
This is not actually a Dropwizard feature, but rather a hibernate validator implementation.
The way it works under the hood is that hibernate creates the Validator class on the fly when requested by invoking the constructor. Now this works very fine if you have simple validation (like say comparing a string). If you need dependencies, then it gets slightly more tricky. I have an example for that as well, that you can read up on here:
With dropwizard validation, can I access the DB to insert a record
This example uses guice, but it demonstrates how you can hook your own creation mechanism into validation. That way you can control your validator creation and inject or initialise them with a datasource to access your database.
I hope that answers your questions,
Artur
Custom valdation in drop wizard are same as hibernate custom validators.
Follow the link : hibernate validator-customconstraints