Spring MVC Map Request Body to Primitive Type - spring

I want to handle simple POST request by spring mvc. The request body contain only a single int value. Can anyone help me to write the action method. My code is below:
#PostMapping(value = "/update")
#ResponseBody
public ResponseEntity updateLogLevel(#RequestBody int level) {
try {
//process request
} catch (Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
return ResponseEntity.ok(Constant.STATUS_SUCCESS);
}
But this code throw exception:
org.springframework.http.converter.HttpMessageNotReadableException",
"message":"JSON parse error: Can not deserialize instance of int out of START_OBJECT token;
nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int out of START_OBJECT token
My request body:
{
"level" : 100
}

You are sending in your payload an object not integer, just send the number
100

Related

How to change WebClient behaviour concerning LocalDateTime?

I am using Spring Boot 2.4.5 and try to request a REST API of another application using WebClient. I know that the other application provides the requested information as a Collection.
When I use an Object[] to receive the response:
Object[] ob = (Object[]) webClient
.get()
.uri(endpoint)
// .bodyValue(criteria)
.exchangeToMono(response -> {
if (response.statusCode()
.equals(HttpStatus.OK)) {
return response.bodyToMono(Object[].class);
} else if (response.statusCode()
.is4xxClientError()) {
return Mono.just("Error response");
} else {
return response.createException()
.flatMap(Mono::error);
}
}).block();
I can see that I receive a LinkedHashMap with all the values including a field:
date_of_declaration -> 2020-03-02T08:43:10
However, if possible, I want to let WebClient immediately convert the response into the designated DTOs...
DeclarationDTO[] ob = (DeclarationDTO[]) webClient
.get()
.uri(endpoint)
// .bodyValue(criteria)
.exchangeToMono(response -> {
if (response.statusCode()
.equals(HttpStatus.OK)) {
return response.bodyToMono(DeclarationDTO[].class);
} else if (response.statusCode()
.is4xxClientError()) {
return Mono.just("Error response");
} else {
return response.createException()
.flatMap(Mono::error);
}
}).block();
...I get an exception when a LocalDateTime object shall be deserialized.
org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize value of type `java.time.LocalDateTime` from String "02-03-2020 01:20:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '02-03-2020 01:20:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {HourOfAmPm=1, NanoOfSecond=0, SecondOfMinute=0, MicroOfSecond=0, MinuteOfHour=20, MilliOfSecond=0},ISO resolved to 2020-03-02 of type java.time.format.Parsed; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "02-03-2020 01:20:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '02-03-2020 01:20:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {HourOfAmPm=1, NanoOfSecond=0, SecondOfMinute=0, MicroOfSecond=0, MinuteOfHour=20, MilliOfSecond=0},ISO resolved to 2020-03-02 of type java.time.format.Parsed
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1438] (through reference chain: java.lang.Object[][0]->de.xxx.myportal.api.infrastructure.dto.MyDTO["a_person"]->de.xxx.myportal.api.infrastructure.dto.APersonDTO["foobar"])
I think WebClient has an internal ObjectMapper, so maybe it is possible to modify this ObjectMapper during WebClient instantiation? ...or is there a better way to tell Webclient how to handle LocalDateTime? ...maybe a WebClient customized by a configuration or...?
I can't explain but after removing any JsonFormat annotation it works out of the box. (Weird!)
This may help https://www.baeldung.com/spring-boot-formatting-json-dates
In your DeclarationDTO you can use something like:
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm:ss")
#JsonProperty("date_of_declaration")
private LocalDateTime dateOfDeclaration;

RestTemplate including body in exception

Suppose I call a webservice with RestTemplate and it returns 500 status error with this body:
{
"timestamp": "2019-10-10T16:51:15Z",
"status": 500,
"error": "Internal Server Error",
"message": "Error occurred while retrieving entity with id: bb00b45c-9e17-4d75-a89a",
"path": "/api/service"
}
Currently RestTemplate exception message is something like:
Caused by: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 null
at org.springframework.web.client.HttpServerErrorException.create(HttpServerErrorException.java:79)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:124)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102)
Is there any way to include the body of the response in the RestTemplate exception message without using a custom error handler?
Thanks!
May be something like this (without a Custom Error Handler)
ObjectMapper mapper;
try {
ResponseEntity<User> response = restTemplate.exchange(url,
HttpMethod.POST, requestEntity, User.class);
} catch (HttpStatusCodeException e) {
List<String> header = e.getResponseHeaders().get("x-app-err-id");
String errorMessageId = "";
if (header != null && !header.isEmpty()) {
errorMessageId = header.get(0);
}
// You can get the body, but deserialise it using mapper into a POJO
ErrorResponseBody errorResponseBody = mapper.readValue(e.getResponseBodyAsString(),
ErrorResponseBody.class);
// You can re-throw it if you want or use the response body
throw new CustomException(e, HttpStatus.INTERNAL_SERVER_ERROR);
}

Spring boot rest request data type validation

I am doing validation for request object in spring boot rest. I have to validate data type of request. The request has multiple boolean values and trying to validate if string in passed for boolean data type.
I have handling HttpMessageNotReadableException in my ControllerAdvice class and sending list of error message. But in my response only first field is throwing exception. If clue ,please help.
#Vishnu Dubey use this .....
#RestControllerAdvice
public class ServiceControllerAdvice {
private static final Logger log = LoggerFactory.getLogger(ServiceControllerAdvice.class);
#ExceptionHandler(value = { ConstraintViolationException.class })
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ServiceResponse<?> constraintViolationException(final ConstraintViolationException ex) {
log.error("Validation failed", ex);
final ServiceResponse<?> response = new ServiceResponse<>(-1);
final Error error = new Error();
error.setCode("PS01");
error.setContext(ex);
error.setMessage(ex.getMessage());
response.setError(error);
return response;
}
}

JSON parserError while creating user in Openfire through spring boot application

In my project I have to create a chat box. For that I have to use Open-fire server. I am having the service for creating users in this server.
I am facing the problem when I am trying to access the openfire service from my spring boot application.
I am have created the model for the user also created the service and provided implementation to it.
This is my model class,
public class OpenFireUser {
private String firstname;
private String username;
private String password;
private String email;
<----getters and setters--->
}
This is my service,
public UserCreationResponse createOpenFireUser(String authorization,User createUser) {
OpenFireUser user= new OpenFireUser();
user.setEmail(createUser.getEmail());
user.setFirstname(createUser.getFirstname().toLowerCase());
user.setPassword("Passw0rd");
user.setUsername(createUser.getUsername().toLowerCase());
UserCreationResponse response=new UserCreationResponse();
RestTemplate restTemplate = new RestTemplate();
try{
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Authorization", authorization);
headers.add("Content-Type", "application/json");
headers.add("Accept", "application/json");
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<OpenFireUser> requestObject = new HttpEntity<OpenFireUser>(user, headers);
ResponseEntity<String> responseEntity=restTemplate.postForEntity(OPENFIRE_REST_ENDPOINT, requestObject,String.class);
int statusCode = responseEntity.getStatusCodeValue();
if(statusCode==201){
response.setResponseCode(statusCode);
return response;
}else{
response.setResponseCode(MessageConstant.ResponseCode.ProcessFail.value());}
return response;
}catch(HttpClientErrorException clientErr){
response.setUserMessage(clientErr.getMessage());
response.setResponseCode(clientErr.getStatusCode().value());
response.setResponseMessage(MessageConstant.CodeMessage.ProcessFail.value());
return response;
}
catch(Exception e)
{
response.setResponseCode(MessageConstant.ResponseCode.ProcessFail.value());
response.setResponseMessage(MessageConstant.CodeMessage.ProcessFail.value());
return response;
}
}
This is controller code for calling service,
#RequestMapping(value = "/createOpenFireUser", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
public UserCreationResponse createOpenFireUser(#RequestBody User createUser) {
logger.debug("Entering inside createOpenFireUser(#RequestBody OpenFireUser createUser) method");
//logger.debug("Create user request : {}" , createUserRequestEntity);
return userService.createOpenFireUser("authorizationKey",createUser);
}
while sending data from postman I am getting error like,
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of com.exelatech.printshop.model.User out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.exelatech.printshop.model.User out of START_ARRAY token
at [Source: java.io.PushbackInputStream#6c88daca; line: 1, column: 1]
2018-07-20 15:59:13.535 WARN 9988 --- [nio-9090-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of model.User out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of model.User out of START_ARRAY token
at [Source: java.io.PushbackInputStream#6c88daca; line: 1, column: 1]
On postman I am getting response like,
"timestamp": 1532082553781,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not deserialize instance of model.User out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of model.User out of START_ARRAY token\n at [Source: java.io.PushbackInputStream#6c88daca; line: 1, column: 1]",
Can anyone help me to solve my issue?
Error was in sending object through postman.
Previously I was sending request object like,
[
{
"firstname" : "Jyoti",
"username" : "JyotiNH",
"password":"Passw0rd",
"email" : "jyoti.kanor#exelaonline.com"
}
]
which is object.
But my method receiving parameter as array of strings,
So when I sent request with object like following structure, it successfully created the user.
{
"firstname" : "Jyoti",
"username" : "JyotiNH",
"password":"Passw0rd",
"email" : "jyoti.kanor#exelaonline.com"
}

How to display customized error response in REST API

My url is http://localhost:8090/employee/?emp_id=1551&name=
I am using Spring boot for designing REST application. I have used #RequestMapping and #RequestParam annotation for get resource. When I pass empty value to request parameter (for eg. name = ), I get below validation response(actual output section below).
However I wanted to override this output to display customized error response as below(expected section below).
How can I achieve this? How to avoid Spring's auto validation for input parameters in Get request?
Output
======
{
"timestamp": 1511144660708,
"status": 400,
"error": "Bad Request",
"message": "Required String parameter 'name' is not present",
"path": "/employee"
}
Expected
========
{
"errors":[
{
"id":"123144",
"detail": "invalid user input"
"status": "400"
}
]
}
Following sample code demonstrates how to customize error message for exception handling.
Create 2 POJOs for your customized response body.
Implement 1 method to catch the MissingServletRequestParameterException exception with #ExceptionHandler annotation for missing paramters.
Generate the response as you expected.
Class: ResponseProperty.java
public class ResponseProperty {
private int id;
private String detail;
private int status;
//getters and setters produced by IDE
}
Class: ResponsePOJO.java
public class ResponsePOJO {
List<ResponseProperty> errors;
public List<ResponseProperty> getErrors() {
return errors;
}
public void setErrors(List<ResponseProperty> errors) {
this.errors = errors;
}
}
Method: handleMethodArgumentTypeMismatch
#ExceptionHandler({ MissingServletRequestParameterException.class })
public ResponseEntity<Object> handleMethodArgumentTypeMismatch(MissingServletRequestParameterException ex) {
ResponseProperty property = new ResponseProperty();
property.setId(123144);
property.setDetail("invalid user input");
property.setStatus(400);
ResponsePOJO responsePOJO = new ResponsePOJO();
List<ResponseProperty> propertyList = new ArrayList<ResponseProperty>();
propertyList.add(property);
responsePOJO.setErrors(propertyList);
return new ResponseEntity<Object>(responsePOJO, HttpStatus.BAD_REQUEST);
}
If you visit the endpoint /employee without required parameter, then you are going to see the response as follows:
Http Response
{
"errors": [
{
"id": 123144,
"detail": "invalid user input",
"status": 400
}
]
}
Hope this helps you! :)
UPDATE
If you want to get the request ID from header named requestId for response, you can use WebRequest to get this information as follows:
#ExceptionHandler({ MissingServletRequestParameterException.class })
public ResponseEntity<Object> handleMethodArgumentTypeMismatch(MissingServletRequestParameterException ex,
WebRequest request) {
ResponseProperty property = new ResponseProperty();
property.setId(Integer.valueOf(request.getHeader("requestId")));
...
}

Resources