Spring Unit Testing File Upload - java

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)

Related

Document a multipart/form-data endpoint with Springfox

I have a POST endpoint which receives a #ModelAttribute parameter. Everything is working ok, but the swagger documentation fails to have the descriptions, examples, etc.
I am using java 11, springboot 2.5.4 and springfox-boot-starter 3.0.0
Here is my code:
#Api
#RestController
#RequestMapping("/foo")
#Validated
public class MyRest {
#PostMapping(value = "/{id}/bar", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
#ApiOperation(value = "Do nothing", notes = "This endpoint does nothing")
public ResponseEntity<String> search(
#ModelAttribute MyModelRequest request,
#ApiParam(value = "Folder ID", required = true)
#PathVariable String id) {
// some business code
return new ResponseEntity<>("lorem ipsum", HttpStatus.OK);
}
}
MyModelRequest
#ApiModel
#Data
public class MyModelRequest {
#ApiParam(name = "fileName", value = "The name of the image to be stored in database")
#ApiModelProperty(value = "name model description", example = "summer picture", required = true)
private String name;
#DecimalMin("0.00")
#DecimalMax("100.00")
#ApiParam(name = "accuracy", value = "The required accuracy")
#ApiModelProperty(value = "Minimum required accuracy", example = "95.15", required = false)
private BigDecimal accuracy;
#ApiParam(name = "marginTop", value = "Top margin of the image")
#ApiModelProperty(value = "Separation between top item and the image", example = "300", required = false)
private Integer marginTop;
#ApiParam(name = "image")
#ApiModelProperty(value = "The image to be stored", example = "vacations.png", required = true)
private MultipartFile image;
}
And this is the generated swagger doc
UPDATE: I noticed that if I change the consumes = { MediaType.MULTIPART_FORM_DATA_VALUE } for consumes = { MediaType.APPLICATION_JSON_VALUE } or remove the whole "consumes" parameter from the endpoint, the documentation shows up correctly, however, doing this will make the fileupload fail.

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

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 {

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

How to access data from RestTemplate as List

I want to access data from a spring boot service. The return type of the data is a List, but every time I access it, the list is empty.
This is my code:
Map<String, String> params = new HashMap<String, String>();
params.put("firstName", "test" );
params.put("lastName", "test1");
ResponseEntity<Person[]> response = restTemplate.getForEntity(url, Person[].class, params);
In this case, response.getBody() is an empty [].
#RequestMapping(value = "/search", method = RequestMethod.GET)
public List<Person> searchUsers(
#RequestParam(value = "firstName", required = false) String firstName,
#RequestParam(value = "lastName", required = false) String lastName,
#RequestParam(value = "email", required = false) String email {
return personService.search(firstName, lastName, email, company);
}
I also tried with String, and Person[], but nothing worked.
Thanks in advance!
#GET
#Path("statement")
#Produces({MediaType.APPLICATION_XML})
public Response statement(#QueryParam("from") String from, #QueryParam("to") String to) {
DB idb = new DB();
List<Transaction> transactions = idb.getTransactionsByDate(from, to);
final GenericEntity<List<Transaction>> entity = new GenericEntity<List<Transaction>>(transactions) {
};
return Response.status(Response.Status.OK).entity(entity).build();
}

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

Categories