Custom Jackson Deserializer For Path Variable In API Controller - java

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);
}

Related

how to avoid displaying rejected value if spring validation is failed at request bean validation

From below log we can see rejected value is display user data(example: User PII data with some special characters)
[Field error in object 'Customer' on field 'FirstName': rejected value [robert% steve];
So we tried to use #ControllerAdvice, MethodArgumentNotValidException and customize default error msg to show defined error msg.
But somehow this approach is not working for us with feature testcases. So do there any configuration not to display rejected value? or to show rejected value with masking?
thanks.
I believe I have found the right solution here. I was not sure that "rejected value" throws MethodArgumentNotValidException. Once I verified that, other things fall into the right place.
Cause:
Spring already has a base class ResponseEntityExceptionHandler which handles MethodArgumentNotValidException specifically using handleMethodArgumentNotValid() method. So your method in #ControllerAdvice class is never called.
Solution:
Override ResponseEntityExceptionHandler.handleMethodArgumentNotValid() method & add your own custom logic there.
Sample code:
#RestControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String, String> error = Map.of("message", "Field value not valid.");
return handleExceptionInternal(ex, error, headers, HttpStatus.BAD_REQUEST, request);
}
}
You can set your own custom validation annotation, set your own validation rules and rejection message:
#Documented
#Constraint(validatedBy = MyValidator.class)
#Target( { ElementType.METHOD, ElementType.FIELD }) // set the desired context
#Retention(RetentionPolicy.RUNTIME)
public #interface MyValidation {
String message() default "Validation error! Not going to display rejected value.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
You can also set multiple validators in the #Constraint, and they will run consecutively.
The validator:
public class MyValidator implements
ConstraintValidator<MyValidation, String> { // here you set the validated field type, e.g. String
#Override
public void initialize(MyValidation value) {
}
#Override
public boolean isValid(String value,
ConstraintValidatorContext cxt) {
... // some validation logic
return true/false;
}
}
Then simply add your annotation to the validated field. You can even change the message at that point:
#MyValidation(message = "Error!")
String validField;
For more deep-dive info, you can check https://www.baeldung.com/spring-mvc-custom-validator
If you'd like to see validation exceptions logged, but without the field values, you can add your own HandlerExceptionResolver that'll log your MethodArgumentNotValidException the way you need. Here's an example:
#EnableWebMvc
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
int beforeDefaultExceptionResolver = resolvers.size() - 1;
resolvers.add(beforeDefaultExceptionResolver, new DefaultHandlerExceptionResolver() {
#Override
protected String buildLogMessage(Exception ex, HttpServletRequest request) {
if (ex instanceof MethodArgumentNotValidException validationEx) {
// example, modified from org.springframework.web.bind.MethodArgumentNotValidException#getMessage
StringBuilder sb = new StringBuilder("Validation failed for argument [")
.append(validationEx.getParameter().getParameterIndex()).append("] in ")
.append(validationEx.getParameter().getExecutable().toGenericString());
BindingResult bindingResult = validationEx.getBindingResult();
if (bindingResult.getErrorCount() > 1) {
sb.append(" with ").append(bindingResult.getErrorCount()).append(" errors");
}
sb.append(": ");
for (ObjectError error : bindingResult.getAllErrors()) {
sb.append('[');
if (error instanceof FieldError fieldError) {
sb.append("Field error in object '" + fieldError.getObjectName() + "' on field '" + fieldError.getField() + "'");
}
else {
sb.append(error);
}
sb.append("] ");
}
return sb.toString();
}
return super.buildLogMessage(ex, request);
}
});
}
}
If you don't want to see validation exceptions logged at all, just set the following loggers' level to ERROR in your application.yml:
logging:
level:
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver: error
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver: error
You can create an #InitBinder for that, then validate your field before hand over :
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.addValidators(new FirstNameValidate());
}
public class FirstNameValidate implements Validator {
#Override
public boolean supports(Class<?> arg0) {
// code implementation ...
}
#Override
public void validate(Object target, Errors errors) {
// code implementation ...
}
}

Pass custom parameter to ConstraintValidator

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.

How to customize Bean Validations ConstraintViolationException?

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))

How do I use a custom validator with dropwizard?

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

Spring File uploading. Require file to be present

I have simple controller method which receives file:
#ResponseBody
public MyDto createProduct(MyDto dto, #RequestParam(value = "file") MultipartFile file) {
}
The problem is that Spring doesn't throw exception if user didn't chose file in form. But I need to be sure that user chose some file. I tried to add required = true but it didn't help (moreover is by default set to true)
Actually Spring throws exception only if my form doesn't contain parameter named file at all:
Required MultipartFile parameter 'file' is not present
But if parameter present and file is not chose in HTML form then there is no exception.
How to solve this problem?
Thanks
You can push your MultipartFile file as a property of your DTO and write a custom validation annotation e.g. #FilePresent. Your signature would than be something like
public MyDto createProduct(#Validated MyDto dto, BindingResult result)
your would annotate your file property inside MyDto
#FilePresent
private MultipartFile file;
Your custom validation code would be something like:
The #FilePresent annotation
#Documented
#Retention(RUNTIME)
#Constraint(validatedBy = {FilePresentMultipartFileValidator.class})
#Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
public #interface FilePresent {
String message() default "{your.package.FilePresent.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value() default "true";
}
Custom Validator
public class FilePresentMultipartFileValidator implements ConstraintValidator<FilePresent, MultipartFile> {
#Override
public void initialize(FilePresent constraintAnnotation) {
//NOOP
}
#Override
public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
return !(value == null || value.isEmpty());
}
}
the final move is to have a ValidationMessages.properties file on the classpath (and/or its localized equivalents) having the key your.package.FilePresent.message with the message value you choose

Categories