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.
Related
I have a Controller where I have the path veriable resourceId as type UUID like shown below.
#GetMapping(value = "{resourceId}")
public ResponseEntity<MyClass> findOneByResourceId(#PathVariable("resourceId") UUID resourceId) {
return new ResponseEntity<>(myService.findOneByResourceId(resourceId), HttpStatus.OK);
}
Everything works fine exception when Jackson is trying to deserialize an invalid UUID if such as "9e3b414a" an exception is thrown. Failed to convert value of type 'java.lang.String' to required type 'java.util.UUID'; nested exception is java.lang.IllegalArgumentException: Invalid UUID string: 9e3b414a
I have already a custom UuidDeserializer class (shown below) which I am using in other areas of my code successfully. I'd like to use this deserializer as well on the pathVariable.
public class UuidDeserializer extends JsonDeserializer<UUID> {
#Override
public UUID deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
var stringToValidate = jsonParser.getValueAsString().trim();
if (MyUtils.isStringInvalidUUID(stringToValidate)) {
throw new MyCustomException("Invalid UUID value")
}
return UUID.fromString(stringToValidate);
}
I cannot seem to get Spring to use this custom deserializer though on a path variable. I tried putting the #JsonDeserialize on the path variable but it doesn't work. HELP!
#GetMapping(value = "{resourceId}")
public ResponseEntity<MyClass> findOneByResourceId(#PathVariable("resourceId")
#JsonDeserialize(using = UuidDeserializer.class) UUID resourceId) {
return new ResponseEntity<>(myService.findOneByResourceId(resourceId), HttpStatus.OK);
}
You can create a custom validation annotation to check UUID, for example #UUIDValidation so first create our custom annotation.
#Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
#Retention(RUNTIME)
#Constraint(validatedBy = UUIDValidator.class)
#Documented
public #interface UUIDValidation {
String message() default "Mandatory fields missing";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Also its custom validator, let's call UUIDValidator that should implement ConstraintValidator and override the isValid method.
public class UUIDValidator implements ConstraintValidator<UUIDValidation, UUID> {
#Override
public boolean isValid(UUID value, ConstraintValidatorContext context) {
if (MyUtils.isStringInvalidUUID(value)) {
throw new MyCustomException("Invalid UUID value");
}
try {
UUID.fromString(value);
return Boolean.TRUE;
} catch (IllegalArgumentException ex) {
return Boolean.FALSE;
}
}
}
And we can call our custom validation annotation on the #PathVariable
#GetMapping(value = "{resourceId}")
public ResponseEntity<MyClass> findOneByResourceId(#PathVariable("resourceId")
#UUIDValidation UUID resourceId) {
return new ResponseEntity<>(myService.findOneByResourceId(resourceId), HttpStatus.OK);
}
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());
}
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