Strict validation of DTO in Spring Boot request body - spring

I have a Spring Boot RestController like this
public class MyRestController{
#RequestMapping(value = "/resources", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#ApiResponses(value = { #ApiResponse(code = 201, message = "Created",
response = Resource.class) })
#ResponseStatus( HttpStatus.CREATED )
public Resource createResource(#RequestBody Resource res){
}
#JsonIgnoreProperties(ignoreUnknown = false)
public class Resource{
private String resourceName;
private int value;
}
When I pass a json like this :
{
"unknownProperty": "test",
"value::100
}
I want an exception to be thrown since I have set #JsonIgnoreProperties(ignoreUnknown = false) but this is not happening. What is missing?

It's my understanding that ignored properties are meant to be ignored silently. If you specifically want to throw an exception on properties you're not expecting to see, then create a custom deserializer and ask your type to be serialized with it eg
#JsonDeserialize(using = MyCustomDeserializer.class) (on your type).
I believe your custom deserializer will need to extend JsonDeserializer<MyType>
To get the deserialization failure you're looking for you'll need to override deserialize() and in that create an object mapper and configure it as follows.
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

Could you add a bean to configure ObjectMapper:
#Bean
public ObjectMapper objectMapper() {
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
return om;
}

Related

FeignException com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.http.ResponseEntity`

Any Help please !!
I receive this error when I'm calling my endpoint which call Feign in the background :
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of
`org.springframework.http.ResponseEntity` (no Creators, like default constructor, exist): cannot deserialize
from Object value (no delegate- or property-based Creator)
at [Source: (BufferedReader); line: 1, column: 2]
This is my endpoint inside Controller :
#RestController
#RequestMapping(Routes.URI_PREFIX)
public class CartoController {
#Autowired
private ReadCartographyApiDelegate readCartographyApiDelegate;
#GetMapping(value = "/cartographies/{uid}", produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseWrapper<ReadCartographyResponse> readCarto(HttpServletRequest request,
#PathVariable(name = "uid") String uid) {
ResponseEntity<ReadCartographyResponse> result ;
try {
result = readCartographyApiDelegate.readCartography(uid);
}catch (Exception e){
throw new TechnicalException("Error during read Carto");
}
return responseWrapperWithIdBuilder.of(result.getBody());
}
}
Interface ReadCartographyApiDelegate generated automatically by openApi from yaml file :
#javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "...")
public interface ReadCartographyApiDelegate {
default Optional<NativeWebRequest> getRequest() {
return Optional.empty();
}
default ResponseEntity<ReadCartographyResponse> readCartography(String uid) {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
String exampleString = "null";
ApiUtil.setExampleResponse(request, "application/json", exampleString);
break;
}
}
});
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
}
This my ReadCartoApiDelegateImpl which implements ReadCartographyApiDelegate interface :
#Service
public class ReadCartographyApiDelegateImpl implements ReadCartographyApiDelegate {
private EcomGtmClient ecomGtmClient;
public ReadCartographyApiDelegateImpl(EcomGtmClient ecomGtmClient) {
this.ecomGtmClient = ecomGtmClient;
}
#Override
public ResponseEntity<ReadCartographyResponse> readCartography(String uid) {
ResponseEntity<ReadCartographyResponse> response = ecomGtmClient.readCartography(uid);
return response;
}
}
This is the feign client :
#FeignClient(name = "ecomGtmSvc", url = "http://localhost/")
public interface EcomGtmClient {
#GetMapping(value = "/read-carto/{uid}")
ResponseEntity<ReadCartographyResponse> readCartography(#PathVariable("uid") String uid);
}
The problem is that ResponseEntity (spring class) class doesn't contain default constructor which is needed during creating of instance. is there Any config to resolve this issue ?
If you want access to the body or headers on feign responses, you should use the feign.Response class. ResponseEntity does not work with feign because it is not meant to. I think it is best if you just return Response from your feign client method. You should then be able to pass the body to the ResponseEntity instance in the Controller.
What is your reason to even use the response-wrapper, i can't really figure that out from your code?
Sadly I couldn't find any documentation on the Response class, but here's the link to the source on GitHub.
https://github.com/OpenFeign/feign/blob/master/core/src/main/java/feign/Response.java
My Suggestion would be
#FeignClient(name = "ecomGtmSvc", url = "http://localhost/")
public interface EcomGtmClient {
#GetMapping(value = "/read-carto/{uid}")
ReadCartographyResponse readCartography(#PathVariable("uid") String uid);
}
#RestController
#RequestMapping(Routes.URI_PREFIX)
public class CartoController {
#Autowired
private ReadCartographyApiDelegate readCartographyApiDelegate;
#GetMapping(value = "/cartographies/{uid}", produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseWrapper<ReadCartographyResponse> readCarto(HttpServletRequest request,
#PathVariable(name = "uid") String uid) {
ReadCartographyResponse result ;
try {
result = readCartographyApiDelegate.readCartography(uid);
}catch (Exception e){
throw new TechnicalException("Error during read Carto");
}
// I don't know where you get the builder from, so I assume it does something import and is needed
return responseWrapperWithIdBuilder.of(result);
}
}
Of course you'd also have to change all intermediate classes.
The Response Output was the correct Object that I have to put, cause every time I need to check the status from my feign client endpoint to do différent logic
#FeignClient(name = "ecomGtmSvc", url = "http://localhost/")
public interface EcomGtmClient {
#GetMapping(value = "/read-carto/{uid}")
ReadCartographyResponse readCartography(#PathVariable("uid") String uid);
}

Creat a JSONObject : Spring boot

I would like to create a JSONObject :
#RequestMapping(value = "/test", method = RequestMethod.GET)
#ResponseBody
public JSONObject Test() {
JSONObject test = new JSONObject();
test.put("name","caroline");
return test;
}
it's giving me as a result :
{"map":{"name":"caroline"}}
But I was waiting for something like that :
{"name":"caroline"}
I don't know where is it the problem , I just followed this exemple
I tried with your code with a sample spring boot project and I get the error,
No converter for [class org.json.JSONObject]
The reason for this error is explained clearly here. To reiterate the answer, JSONObject classes don't have getters and hence the error. By default spring-boot starter web dependency has Jackson web support which can convert any POJO class to JSON object. So as the answer by #süleyman-can using a POJO is the right way to handle this.
In case, you can't use a POJO class because the fields in the response will be different for each request. For example, you have to send
{"a": "b"}
for one response and
{"c": "d"}
for another response, you can always use Map<String, String> like this,
#RequestMapping(value = "/test", method = RequestMethod.GET)
#ResponseBody
public Map<String, String> test() {
Map<String, String> test = new HashMap<>();
test.put("name","caroline");
return test;
}
and the response would come like this,
{"name":"caroline"}
I hope you are talking about org.json package
If you really want to use JSONObject to create your JSON, then the following code works. It's just that you can change the return type from JSONObject to String.
#RequestMapping(value = "/test", method = RequestMethod.GET)
#ResponseBody
public String Test() {
JSONObject test = new JSONObject();
test.put("name","caroline");
return test.toString();
}
you can try this
1- add this dependecy in pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
2- i have this class for example
public class Car {
private String color;
private String type;
// standard getters setters
}
2- Java Object to JSON
ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);
must result like it:
{"color":"yellow","type":"renault"}
3- JSON to Java Object
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Car car = objectMapper.readValue(json, Car.class);
You can do by creating a Class
class MyResponseClass {
private String name;
public MyResponseClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Initial:
#RestController
class MyController {
#GetMapping("/test")
public MyResponseClass getMyResponseClass() {
final MyResponseClass test = new MyResponseClass("caroline");
return test;
}
}
I suggest you read this article: Building an Application with Spring Boot

Springboot show error message for invalid date (YearMonth) formats: eg 2020-15

I have a project with Spring Boot and I want to show an error response if the given date format is incorrect.
The correct format is yyyy-MM (java.time.YearMonth) but I want to want to show a message if someone sends 2020-13, 2020-111 or 2020-1.
When I've added a custom validator the debugger goes in there with a valid request but not with an incorrect request. I also tried to use the message.properties with the typeMismatch.project.startdate=Please enter a valid date. but I also don't see that message in my response body.
It seems like the application does not understand my incorrect request and then always throws a BAD REQUEST with empty body, which is not strange because it is not a valid date.
Can someone explain me how I can show an errormessage in the response for these incorrect values?
Or is there no other way then use a String and convert that to the YearMonth object so I can show catch and show an error message?
Request object:
#Getter
#Setter
public class Project {
#NotNull(message = "mandatory")
#DateTimeFormat(pattern = "yyyy-MM")
private YearMonth startdate;
}
Controller:
#RestController
#RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class ProjectController {
#PostMapping(value = "/project", consumes = MediaType.APPLICATION_JSON_VALUE)
public Project newProject(#Valid #RequestBody Project newProject) {
return projectService.newProject(newProject);
}
}
ExceptionHandler:
#RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#SneakyThrows
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
headers.add("Content-Type", "application/json");
ObjectMapper mapper = new ObjectMapper();
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach(error -> {
String name;
if (error instanceof FieldError)
name = ((FieldError) error).getField();
else
name = error.getObjectName();
String errorMessage = error.getDefaultMessage();
errors.put(name, errorMessage);
});
return new ResponseEntity<>(mapper.writeValueAsString(errors), headers, status);
}
}
Okay, I made a solution which is workable for me.
I've added the solution below for people who find this thread in the future and has the same problem I had.
Create a custom validator with a simple regex pattern:
#Target({ FIELD })
#Retention(RUNTIME)
#Constraint(validatedBy = YearMonthValidator.class)
#Documented
public #interface YearMonthPattern {
String message() default "{YearMonth.invalid}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
public class YearMonthValidator implements ConstraintValidator<YearMonthPattern, String> {
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
Pattern pattern = Pattern.compile("^([0-9]{4})-([0-9]{2})$");
Matcher matcher = pattern.matcher(value);
try {
return matcher.matches();
} catch (Exception e) {
return false;
}
}
}
Update the request object:
#Getter
#Setter
public class Project {
#NotNull(message = "mandatory")
#YearMonthPattern
private String startdate;
public YearMonth toYearMonth(){
return YearMonth.parse(startdate);
}
}
The DateTimeFormat annotation is replaced with our new custom validator and instead of a YearMonth, make it a String. Now the validator annotation can be executed because the mapping to the YearMonth won't fail anymore.
We also add a new method to convert the String startdate to a YearMonth after Spring has validated the request body, so we can use it in the service as a YearMonth instead of having to translate it each time.
Now when we send a requestbody with:
{
"startdate": "2020-1"
}
we get a nice 400 bad request with the following response:
{
"endDate": "{YearMonth.invalid}"
}

Spring #RequestMapping method without #RequestBody

In a Spring Boot Controller method, how do I get the body of a POST? All of the examples I have seen use #RequestBody. How do I get the body without using #RequestBody?
I am writing a method to handle Slack Events. When Slack POSTs an event, the body is in JSON and often contains a "user" key. Depending on the type of event, the value of "user" can either be a string or an object. Because of this, I cannot create a single Class and write
#RequestMapping(path = "/slackRequest", method = RequestMethod.POST)
public String handleSlackRequest(#RequestBody final SlackRequest slackRequest)
Answer: Implementing the approach suggested by #ChiDov, the solution is to keep the #RequestBody, import
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
define the user field (and a new field to store the 'user' if it is a simple String value) as
#OneToOne
private SlackEventUser user;
private String slackUserId;
and define its Setter method as
#JsonSetter("user")
public void setUser(JsonNode userNode) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
if (userNode.isObject()) {
SlackEventUser slackEventUser = mapper.convertValue(userNode, SlackEventUser.class);
this.user = slackEventUser;
} else {
String userString = mapper.convertValue(userNode, String.class);
this.slackUserId = userString;
this.user = null;
}
}
Updated: I would make your DTO like :
Class SlackRequest{
...
private String eventType;
private JsonNode user;
...
public String getUser(){
return user.asText();
}
}
and in controller:
#RequestMapping(path = "/slackRequest", method = RequestMethod.POST)
public String handleSlackRequest(#RequestBody final SlackRequest slackRequest){
if(slackRequest.getEventType == "objectEvent"){
SomeObject user = mapper.convertValue(slackRequest.getUser(), SomeObject.class);
// do something with the object
}else{
// do something with the user string
}
}
Get Inspiration from : How to deserialize dynamic field using Jackson?

How to send Java collections containing subclasses to spring controller

I'm trying to send collections to my spring MVC controller:
#RequestMapping("/postUsers.do")
public #ResponseBody ResponseDTO postUsers(#ModelAttribute("mapperList") MapperList mapperList) {
//prints {"users":null}
System.out.println(new ObjectMapper().writeValueAsString(mapperList));
return new ResponseDTO();
}
this is the code posting my users :
public ResponseDTO postUsers(ArrayList<User> users) {
ResponseDTO serverResponse = null;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestMethod("POST");
// prints {"users":[{"property1":"x","property1":y}]}
System.out.println(objectMapper.writeValueAsString(new MapperList(users)));
objectMapper.writeValue(connection.getOutputStream(), objectMapper.writeValueAsString(new MapperList(users)));
//blabla ...
}
and this is the object containing my list :
public class MapperList implements Serializable {
private static final long serialVersionUID = 8561295813487706798L;
private ArrayList<User> users;
public MapperList() {}
public MapperList(ArrayList<User> users) {
this.setUsers(users);
}
public ArrayList<User> getUsers() {
return users;
}
public void setUsers(ArrayList<User> users) {
this.users = users;
}
}
and this is the users type to post:
public abstract class User implements Serializable {
private static final long serialVersionUID = -1811485256250922102L;
private String property1;
private String property2;
public User() {}
public User(String prop1, String prop2) {
// set properties
}
// getters and setters
}
the problem is, when I output the value of the users's array before to post it to the controller, I got the following json value :
{"users":[{"property1":"x","property1":y}]}
but in the controller, when I print what I get from the request body, I only get :
{"users":null}
I also tryed with the annotation #RequestBody instead of #ModelAttribute("mapperList") and a JSONException is displayed :
*A JSONObject text must begin with '{' at 1 [character 2 line 1]\r\n*
My array list of users contains only one user that should be displayed. I don't understand why this doesn't work...
Thanks for any help !
You can chnage your MapperList class definition as public class MapperList extends ArrayList<User>{ ..} you dont need to define any instance variable like private ArrayList users inside MapperList class. Use #Requestbody annotation. You will be able to use MapperList as a ArrayList
Try to use:
public class MapperList{
private List<User> users;
//setter and getter
//toString
}
public class User{
private String property1;
private String property2;
//getter + setter
}
json:
{"users":[{"property1":"x", "property2":"y"}]}
in controller use #RequestBody. In that case Jackson will map your json to ArrayList of users.
#ResponseStatus(HttpStatus.OK)
#RequestMapping("/postUsers.do")
public #ResponseBody ResponseDTO postUsers(#RequestBody MapperList users) {
System.out.println(users);
return null;
}
no need to get objectMapper in that case. Don't forget to set content-type in request header to application/json. It required by Spring to handle #RequestBody processing.
If not working try to change MapperList:
List<User> users = new ArrayList<User>();
On the server side keep the #RequestBody annotation:
public #ResponseBody ResponseDTO postUsers(#RequestBody MapperList mapperList)
...
But this line causes problems:
objectMapper.writeValue(
connection.getOutputStream(),
objectMapper.writeValueAsString(new MapperList(users))
);
First it converts the object to JSON and then again uses objectMapper to JSON-encode the string into output stream. Try the following instead:
connection.getOutputStream().write(
objectMapper.writeValueAsString(new MapperList(users))
.getBytes("UTF-8")
);
or directly output to stream:
objectMapper.writeValue(
connection.getOutputStream(),
new MapperList(users))
);
Zbynek gave me part of the answer. Indeed
objectMapper.writeValue(
connection.getOutputStream(),
objectMapper.writeValueAsString(new MapperList(users))
);
doesn't work properly in my case
But moreover, my User class was an abstract class, with many type of User as subclasses. so the #RequestBody annotation couldn't work without specified the object type in the Json.
I used the following annotations on User class to make it working :
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(value = SubClassA.class, name = "a"),
#JsonSubTypes.Type(value = SubClassB.class, name = "b")
})
Thanks a lot for all your answers.

Resources