Unit testing for Spring MVC controller with Date value as #RequestParam - java

Please help me to pass this Date object to MVCMock.
Since param() only accepts String as values.
I am not sure how to pass Date value here
MockHttpServletRequestBuilder mvcBuilder = get("/pam/holdings/getholdings")
.accept(MediaType.ALL)
.flashAttr("holdingsFilterViewData", holdingsFilter)
.param("group","")
.param("account","")
.param("selectedHoldingsview","");
public String loadSelectedHoldings(
#ModelAttribute("holdingsFilterViewData") HoldingsFilter holdingsFilter,
#RequestParam(value = "account", required = false) String account,
#RequestParam(value = "group", required = false) String group,
#RequestParam(value = "asOfDate", required = false) Date asOfDate,
#RequestParam(value = "selectedHoldingsview", required = false) String selectedViewName,
Model model, HttpServletResponse servletResponse)
throws NoUserLoggedInException, NoKeyOfTypeFoundException,
ParseException, IOException {

Related

Spring Unit Testing File Upload

I am trying to test file upload using spring test.
#Test
public void testUploadDocument() {
File f = new File("C:\\Users\\JC\\Documents\\sample_test_2.xlsx");
System.out.println(f.isFile()+" "+f.getName()+f.exists());
FileInputStream fi1 = new FileInputStream(f);
MockMultipartFile fstmp = new MockMultipartFile("file", f.getName(), "text/plain", fi1);
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(MockMvcRequestBuilders.fileUpload("http://" + hostPort + "/AdminService/rest/document/saveDocument")
.file(fstmp)
.param("siteId","555").param("docTypeId","550").param("docSubTypeId", "5051").param("contentDate", "06-Oct-2017").param("contentDescription", "")
.param("docName", "Test Co-op Unit 2").param("isNewFile", "true"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
It is throwing Requested Method POST not supported even though I declared it as POST. Also I tried MockMvcRequestBuilders.post. But same problem.
#RequestMapping(value = "/saveDocument", method = RequestMethod.POST)
public ResponseEntity<String> saveDocument(
#RequestParam("siteId") Integer siteId, #RequestParam("docTypeId") Integer docTypeId,
#RequestParam("docSubTypeId") Integer docSubTypeId, #RequestParam("docName") String docName,
#RequestParam(value = "contentDescription", required = false) String contentDescription,
#RequestParam(value = "contentDate", required = false) String contentDate, #RequestParam(value = "docId", required = false) Integer docId,
#RequestParam(value = "isNewFile", required = false) boolean isNewFile,
#RequestParam(value = "file", required = false) MultipartFile file)

How to process twilio SMS status callback in java

I have following service method for SMS callback processing
#RequestMapping(value = "/", method = RequestMethod.POST)
#ResponseBody
public void processSms(#RequestParam(value = "MessageStatus", required = false) String messageStatus,
#RequestParam(value = "ApiVersion", required = false) String apiVersion,
#RequestParam(value = "SmsSid", required = false) String smsSid,
#RequestParam(value = "SmsStatus", required = false) String smsStatus,
#RequestParam(value = "To", required = false) String to,
#RequestParam(value = "From", required = false) String from,
#RequestParam(value = "MessageSid", required = false) String messageSid,
#RequestParam(value = "AccountSid", required = false) String accountSid){
TwilioCallBackResponse response = new TwilioCallBackResponse();
response.messageStatus = messageStatus;
response.apiVersion = apiVersion;
response.smsSid = smsSid;
response.smsStatus = smsStatus;
response.to = to;
response.from = from;
response.messageSid = messageSid;
response.accountSid = accountSid;
LOG.info("Incomming twilio callback: " + response.messageStatus);
smsService.processSmsCallback(response);
}
I can get and log response from twilio successfully.
Problem is that in twilio end response error is logged. Should I specify content type or respond with some response body? Any ideas?
This is from twilio log
and error 11200 HTTP retrieval failure is also logged
Status callbacks do not control application flow, so TwiML does not need to be returned in this instance; however, it's recommended that you respond to status callbacks with either a 204 No Content or a 200 OK with Content-Type: text/xml and an empty <Response/> in the body. Failure to respond properly will result in warnings in Debugger.
Ok, based on Jim answer this is what works for me and no more warnings on twilio side
#RequestMapping(value = "/", method = RequestMethod.POST, produces = "text/xml")
#ResponseBody
#ResponseStatus(value = HttpStatus.OK)
public String processSms(#RequestParam(value = "MessageStatus", required = false) String messageStatus,
#RequestParam(value = "ApiVersion", required = false) String apiVersion,
#RequestParam(value = "SmsSid", required = false) String smsSid,
#RequestParam(value = "SmsStatus", required = false) String smsStatus,
#RequestParam(value = "To", required = false) String to,
#RequestParam(value = "From", required = false) String from,
#RequestParam(value = "MessageSid", required = false) String messageSid,
#RequestParam(value = "AccountSid", required = false) String accountSid){
TwilioCallBackResponse response = new TwilioCallBackResponse();
response.messageStatus = messageStatus;
response.apiVersion = apiVersion;
response.smsSid = smsSid;
response.smsStatus = smsStatus;
response.to = to;
response.from = from;
response.messageSid = messageSid;
response.accountSid = accountSid;
LOG.info("Incomming twilio callback: " + JsonUtils.printJson(response));
smsService.processSmsCallback(response);
return "<Response/>";
}

are these pathParams or pathVariable

I have to write an API call
#GET
#Path("/{settingName1, settingName2}")
public Response getNetworkSettingValue(#ApiParam(value = "Name") #QueryParam("name") String name,
#ApiParam(value = "City") #QueryParam("city") String city,
#ApiParam(value = "State") #QueryParam("state") String state) {}
here my doubt is how to get settingName1 & settingName2 values,
can write like
#ApiParam(value = "SettingName1") #PathParam("settingName1") String settingName1
or
#ApiParam(value = "SettingName1") #PathVariable("settingName1") String settingName1
in method declaration.
or
any other way to get those two values
By the #Path annotation, I assume you are using JAX-RS (Jersey, RESTEasy, etc). So it should be:
#ApiParam(value = "SettingName1") #PathParam("settingName1") String settingName1
If you were using Spring, it should be:
#ApiParam(value = "SettingName1") #PathVariable("settingName1") String settingName1
your annotations are mixed up with spring and swagger.
If u want to accesss pathvariables with spring than it have to be like
#RequestMapping(value = "/{settingName1}/{settingName2}", method = equestMethod.GET)
public Response getNetworkSettingValue(#ApiParam(value = "settingName1") #PathVariable final String settingName1,
#ApiParam(value = "settingName2") #PathVariable final String settingName2) {
...
return new Response();
}

spring mvc requestmapping dynamic url

How do I change my request mapping for dynamic urls? URLs might look like this:
http://zz.zz.zz.com:8080/webapp/p1/q9/e3/test?Id=2&maxrows=5
http://zz.zz.zz.com:8080/webapp/a1/b2/c3/test?Id=2&maxrows=5
http://zz.zz.zz.com:8080/webapp/x1/y2/z3/test?Id=2&maxrows=5
Here's the working controller syntax when the url is in this format:
http://zz.zz.zz.com:8080/webapp/test?Id=2&maxrows=5
#RequestMapping(value = "/test", method = RequestMethod.GET)
public #ResponseBody void test(
#RequestParam(value = "Id", required = true) String Id,
#RequestParam(value = "maxrows", required = true) int maxrows
) throws Exception {
System.out.println("Id: " + Id + " maxrows: " + maxrows);
}
Try this:
#RequestMapping(value = "/test/{param1}/{param2}/{param3}")
public #ResponseBody void test(
#RequestParam(value = "Id", required = true) String Id,
#RequestParam(value = "maxrows", required = true) int maxrows,
#PathVariable(value = "param1") String param1,
#PathVariable(value = "param2") String param2,
#PathVariable(value = "param3") String param3) {
...
}
For more information look at Spring Reference Documentation

How do I map different values for a parameter in the same #RequestMapping in Spring MVC?

Suppose I have:
#RequestMapping(params = "action=nuovoprodotto")
public ModelAndView nuovoProdotto(
#RequestParam(value = "page", required = false, defaultValue = "-1") int page,
#RequestParam(value = "action") String action,
#ModelAttribute Prodotto prod, HttpSession session)
throws Exception {
is it possible to map this request to like two or three values of "action" parameter?
I tried many ways like
#RequestMapping(params = "action=nuovoprodotto, action=salvaprodotto")
or
#RequestMapping(params = "action=nuovoprodotto|salvaprodotto")
but they don't work... If I can't what are the solutions, besided writing an handler for every single parameter value combination?
Try this:
#RequestMapping(params = {"action=nuovoprodotto","action=salvaprodotto"})
The params attribute is actually of type String[], but annotations let you write a String in place of a single-element String[], so these two are equivalent:
#RequestMapping(params = {"action=nuovoprodotto"})
and
#RequestMapping(params = "action=nuovoprodotto")
Reference:
#RequestMapping.params()
Update: my bad, as you can read in the section Advanced #RequestMapping options, multiple params are combined using and, not or, so it can't work as specified above.
So I'd say what you have to do is create an alias method with almost the same signature:
#RequestMapping(params = "action=nuovoprodotto")
public ModelAndView nuovoProdotto(
#RequestParam(value = "page", required = false, defaultValue = "-1") int page,
#RequestParam(value = "action") String action,
#ModelAttribute Prodotto prod, HttpSession session)
throws Exception {
// some stuff here
}
#RequestMapping(params = "action=salvaprodotto")
public ModelAndView salvaProdotto(
#RequestParam(value = "page", required = false, defaultValue = "-1") int page,
#RequestParam(value = "action") String action,
#ModelAttribute Prodotto prod, HttpSession session)
throws Exception {
return nuovoProdotto(page, action, prod, session);
}

Categories