how to ignore response fields dynamically in spring webflux - java

I have the below response modal generated from swagger2.0.
Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2022-08-17T22:02:01.513781100-05:00[America/Chicago]")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("city")
private String city ;
#JsonProperty("dateOfBirth")
private String dateOfBirth;
}
when the get User returns the response I would like to skip/Ignore the name and city and wants to return only id and dateOfBirth, how to use JsonIgnoreProperties while converting the response to bodyToMono.
public Mono<User> getUser(String userid) {
return this.webClientConfig
.getWebClient()
.get()
.uri(uriBuilder -> uriBuilder.path("/users/").path(userid).build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(User.class)
}

used Jackson2ObjectMapperBuilder
https://www.baeldung.com/jackson-deserialize-json-unknown-properties

Related

How to make optional parameters mandatory

I need the originId and description fields to be optional if the status is 'CREATED' and mandatory if it's 'UPDATED'.
#PutMapping("{id}")
#ResponseStatus(HttpStatus.OK)
public Mono<Void> update(#PathVariable (value = "id") String id,
#RequestBody #Valid PackageDTO request) {
return update.execute(id, request);
}
public class PackageDTO {
private Long originId;
private String description;
private PackageStatus status;
}
public enum PackageStatus {
CREATED, UPDATED;
}
I tried to use 'required' in Requestbody but i did not succeed

How to turn a String into ArrayList<Details>?

The browser sends the following object to the backend:
Now I would like to store the data in my database. So I have an entity that looks like this:
#Entity
public class NewQuote {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
#ElementCollection(targetClass = Details.class)
private List<Details> details = new ArrayList<>();
public NewQuote(String description, ArrayList<Details> details) {
this.description = description;
this.details = details;
}
#Embeddable
public class Details {
private String description;
private String label;
public Details(String description, String label) {
this.description = description;
this.label = label;
}
public Details() {}
}
Controller
#PostMapping(value = "/save-quote", produces = MediaType.APPLICATION_JSON_VALUE)
public void saveQuote(#RequestBody Map<String, String> data) {
newQuoteService.saveQuote(data);
}
Service
public void saveQuote(Map<String, String> data) {
JSONObject json = new JSONObject(data);
NewQuote newQuote = new NewQuote(
json.getAsString("description"),
json.getAsString("details")
);
newQuoteRepository.save(newQuote);
}
I am getting an error because json.getAsString("details") should not be a string of course. So how can I turn it to ArrayList<Details>?
Add a DTO to manage your json response. You don't need to explicitly use JSONObject because spring already manage the process of mapping under the wood with Jackson.
Also, it is not a good practice to pass your Entities directly into the controller methods.
NewQuoteDto.java
public class NewQuoteDto {
private Long id;
private String description;
private List<Details> details = new ArrayList<>();
public NewQuoteDto() {
}
// getter and setter or you can use lombok
}
DetailDto.java
public class DetailDto {
private String description;
private String label;
public DetailDto() {}
// getter and setter or you can use lombok
}
Controller
#PostMapping(value = "/save-quote", produces = MediaType.APPLICATION_JSON_VALUE)
public void saveQuote(#RequestBody NewQuoteDto dataDto) {
// here you map dataDto to your model before you call saveQuote
NewQuote data = mapper.map(dataDto, NewQuote.class); // if you use ModelMapper library.
newQuoteService.saveQuote(data);
}
For custom mapping take look here.

Spring boot test for Restful POST API DTO with MultiPartFile attribute

I have a Spring Boot app which has a RestController with the following POST method:
#PostMapping(path = "/add", headers = {"content-type=multipart/form-data; charset=utf-8"})
public ResponseEntity<UserWebDTO> addUser(#RequestHeader HttpHeaders headers, #ModelAttribute UserAddDTO userAddDTO) throws Exception {
return new ResponseEntity<>(userService.addUser(userAddDTO), HttpStatus.CREATED);
}
and UserAddDto is as follows:
public class UserAddDTO {
private String first_name;
private String last_name;
private String country_code;
private String phone_number;
private GenderEnum gender;
private String birthdate;
private MultipartFile avatar;
private String email;
}
The code works fine from postman, but I have no idea how to make an integration test with MockMvc for this dto with Multipartfile object, and the test I tried gives me :
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.user.basic.authentication.dtos.UserAddDTO["avatar"]->org.springframework.mock.web.MockMultipartFile["inputStream"])
any help is appreciated.
Thanks!
I believe that you need to implements Serializable
public class UserAddDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String first_name;
private String last_name;
private String country_code;
private String phone_number;
private GenderEnum gender;
private String birthdate;
private MultipartFile avatar;
private String email;
}

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

List of Pojo not getting converted into Json using #ResponseBody

I have controller class as below:
#RequestMapping(value = "/Reporting/FilterAsJson", method = RequestMethod.POST)
public #ResponseBody PagedQueryResult<GetEntitlementOverviewReportResult> filterAsJson(#ModelAttribute GetEntitleReportQuery query, HttpSession session)
{
getEntitlementOverviewFromSession(session).updateFromQuery(query, session);
return queryDispatcher.dispatch(query);}
The POJO class GetEntitlementOverviewReportResult is :
public class GetEntitlementOverviewReportResult
{
private Long id;
private String customerName;
private Long customerId;
private String customerNumber;
private String createdOn;
private String itemCreationDate;
private String licenseStatus;
private String licenseType;
private String licenseStatusCode;
private String licenseID;
private Long requestId;
private String licenseRootID;
private String customerNameCS;
private String customerNumberCS;
// <with getters and setters for the variables>
}
The problem is when all the fields in bean class is being set, proper Json is getting returned as a response. But when only first 6 fields are getting set, the response fails with 500 error in the debugger tool and doesn't return back to the calling ajax method. I get an "internal error" pop up in the browser. What am i missing here? Is is not possible to leave out the other fields whose values are not being fetched? I also tried using #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) but it doesn't make any difference.

Categories