#RequestBody Map<String, Object> input getting int value - java

#RequestMapping(path = "/registrationuser", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE, consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getUserDetails(#RequestBody Map<String, Object> input) throws commonException {
Map<String, Object> retMap = new HashMap<String, Object>();
String email=(String) input.get("email");
long id=(Long) input.get("userid");
String password=(String) input.get("password");
String rollid="1";
User user = new User();
user.setEmail(email);
user.setId(id);
user.setPassword(bCryptPasswordEncoder.encode(password));
userRepository.save(user);
ResponseEntity<Map<String, Object>> retValue = new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
return retValue;
}
===
$scope.saveUserFunction = function(myVar) {
console.log($scope.edituserdetails.email);
console.log($scope.edituserdetails.email);
console.log($scope.edituserdetails.username);
console.log($scope.edituserdetails.password);
console.log($scope.edituserdetails.id);
console.log($scope.token);
//$scope.user = {};
// calling our submit function.
$http({
method : "POST",
url : "/registrationuser",
data : {
"email" : $scope.edituserdetails.email,
"username": $scope.edituserdetails.username,
"password" : $scope.edituserdetails.password,
"userid": $scope.edituserdetails.id
}
})
.success(function(data) {
if (data.errors) {
} else {
// $scope.message = data.message;
}
});
}
});
Getting below error for user ID. Why it is come as integer. I need to cast it as long as well?

You could use your entity directly in spring-rest like:
#RequestBody User user
Afterwards the password then also could be reset.
Also the return value shouldn't be a Map.
return new ResponseEntity<User>(user, HttpStatus.OK);

Related

How do I Mock Rest Template for Post method

I want one JSONObject response after passing URI through RESTTemplate
Test case is passing but the code coverage is still 0%
I have to return accountDetails object in JSON format
how do we Pass URI which takes account ID and given response entity in JSON Format this is what I have to figure out.
Test method:
void scheduleOnDemand() throws Exception {
AccountDTO accountDTO = new AccountDTO();
accountDTO.setId(1);
accountDTO.setTimeZone("Asia/Kolkata");
accountDTO.setPlatformType("AZURE");
accountDTO.setEnvironmentName("test");
accountDTO.setName("azureAccount");
accountDTO.setNextScheduleDate("2021-09-13");
accountDTO.setEnvironmentId(1);
HashMap<String, Object> accountDetails = new HashMap<>();
accountDetails.put("account_Id", "1");
accountDetails.put("TimeZone", "Asia/Kolkata");
accountDetails.put("AgentStatus", "Initiated");
accountDetails.put("Account_Platform", "AZURE");
accountDetails.put("Schedule_Time", "13:30:50.000");
accountDetails.put("Environment_Name", "test");
accountDetails.put("Account_Name", "azureAccount");
accountDetails.put("History_Id", "109");
accountDetails.put("Schedule_Date", "2021-09-13");
accountDetails.put("Environment_Id", "1");
Mockito.when(restTemplate.postForEntity("configure/accountDetails?Account_Id=1",null, JSONObject.class))
.thenReturn(new ResponseEntity((accountDetails), HttpStatus.OK));
}
Actual Method:
#Override
public JSONObject scheduleOnDemand(String accountId) throws Exception {
JSONObject object = null;
// PlatformHistoryDetails phistory = null;
HashMap<String, Object> accountDetails = new HashMap<>();
accountDetails = utilService.getAccountDetails(Integer.parseInt(accountId));
if (((String) accountDetails.get("scantype")).equalsIgnoreCase("infra")||((String) accountDetails.get("scantype")).equalsIgnoreCase("all")) {
URI postUri = UriComponentsBuilder.fromPath("/").pathSegment("api/scheduleOnDemand")
.queryParam("requestId", MDC.get("requestId")).queryParam("service", "scan")
.queryParam("Account_Id", accountId).build().toUri();
PlatformHistoryDetails phistory = modelMapper.map(apiClient.postOperation(postUri, Object.class),
PlatformHistoryDetails.class);
phistory.getHistory().setUser("admin");
object = utilService.processOneAccount(phistory);
} else {
throw new Exception("Account is not of type INFRA or ALL but of type " + accountDetails.get("scantype"));
}
return object;
}
accountDetails Implementation:
#Override
#SuppressWarnings({ "unchecked", "rawtypes" })
public HashMap<String, Object> getAccountDetails(int accountId) {
URI getUri = UriComponentsBuilder.fromPath("/").pathSegment("configure/accountDetails")
.queryParam("Account_Id", accountId).build().toUri();
HashMap<String, Object> account = (LinkedHashMap) apiClient.getAccountDetails(getUri, Object.class);
return account;
}

Transform JSON to another JSON structure

I have a case to transform a response from
Dogs API
to a different structure like this :
[
{
"breed": "pug",
"sub_breed": []
},
{
"breed": "ridgeback",
"sub_breed": [
{
"breed": "rhodesian",
"sub_breed": []
}
]
},
{
"breed": "doberman",
"sub_breed": []
},
{
"breed": "hound",
"sub_breed": [
{
"breed": "Ibizan",
"sub_breed": []
},
{
"breed": "afghan",
"sub_breed": []
}
]
}
]
I am confused after getting the response and don't know how to transform it.
Here is what I do until getting the response
public List<DogResponse> getDogs() {
List<DogResponse> response = new ArrayList<DogResponse>();
try {
String url = "https://dog.ceo/api/breeds/list/all";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(result.getBody().toString(), Map.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map.get("message")));
for (Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key : "+key);
System.out.println("val : "+value);
}
} catch (Exception e) {
// TODO: handle exception
}
return response;
}
DogResponse
public class DogResponse {
private String breed;
private DogResponse sub_breed;
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public DogResponse getSub_breed() {
return sub_breed;
}
public void setSub_breed(DogResponse sub_breed) {
this.sub_breed = sub_breed;
}
}
I am trying using Map but failed when I want to print the key and value, it's showing nothing.
You should map the response to List of DogResponse you may have an issue because of circular dependency.
List<DogResponse> dogs = mapper.readValue(jsonString, new TypeReference<List<DogResponse>>() {});
You can try this.
public List<DogResponse> getDogs() {
List<DogResponse> response = new ArrayList<DogResponse>();
try {
String url = "https://dog.ceo/api/breeds/list/all";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, List<String>>> map = mapper.readValue(result.getBody().toString(), Map.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map.get("message")));
Map<String, List<String>> innerMap = map.get("message");
for (Entry<String, List<String>> entry : innerMap.entrySet()) {
String key = entry.getKey();
List<String> value = entry.getValue();
System.out.println("key : " + key);
System.out.println("val : " + value);
}
} catch (Exception e) {
// TODO: handle exception
}
return response;
}
ResponseEntity result = restTemplate.getForEntity(url, DogResponse.class);
This should work.

Remove a char from Iterable<Map<String, Object>> in java

In my code I am using,
#RequestMapping(value = "/getBlueprintById", method = RequestMethod.GET)
public #ResponseBody BlueprintsMessage find(#FormDataParam("id") String id, final HttpServletResponse response) {
ResponseStatus status = null;
Long blueprintId = Long.parseLong(id);
response.setHeader("Cache-Control", "no-cache");
Iterable<Map<String, Object>> entity = null;
try {
entity = blueprintService.getBlueprintById(blueprintId);
status = new ResponseStatus(ResponseStatusCode.STATUS_OK, "SUCCESS");
} catch (Exception e) {
e.printStackTrace();
}
return new BlueprintsMessage(status, entity);
}
and the output value was,
{
"blueprint": {
"relation": [
{
"id": 1271,
"relationParam": [
{
"value": "{\"canaries\":\"1\",\"canary_watch_time\":\"30000-180000\",\"update_watch_time\":\"30000-180000\",\"max_in_flight\":\"4\"}"
}
]
}
]
}
}
I want to remove \ in my output and the output was same as Iterable<Map<String, Object>> type. The values saved into database, i just get the values from DB.

spring mvc controller error java.lang.IllegalStateException: No suitable resolver for argument [0]

Code gives an error
java.lang.IllegalStateException: No suitable resolver for argument
[0][type=org.jopenclass.form.Course]
It sends a JSON response to an ajax call. I use hibernate to persist the objects.
#RequestMapping(value = "/savecourse", method = RequestMethod.POST)
public #ResponseBody
Object saveLecturer(#Valid #ModelAttribute(value = "course") Course course,
BindingResult result) {
Map<String, Object> response = new HashMap<String, Object>();
if (result.hasErrors()) {
List<ObjectError> results = result.getAllErrors();
for (ObjectError objectError : results) {
System.out.println(objectError.getDefaultMessage());
}
response.put("message", "Could not add the Course to the system.");
} else {
try {
course.setId(courseDao.saveCourse(course));//returns the id
response.put("course", course);
} catch (Exception e) {
System.out.println(e);
}
}
return response;
}
But when I create a new object and copy the parameters to the other object, it works fine. The second method(Not a good method of course) works well. All the parameters in the request object are set to the cse object as well.
#RequestMapping(value = "/savecourse", method = RequestMethod.POST)
public #ResponseBody
Object saveLecturer(#Valid #ModelAttribute(value = "course") Course course,
BindingResult result) {
Map<String, Object> response = new HashMap<String, Object>();
if (result.hasErrors()) {
List<ObjectError> results = result.getAllErrors();
for (ObjectError objectError : results) {
System.out.println(objectError.getDefaultMessage());
}
response.put("message", "Could not add the Course to the system.");
} else {
try {
course.setId(courseDao.saveCourse(course));//returns the id
Course cse = new Course();
cse.setId(course.getId());
cse.setCourseName(course.getCourseName());
cse.setFee(course.getFee());
Lecturer lec = new Lecturer();
lec.setId(course.getLecturer().getId());
lec.setFirstName(course.getLecturer().getFirstName());
lec.setLastName(course.getLecturer().getLastName());
cse.setLecturer(lec);
cse.setGrade(course.getGrade());
response.put("course", cse);
} catch (Exception e) {
System.out.println(e);
}
}
return response;
}
What is wrong in the first method?
In the first case Jackson is not able to deserialize your response. I would suggest changing your return type to Map<String, ? extends object>
Let us know if the problem persists

500 internal server error in spring mvc 3 controller response for ajax call

my code gives 500 error when I have the following code. It sends a jason response to an ajax call.
#RequestMapping(value = "/savecourse", method = RequestMethod.POST)
public #ResponseBody
Object saveLecturer(#Valid #ModelAttribute(value = "course") Course course,
BindingResult result) {
Map<String, Object> response = new HashMap<String, Object>();
if (result.hasErrors()) {
List<ObjectError> results = result.getAllErrors();
for (ObjectError objectError : results) {
System.out.println(objectError.getDefaultMessage());
}
response.put("message", "Could not add the Course to the system.");
} else {
try {
course.setId(courseDao.saveCourse(course));//returns the id
response.put("course", course);
} catch (Exception e) {
System.out.println(e);
}
}
return response;
}
But when I create a new object and copy the parameters to the other object, it works fine. The second method(Not a good method of course) works well. All the parameters in the request object are set to the cse object as well.
#RequestMapping(value = "/savecourse", method = RequestMethod.POST)
public #ResponseBody
Object saveLecturer(#Valid #ModelAttribute(value = "course") Course course,
BindingResult result) {
Map<String, Object> response = new HashMap<String, Object>();
if (result.hasErrors()) {
List<ObjectError> results = result.getAllErrors();
for (ObjectError objectError : results) {
System.out.println(objectError.getDefaultMessage());
}
response.put("message", "Could not add the Course to the system.");
} else {
try {
course.setId(courseDao.saveCourse(course));//returns the id
Course cse = new Course();
cse.setId(course.getId());
cse.setCourseName(course.getCourseName());
cse.setFee(course.getFee());
Lecturer lec = new Lecturer();
lec.setId(course.getLecturer().getId());
lec.setFirstName(course.getLecturer().getFirstName());
lec.setLastName(course.getLecturer().getLastName());
cse.setLecturer(lec);
cse.setGrade(course.getGrade());
response.put("course", cse);
} catch (Exception e) {
System.out.println(e);
}
}
return response;
}
Can you please tell me what is wrong in the first method?
Any help is greatly appreciated.

Categories

Resources