Null properties in objects retrive by mono.block - spring

I'm doing a post request to a server.
When I ask for a String, the response its OK. But, when I ask for an object, all the properties are sent null.
I have a #ApplicationScoped class where I execute the following code:
MyClassDTO dto = client.post()
.uri("/myUri/someEndpoint")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(Mono.just(json.toString()), String.class)
.retrieve()
.bodyToMono(MyClassDTO.class)
.block();
When I execute this I recibe all the fields null.
Here is MyClassDTO code:
#Data #Builder #NoArgsConstructor #AllArgsConstructor
public class MyClassDTO {
private String Error;
private String ErrorMsg;
private SdtpProductPriceDTO SDTProductPrice;
}
Can someone give me a lead on this?
Thanks in advance!

Related

SpringBoot + Thymeleaf - upload MultipartFile in form

I've done the following Thymeleaf form which takes some fields and a .pdf CV file
Form: link
There is the controller:
#Controller
#RequestMapping("/interview")
public class InterviewController {
#PostMapping(path = "/create", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public #ResponseBody ResponseEntity<Object> createInterview(#RequestBody #ModelAttribute CreateInterviewTO createInterviewTO) {
ErrorRTO errorRTO = checkErrorsInsertInterview.validate(createInterviewTO);
//...Other
}
}
And at the end, DTO class:
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class CreateInterviewTO {
private String site;
private String candidateName;
private String candidateSurname;
private Date candidateBirth;
private String mail;
private String eduQualification;
private String candidateType;
private String interviewType;
private String enterpriseId;
private MultipartFile curriculum;
}
When I send the request, I receive the following error:
w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
UPDATE: when I sent request, curriculum DTO attribute is null.
Anyone has a solution?

Spring data swagger generates requestbody field from getter method

I have this DTO which i use as the #RequestBody of an endpoint in my spring data app:
#Builder
#AllArgsConstructor
#EqualsAndHashCode
#Getter
#NoArgsConstructor
public class CreateBridgeInput {
private String customIdName;
private BridgeType type;
private String zoneId;
#Override
public String getId() {
return this.customIdName;
}
}
If I make CreateBridgeInput implement this interface
public interface EntityInputBase {
public String getId();
}
The generated swagger file includes a field called id in the expected request body, despite there being no field called id.
Why does it do this, and how do I prevent this from happening? I found that I can use the #Hidden annotation from swagger, but if a class that extends EntityInputBase does actually have an id field, it will hide it when it shouldn't.

Got status 500 and message "Missing URI template variable 'rank'", whenever test HTTP POST request on postman

I got the error "Resolved [org.springframework.web.bind.MissingPathVariableException: Missing URI template variable 'rank' for method parameter of type Rank]" on eclipse console
And message: "Missing URI template variable 'rank' for method parameter of type Rank" with status "500" whenever try HTTP POST request
My RESTController code:
#RestController
#RequestMapping(path = "/comp")
public class RankController {
#PostMapping(path = "/rank")
ResponseEntity<Rank> createRank(#Valid #PathVariable Rank rank) throws URISyntaxException{
Rank result = rankRepository.save(rank);
return ResponseEntity.created(new URI("/comp/rank" + result.getId())).body(result);
}
}
My Rank entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "RANK_TBL")
public class Rank {
#Id
private Long id;
private String name;
#ManyToOne(cascade = CascadeType.PERSIST)
private Employee employee;
}
My Employee entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "EMPLOYEE_TBL")
public class Employee {
#Id
private Long id;
private String name;
private String email;
#OneToMany
private Set<Rank> Rank;
}
Change #PathVariable with #RequestBody
Here you are making a request to save the entity and you should pass the payload as #RequestBody in JSON format. From postman you may use raw type and select the JSON type.
Ideal way is to use #RequestBody whenever we are creating or updating the records which requires the object to passed with POST and PUT methods. For methods which retrieves the records based on Id or some parameters you may use #PathVariable
You may explore more about the annotations here

Response Entity not getting mapped for custom objects inside a class

I am hitting an API and getting the response using resttemplate.exchange object and i am mapping the response to a parameterized object .All the variables inside the response class are getting mapped to the response entity object but not the Attribute class variables inside the parameterized object.
ResponseEntity<ArrayList<Response>> responseEntity =
restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
new HttpEntity<>(headers),
new ParameterizedTypeReference<ArrayList<Response>>()
{});
#Getter
#Setter
public class Response {
private String number;
private String id;
private String name;
#JsonProperty("attributes")
private ArrayList<Attributes> attributes ;
}
#Getter
#Setter
#JsonIgnoreProperties(ignoreUnknown=true)
public class Attributes {
private String value;
private String name;
}

Spring Boot validation of RequestBody Dto annotated in Rest API

In my controller I have annotated the request parameter with the #Valid annotation and the field of my DTO with the #NotNull annotation, but the validation doesn't seem to work.
Are there any configurations to do in order to proceed with the validation? Following there are the Controller and the DTO class details.
#RepositoryRestController
#RequestMapping(value = "/download_pdf")
public class PurchaseController {
#Autowired
private IPurchaseService iPurchaseService;
#Loggable
#RequestMapping(value = "view_order", method = RequestMethod.POST)
public ResponseEntity getPDF(#RequestBody #Valid CustomerOfferDto offer,
HttpServletResponse response) {
return iPurchaseService.purchase(offer, response);
}
}
public class CustomerOfferDto {
#NotNull
private String agentCode;
// getter and setter...
}
Following are the steps I did to make it work.
Add dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Constraints in DTO class:
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
#ValidTaskDTO
public class TaskDTO {
#FutureOrPresent
#NotNull(message = "DueDate must not be null")
private ZonedDateTime dueDate;
#NotBlank(message = "Title cannot be null or blank")
private String title;
private String description;
#NotNull
private RecurrenceType recurrenceType;
#Future
#NotNull(message = "RepeatUntil date must not be null")
private ZonedDateTime repeatUntil;
}
RestController method with #Valid annotation on requestBody argument:
#RestController
#RequestMapping("/tasks")
#Validated
public class TaskController {
#PostMapping
public TaskDTO createTask(#Valid #RequestBody TaskDTO taskDTO) {
.....
}
}
On making a POST request with requestbody containing null value for dueDate, I got the expected error message as shown below.
{
"timestamp": "2021-01-20T11:38:53.043232",
"status": 400,
"error": "Bad Request",
"message": "DueDate must not be null"
}
I hope this helps. For details on class level constraints, hav a look at this video.
In my projects, this usually happens when I change my code from lets say Entity to DTO and forget to add #ModelAttribute to my DTO parameter.
If this also happened to you, try adding #ModelAttribute("offer") to your DTO parameter.

Resources