Validate Resource in the POST method - java

I need to validate a Resource object with #NotBlank annotations in the POST method manually. Is there any way to validate Resource object using Jackson/Spring api. Not sure how to do it.
public class FileMetadataResource extends BaseResource {
#JsonProperty("title")
#NotBlank(groups = {default.class})
#Size(max = 60)
private String title;
#JsonProperty("description")
#Size(max = 255)
#NotBlank
private String description;
}
My custom HandlerMethodArgumentResolver populates the FileMetadataResource
#RequestMapping(method = RequestMethod.POST, consumes = "multipart/related")
#ResponseStatus(HttpStatus.CREATED)
public FileMetadataResource post(FileMetadataResource fileMetadataResource) {
//How to validate fileMetadataResource using jackson here
}
ANy help is appreciated.

Related

Spring Boot, How to Validation (#Notblank) json array in request

Hi everyone I have a question about validate json array request in Spring Boot
This controller
public ResponseEntity<BaseResponse> humanController(#RequestHeader Map<String, String> header,#Valid #RequestBody jsonRequest rqBody) throws ServiceException,Exception {
...
...
}
This jsonRequest Model Request
public class jsonRequest {
#NotBlank
#JsonProperty(value = "name")
private String name;
#NotBlank
#JsonProperty(value = "body")
private bodyModel[] body;
...
...
}
This bodyModel Request
public class bodyModel {
#NotBlank
#JsonProperty(value = "hands")
private String hands;
#NotBlank
#JsonProperty(value = "legs")
private String legs;
#NotBlank
#JsonProperty(value = "head")
private String head;
...
...
}
How can I validate (#Notblank) in bodyModel, I use #NotBlank It not work ?

Springboot BindingResult hasErrors is always false

I have tried all the answer I have found on internet and nothing seems to be working.
I have added hibernate-validation, spring validation but both are not working and bindingResult.haserrors() is always false.
Dependencies I am using currently in my project
javax.validation:validation-api:2.0.1.Final
org.hibernate.validator:hibernate-validator:6.0.18.Final
org.springframework.boot:spring-boot-starter-validation:2.1.13.RELEASE
com.github.java-json-tools:json-schema-validator:2.2.8
io.springfox:springfox-bean-validators:2.9.2
Controller
public String processRequest(
#ApiParam(value = "Input JSON",
required = true) #Valid #RequestBody MyClass myClass,
BindingResult results) {
if (results.hasErrors()) {
List<FieldError> fieldErrors = results.getFieldErrors();
throw new InvalidFieldException(fieldErrors);
}
}
MyClass
public class MyClass {
#NotBlank
#Size(min = 1, max = 80)
private String firstName;
#Size(max = 80)
private String middleName;
#NotBlank
#Size(min = 1, max = 80)
private String lastName;
}
I am call controller using this myClass Object
MyClass myClass =
MyClass.builder().firstName("linus").lastName("").build();
Can someone please help me?

Spring Boot Request body validation on same DTO used for different API

In my request body DTO, I want specific fields to be required for one of the API but not for another.
My request body:
#Data
class MyClass {
#NotNull
private String fullName;
#NotNull
private String firstName;
#NotNull
private String lastName;
}
I want fullName to be required for /api/v1 but not for /api/v2. I am using #Valid on request body from javax.validation.
You have to use Spring's #Validated, which is a variant of JSR-303's #Valid. This is used at the method-level:
Controller:
#RequestMapping(value = "apiV1Method")
public String apiV1Method(#Validated(Account. ValidationAPI1.class) MyClassDTO myClassDTO) {...}
#RequestMapping(value = "apiV2Method")
public String apiV2Method(#Validated(Account. ValidationAPI2.class) MyClassDTO myClassDTO) {...}
Object:
class MyClassDTO {
public interface ValidationAPI1 {}
public interface ValidationAPI2 {}
#NotNull(groups = {ValidationAPI1.class})
private String fullName;
#NotNull(groups = {ValidationAPI1.class, ValidationAPI2.class})
private String firstName;
#NotNull(groups = {ValidationAPI1.class, ValidationAPI2.class})
private String lastName;
...
}

Error org.springframework.web.HttpMediaTypeNotSupportedException

i have a problem with rest and method post on my controler i have this 2 class the first is user in my class user i have my class with the getters and setter and a default contructor because for the finally I would like use Hibernate .:
#Entity
#Table(name="Utilisateur") // mapping with hibernate (but not using in this situation)
public class User {
#Id
private long id;
#Column(name="nom")
private String nom;
#Column(name="prenom")
private String prenom;
#Column(name="admin")
private boolean admin;
#Column(name="actif")
private boolean actif;
#Column(name="logins")
private String logins;
#Column(name="email")
private String email;
#Column(name="naissance")
private String naissance;
#Column(name="pwd")
private String pwd;
#Column(name="compte")
private String compte;
public User(){
}
/*
with getter and setter.
*/
}
and my class controler (User controller) : is using for make the api principally post api .
#RestController
public class UserController {
#RequestMapping(
value="/api/greetings/post",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE
)
#ResponseBody
public ResponseEntity<User> getByEmail(#RequestBody User user){
if(user==null){
return new ResponseEntity<User>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
and i get this erreur I am using postman for make the query and in parameter of my query I send this Json query :
{"id":"3","nom":"Gille","prenom":"Laurent","admin":"1","actif":"0","logins":"gilaur","email":""toto#hotmail.com,"naissance":"1990/09/09","pwd":"gal","compte":"autre"}
And i get this error :
{"timestamp":1457906727481,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'text/plain;charset=UTF-8' not supported","path":"/api/greetings/post/"}
Thank you
you are change headers content-type application/json in Postman because you try set text/plain

Bean Validation and requested parameter in spring mvc

Is it possible to use validators for validation request parameters from javax.validation.constraints package in any way? I.e. like the following:
#Controller
public class test {
#RequestMapping("/test.htm")
public String test(#RequestParam("name") #NotNull String name)
{
return "index";
}
}
Use this way:
public class Comment{
#NotEmpty
#Length(max = 140)
private String text;
//Methods are omitted.
}
Now use #Valid in controller
#Controller
public class CommentController {
#RequestMapping(value = "/api/comment", method = RequestMethod.POST)
#ResponseBody
public Comment add(#Valid #RequestBody Comment comment) {
return comment;
}
}
When you are applying #Valid for Comment object in your cotroller,it will apply the validation mentioned in Comment class and its attribute like
#NotEmpty
#Length(max = 140)
private String text;
You can also check this out for little alternate way of doing:
http://techblogs4u.blogspot.in/2012/09/method-parameter-validation-in-spring-3.html
you can try this
#Controller
public class test {
#RequestMapping("/test.htm")
public String test(#RequestParam(value="name",required=true) String name)
{
return "index";
}
}

Categories