List of Pojo not getting converted into Json using #ResponseBody - java

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.

Related

Field error in object 'titulo' on field 'status': rejected value [Pendente];

I am trying to learn Spring Framework on the go. During runtime I get following stacktrace:
Validation failed for object='title'. Error count: 1
org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'title' on field 'status': rejected value
[Received];
I noticed that the problem is in the status, which is formatted by enum, but I can't any error.
My class Controller:
#Controller
#RequestMapping("/titles")
public class registerTitleController {
#RequestMapping("/title")
public String new() {
return "RegisterTitle";
}
#Autowired
private Titles titles;
#RequestMapping(method=RequestMethod.POST)
public String saveIn(Title title) {
titles.save(title);
return "RegisterTitle";
}
}
My class entity
#Entity
public class Title {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cod;
private String description;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Temporal(TemporalType.DATE)
private Date dateV;
private BigDecimal val;
#Enumerated(value = EnumType.STRING)
private StatusTitle status;
//other accessor methods
My class enum
public enum StatusTitle {
PENDING("Pending"),
RECEIVED("Received");
private String description;
private StatusTitulo(String descricao){
this.description = description;
}
public String getDescription() {
return description;
}
}
My system work without the status of the attribute.
Can someone point out what is wrong? Your help will be much appreciated.
You probably are sending "Received", but you need to send "RECEIVED" string to properly convert to the ENUM by default.

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;
}

Java object not populated from json request for inner class

Have searched in different sites but couldn't find correct answer, hence posting this request though it could possible duplicates.sorry for that.
I am sending the below json request to my back-end service and converting to java object for processing. I can see the request body passed to my service but when i convert from json to java object , values are not populating
{
"data":{
"username":"martin",
"customerId":1234567890,
"firstName":"john",
"lastName":"smith",
"password":"p#ssrr0rd##12",
"email":"john.smith#gmail.com",
"contactNumber":"0342323443",
"department":"sports",
"location":"texas",
"status":"unlocked",
"OrderConfigs":[
{
"vpnId":"N4234554R",
"serviceId":"connectNow",
"serviceType":"WRLIP",
"ipAddress":"10.101.10.3",
"fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
"timeout":1800,
"mapId":"test_map"
}
]
}
}
My Parser class have something like,
JSONObject requestJSON = new JSONObject(requestBody).getJSONObject("data");
ObjectMapper mapper = new ObjectMapper();
final String jsonData = requestJSON.toString();
OrderDTO mappedObject= mapper.readValue(jsonData , OrderDTO .class);
// I can see value coming from front-end but not populating in the mappedObject
My OrderDTO.java
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true,value = {"hibernateLazyInitializer", "handler", "created"})
public class OrderDTO {
private String username;
private long customerId;
private String source;
private String firstName;
private String lastName;
private String email;
private String contactNumber;
private String password;
private String department;
private String location;
private String status;
private List<OrderConfig> OrderConfigs;
#JsonInclude(value = Include.NON_NULL)
public class OrderConfig {
private String vpnId;
private String serviceId;
private String serviceType;
private String ipAddress;
private String mapId;
private String[] fRoutes;
private Map<String, Object> attributes;
private SubConfig subConfig;
private String routeFlag;
getter/setters
.....
}
all setter/getter
}
Not sure what I'm missing here. Is this right way to do?
If your are trying to use inner class, correct way to use is to declare it static for Jackson to work with inner classes.
For reference check this
code changes made are
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
static class OrderConfig {
Make sure that your json tag names match with variable names of java object
Ex : "fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
private String[] fRoutes;
OrderConfigs fields will not be initialized, just modify your bean as
#JsonProperty("OrderConfigs")
private List<OrderConfig> orderConfigs;
// setter and getter as setOrderConfigs / getOrderConfigs
See my answer here. (same issue)

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

#QueryParam by default on all properties of #BeanParam in jersey 2

I want to use POJO as #BeanParam in jersey 2:
public class GetCompaniesRequest {
/** */
private static final long serialVersionUID = -3264610327213829140L;
private Long id;
private String name;
...//other parameters and getters/setters
}
#Path("/company")
public class CompanyResource {
#GET
public Response getCompanies(
#BeanParam final GetCompaniesRequest rq) {
...
}
}
There are many properties in GetCompaniesRequest and I want all them to be available as #QueryParameter. Can I achieve this without putting #QueryParam on every property?
You can inject the UriInfo and retrieve all the request parameters from it to a Map.
This will let you avoid injecting multiple query paramters with #QueryParam annotation.
#GET
public Response getCompanies(#Context UriInfo uris)
{
MultivaluedMap<String, String> allQueryParams = uris.getQueryParameters();
//Retrieve the id
long id = Long.parseLong(allQueryParams.getFirst("id"));
//Retrieve the name
String name = allQueryParams.getFirst("name");
//Keep retrieving other properties...
}
Otherwise, if you still need to use the #BeanParam , you will have to annotate each property in GetCompaniesRequest with #QueryParam:
public class GetCompaniesRequest implements MessageBody
{
#QueryParam("id")
private Long id;
#QueryParam("name")
private String name;
...
}

Categories