how to access GetMapping notation from postman with HttpServletRequest - spring

I have a spring boot controller but I don't know how to access the GetMapping notation through postman application. This is my controller:
#GetMapping
public ResponseEntity<dataTableDTO> getProject(HttpServletRequest request, int draw) throws Exception {
//... do what needs to be done
List<ProjectEntity> objProj = (List<ProjectEntity>) projectRepository.findAll();
List<String> slist = new ArrayList<String>();
for(ProjectEntity d : (List<ProjectEntity>)objProj){
slist.add(String.valueOf(d.getCustomerId()));
}
String listCustId = StringUtils.collectionToCommaDelimitedString(slist);
List<CustomerDTO> objCust = (new CustomerDAO()).getCustomer(listCustId, request.getHeader("Authorization"));
List<ProjectDTO> objProjDTO = new ArrayList<ProjectDTO>();
for(ProjectEntity d : (List<ProjectEntity>)objProj){
String name = "";
for(CustomerDTO c : objCust){
if(c.getId() == d.getCustomerId()){
name = c.getFirstName() + " " + c.getLastName();
}
}
objProjDTO.add(new ProjectDTO(d.getId(), d.getCustomerId(), name, d.getName(), d.getType()));
}
dataTableDTO data = new dataTableDTO(draw, objProjDTO.size(), objProjDTO.size(), objProjDTO, null);
return new ResponseEntity<dataTableDTO>(data, HttpStatus.OK);
}
I just want to know how to access the GetMapping notation through postman. I already try but i got error
error image

Put a #RequestParam annotation on your draw variable?
#GetMapping
public ResponseEntity<dataTableDTO> getProject(HttpServletRequest request, #RequestParam(name="draw") int draw) throws Exception {...}

Related

Handle Sharp In Controller And Get Id

There was a jsp application. I have just converted to spring boot application. I want to continue to use same links to handle company's information. Old urls are like /Dashboard.jsp#/company/10712. I have tried to handle company id but it didn't wook. How can I handle company id ?
#GetMapping("/Dashboard.jsp#/company/{id}")
public void try(#PathVariable String id) {
System.out.println(id);
}
I have also tried;
adding
server.tomcat.relaxed-path-chars=#
in application properties.
#RequestMapping(value = ERROR_PATH, produces = "text/html")
public Object errorHtml(HttpServletRequest request, HttpServletResponse response) {
if (response.getStatus() == HttpStatus.NOT_FOUND.value()) {
return new ModelAndView("redirect:" + StringUtils.getBaseUrl(request) + "/?page=error", HttpStatus.FOUND);
} else {
return new ModelAndView("redirect:" + StringUtils.getBaseUrl(request) + "/?page=error");
}
}
This function handle 404.
request.getAttribute("javax.servlet.forward.request_uri")
returns /esir/Dashboard.jsp. There is no # and others.

what code should i modify in this SpringBoot org.opentest4j.AssertionFailedError?

made a test code but failed,
the Error is :
error
and here's the test code
#Test
public void Posts_update() throws Exception {
Posts savedPosts = postsRepository.save(Posts.builder()
.title("title")
.content("content")
.author("author")
.build());
Long updateId = savedPosts.getId();
String expectedTitle = "title2";
String expectedContent = "content2";
PostsUpdateRequestDto requestDto = PostsUpdateRequestDto.builder()
.title(expectedTitle)
.content(expectedContent)
.build();
String url = "http://localhost:" + port + "/api/v1/posts/" + updateId;
HttpEntity<PostsUpdateRequestDto> requestEntity = new HttpEntity<>(requestDto);
// when
ResponseEntity<Long> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, Long.class);
// then
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getBody()).isGreaterThan(0L);
List<Posts> all = postsRepository.findAll();
assertThat(all.get(0).getTitle()).isEqualTo(expectedTitle);
assertThat(all.get(0).getContent()).isEqualTo(expectedContent);
}
I'm trying this from a book but i can't find answer here.
You are saving entity with title "title" and expecting it to be "title2" when you fetch it. Either change your entity data or expected title. Replace repository save with below
Posts savedPosts = postsRepository.save(Posts.builder()
.title("title2")
.content("content")
.author("author")
.build());
This should work

HttpClientErrorException$BadRequest: 400 : [no body] when calling restTemplate.postForObject

I am calling a POST service getOrder3 written in SpringBoot which is working fine (tested in Postman), but getting error when called via restTemplate.postForObject from another service. I tried 2 versions of the client service getOrderClient and getOrderClient2, but both are giving same error :
HttpClientErrorException$BadRequest: 400 : [no body]
Please find the details below. Any help is appreciated.
getOrder3
#PostMapping(value="/getOrder3/{month}",produces="application/json")
public ResponseEntity<OrderResponse> getOrder3(
#PathVariable("month") String month,
#RequestParam String parmRequestSource,
#RequestParam(required=false) String parmAudienceType,
#RequestBody OrderRequestForm orderRequestForm) {
OrderResponse orderResponse = new OrderResponse();
log.info("In getOrder3...parmRequestSource = " + parmRequestSource + " parmAudienceType = " + parmAudienceType);
try {
//validate JSON schema
//orderService.validateMessageAgainstJSONSchema(orderRequestForm);
//process order
orderResponse = orderService.processOrder(orderRequestForm);
orderResponse.setParmRequestSource(parmRequestSource);
orderResponse.setParmAudienceType(parmAudienceType);
orderResponse.setMonth(month);
}catch (Exception e) {
throw new OrderException("101", e.getMessage(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(orderResponse,HttpStatus.OK);
}
The service is working fine , tested in postman
Now when I try to call via another microservice via restTemplate.postForObject, I get the error. Tried 2 versions of the client as below, getOrderClient and getOrderClient2
getOrderClient
#PostMapping(value="/getOrderClient/{month}",produces="application/json")
public OrderResponse getOrderClient(
#PathVariable("month") String month,
#RequestParam String parmRequestSource,
#RequestParam String parmAudienceType,
#RequestBody OrderRequestForm orderRequestForm) throws URISyntaxException, JsonProcessingException {
RestTemplate restTemplate = new RestTemplate();
URI uri = new URI("http://localhost:51001/orders/v1/getOrder/"+month+"?parmRequestSource="+parmRequestSource+"&parmAudienceType="+parmAudienceType);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String requestJson = new ObjectMapper().writeValueAsString(orderRequestForm);
HttpEntity<String> httpEntity = new HttpEntity<String>(requestJson,headers);
String response = restTemplate.postForObject(uri, httpEntity, String.class);
return new ObjectMapper().readValue(response, OrderResponse.class);
}
getOrderClient2
#PostMapping(value="/getOrderClient2/{month}",produces="application/json")
public OrderResponse getOrderClient2(
#PathVariable("month") String month,
#RequestParam String parmRequestSource,
#RequestParam String parmAudienceType,
#RequestBody OrderRequestForm orderRequestForm) throws URISyntaxException, JsonProcessingException {
RestTemplate restTemplate = new RestTemplate();
URI uri = new URI("http://localhost:51001/orders/v1/getOrder/"+month+"?parmRequestSource="+parmRequestSource+"&parmAudienceType="+parmAudienceType);
return restTemplate.postForObject(uri, orderRequestForm, OrderResponse.class);
}
Both are giving same error :
HttpClientErrorException$BadRequest: 400 : [no body]
Please suggest.
To improve the visibility of the solution, #astar fixed the issue by annotating the model object's properties with #JsonProperty.

Controller Testing For SPRING-MVC

I am getting error in my controller Saying Null Pointer Exception while When I don't perform the testing. Everything works fine.
Controller :
#RequestMapping(value = "/studentinsection/{sectionId}", method = RequestMethod.GET)
public ModelAndView studentInSectionForm(#ModelAttribute("studentInSectionFormData") StudentInSectionForm studentInSectionFormData,
#PathVariable Integer sectionId,
ModelMap model) {
ArrayList<StudentInSections> studentInSectionList = (ArrayList<StudentInSections>)
studentInSectionsService.retrieveAllStudentInSections(sectionId, 1);
StudentSection studentSection = studentSectionService.retrieveStudentSection(sectionId);
logger.info("section Name is:" + studentSection.getSectionName());
ArrayList<User> userList = new ArrayList<User>();
for (StudentInSections studentInSections : studentInSectionList) {
String studentName =
(userService.retrieveUserName(studentInSections.getStudentId(), 1));
User users = userService.retrieveUser(studentName);
userList.add(users);
}
logger.info("sectionId is " + sectionId);
ArrayList<User> allStudents = (ArrayList<User>)
userService.retrieveAllStudents();
studentInSectionFormData.setStudentInSectionList(studentInSectionList);
model.addAttribute("studentList", allStudents);
model.addAttribute("userList", userList);
model.addAttribute("studentSectionName", studentSection.getSectionName());
model.addAttribute("studentSectionId", studentSection.getSectionId());
return new ModelAndView("studentinsection", "studentInSectionFormData", studentInSectionFormData);
}
Testing is as follow:
#Test
public void testStudentInSectionForm() throws Exception {
mockMvc.perform(get("/studentinsection/1"))
.andExpect(status().isFound())
.andExpect(redirectedUrl("studentinsection"));
}
this is passing everything into the controller fine even sectionId is getting printed 1 in logger than also studentin sectionList returns nullMointerException. help me to resolve my problem.. Thanx
It slooks like the context is not being loaded correctly. What is the exception stacktrace.
You can also view the request if you do :
mockMvc.perform(get("/studentinsection/1"))
.andExpect(status().isFound())
.andDo(print())

Spring MVC + GWT : Redirect Issue

I am using Spring annotated MVC framework in an app which I am developing.
Following is the issue I am facing:
I have Controller which does a redirect, after a POST:
#RequestMapping(value = "/emdm-viewer-redirect.do", method = RequestMethod.POST)
public ModelAndView getMetricKeysAndRedirect(#RequestParam Object jsonObject, Model model)
{
ModelAndView modelAndView = new ModelAndView("redirect:/mdm-viewer.do");
.....
.....
....//make some service calls and populate value1
...
modelAndView.addobject("param1", value1);
return modelAndView;
}
I have another controller which is mapped to URL mdm-viewer.do (The redirect URL mentioned above):
#RequestMapping(value = "/mdm-viewer.do", method = RequestMethod.GET)
public String getMDMViewer(Model model) {
return "mdmViewer"; //returns a mdmViewer.jsp
}
Please note that the mdmviewer.jsp is a GWT entrypoint which is in classpath.
I have my firebug window open which tells me that a GET request was made for mdm-viewer.do, but it gives me a blank response. In fact, it does not redirect to the new jsp and stays on the same page from where the POST request was made.
However, if I copy the firebug URL and open it in a new window of my browser, I see the expected results.
Any ideas what I am doing wrong here? Tried to google it a lot, but can't find a similar issue anywhere.
Eventually, I returned a ModelAndView back from the POST method using a
#ResponseBody
And in my GWT Module, I used the response.getText() output to do a
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
JSONObject jsonObject = (JSONObject) JSONParser.parse(response.getText());
String viewName = jsonObject.get("viewName").isString().stringValue();
JSONObject jsonParams = jsonObject.get("model").isObject();
Set<String> chartKeys = jsonParams.keySet();
String redirectURL = viewName + "?";
for (String keyString : chartKeys) {
redirectURL = redirectURL + keyString + "=" + jsonParams.get(keyString).isString().stringValue() + "&";
}
Window.open(GWT.getHostPageBaseURL() + redirectURL, "_self", "");
}
}

Resources