How to set Jexcel name in Spring mvc? - spring

I'm following with mkyong Jexcel with Spring tutorial and everything looks fine.it can create excel file and write sheet except one thing is I can't change my excel file name? It will display file name same as my link to controller.
Here is example
<li><h3>Jexcel Showcase</h3></li>
It will always create excel file name "report.html.xls". Anyone know how to change file name??
This is my controller
#RequestMapping(method=RequestMethod.POST)
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//dummy data
revenueData.put("Jan-2010", "$100,000,000");
revenueData.put("Feb-2010", "$110,000,000");
revenueData.put("Mar-2010", "$130,000,000");
revenueData.put("Apr-2010", "$140,000,000");
revenueData.put("May-2010", "$200,000,000");
return new ModelAndView("jexcelSuccess","revenueData",revenueData);
}
and buildExcelDocument method
protected void buildExcelDocument(Map model, WritableWorkbook workbook,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");
WritableSheet sheet = workbook.createSheet("Revenue Report", 0);
WritableSheet sheet2 = workbook.createSheet("Test Report", 1);
WritableSheet sheet3 = workbook.createSheet("Hello Report", 2);
sheet.addCell(new Label(0, 0, "Month"));
sheet.addCell(new Label(1, 0, "Revenue"));
int rowNum = 1;
for (Map.Entry<String, String> entry : revenueData.entrySet()) {
//create the row data
sheet.addCell(new Label(0, rowNum, entry.getKey()));
sheet.addCell(new Label(1, rowNum, entry.getValue()));
rowNum++;
}
}
Thank in advance,
Mart

Add this line to the controller:
response.setHeader("Content-Disposition", "attachment; filename=\"whatEver.xls\"");

Related

How to use MockMVC test the controller which use org.apache.commons.fileupload?

My Controller use " org.apache.commons.fileupload " realized the file UPload.
see it:
#PostMapping("/upload")
public String upload2(HttpServletRequest request) throws Exception {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
boolean uploaded = false;
while (iter.hasNext() && !uploaded) {
FileItemStream item = iter.next();
if (item.isFormField()) {
item.openStream().close();
} else {
String fieldName = item.getFieldName();
if (!"file".equals(fieldName)) {
item.openStream().close();
} else {
InputStream stream = item.openStream();
// dosomething here.
uploaded = true;
}
}
}
if (uploaded) {
return "ok";
} else {
throw new BaseResponseException(HttpStatus.BAD_REQUEST, "400", "no file field or data file is empty.");
}
}
and my MockMvc code is
public void upload() throws Exception {
File file = new File("/Users/jianxiaowen/Documents/a.txt");
MockMultipartFile multipartFile = new MockMultipartFile("file", new FileInputStream(file));
HashMap<String, String> contentTypeParams = new HashMap<String, String>();
contentTypeParams.put("boundary", "----WebKitFormBoundaryaDEFKSFMY18ehkjt");
MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(baseUrl+"/upload")
.content(multipartFile.getBytes())
.contentType(mediaType)
.header(Origin,OriginValue)
.cookie(cookie))
.andReturn();
logResult(mvcResult);
}
my controller is right , it has successed in my web project,
but I want to test it use MvcMock, it has some mistake, see :
can someOne can help me?
"status":"400","msg":"no file field or data file is empty.","data":null
I don't know why it says my file is empty.
my English is poor, thank you very much if someone can help me.
The MockMvc can be used for integration testing for controllers using Apache Commons Fileupload too!
Import the org.apache.httpcomponents:httpmime into your pom.xml or gradle.properties
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
Update the code to use MultipartEntityBuilder to build the multipart request on the client, and then serialize the entity into bytes, which is then set in the request content
public void upload() throws Exception {
File file = new File("/Users/jianxiaowen/Documents/a.txt");
String boundary = "----WebKitFormBoundaryaDEFKSFMY18ehkjt";
// create 'Content-Type' header for multipart along with boundary
HashMap<String, String> contentTypeParams = new HashMap<String, String>();
contentTypeParams.put("boundary", boundary); // set boundary in the header
MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
// create a multipart entity builder, and add parts (file/form data)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
HttpEntity multipartEntity = MultipartEntityBuilder.create()
.addPart("file", new FileBody(file, ContentType.create("text/plain"), file.getName())) // add file
// .addTextBody("param1", "value1") // optionally add form data
.setBoundary(boundary) // set boundary to be used
.build();
multipartEntity.writeTo(outputStream); // or getContent() to get content stream
byte[] content = outputStream.toByteArray(); // serialize the content to bytes
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post(baseUrl + "/upload")
.contentType(mediaType)
.content(content) // finally set the content
.header(Origin,OriginValue)
.cookie(cookie)
).andReturn();
logResult(mvcResult);
}
Can you try the below?
mockMvc.perform(
MockMvcRequestBuilders.multipart(baseUrl+"/upload")
.file(multiPartFile)
).andReturn();
Update:
You need to update the controller to handle the MultipartFile:
#PostMapping("/upload")
public String upload2(#RequestParam(name="nameOfRequestParamWhichContainsFileData")
MultipartFile uploadedFile, HttpServletRequest request) throws Exception {
//the uploaded file gets copied to uploadedFile object.
}
You need not use another library for managing file uploads. You can use the file upload capabilities provided by Spring MVC.

Stream data in response for Spring MVC 4.3 Using Java 8, Tomcat 7

Below is the piece of code that causes OutOfMemory issue when I run my xyz.war in tomcat 7 with Java 8.
In Below code I am creating a CSV response of the data that was fetched from MongoDB via cursor.
#RequestMapping(value = "/elements/{elementname}/records", method = RequestMethod.GET)
public ModelAndView getAllRecords(
HttpServletRequest request, HttpServletResponse response,
#RequestParam(value = "customerid", required = true) long customerId,
#RequestParam(value = "userid", required = true) long userId,
#RequestParam(value = "query", required = false) String query,
throws Exception {
Map < String, Object > model = new HashMap < String, Object > ();
JsonObject records = elementService.searchRecords(query);
ModelAndViewData msvd = elementService.commonRestService
.getModelAndView("dataObject", "streamingView");
return new ModelAndView(msvd.getViewName(), handleCsvReportTypeRequest(records, customerId, userId));
}
public Map < String, Object > handleCsvReportTypeRequest(JsonObject records,
String elementName, long customerId, long userId) throws Exception {
StringBuffer csvData = new StringBuffer();
// create csv data
ModelAndViewData modelAndStreamingViewData = commonRestService.getModelAndView(
"dataObject", "streamingView");
byte[] byteArray = String.valueOf(csvData).getBytes();
InputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
model.put(modelAndStreamingViewData.getModelAttributeName(), byteArrayInputStream);
model.put(DownloadConstants.CONTENT_TYPE, DownloadConstants.CSV_CONTENT_TYPE);
model.put(DownloadConstants.FILENAME, "XYZ.csv");
model.put(DownloadConstants.LAST_MODIFIED, new Date(System.currentTimeMillis()));
model.put(DownloadConstants.CONTENT_LENGTH, Integer.valueOf(byteArray.length));
return model;
}
How can I stream CSV data back to the user without creating a huge data in memory and then passing to the user?
Use a Buffered read and write the response in HttpResponse object.
Try this way:
Spring MVC : large files for download, OutOfMemoryException

how to access GetMapping notation from postman with HttpServletRequest

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 {...}

How to create a link with ApachePOI?

I want to set the data inside a cell to be a link :
public class TestExcelExport extends AbstractXlsxView {
#Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=\"export.xlsx\"");
Sheet sheet = workbook.createSheet("test");
Row row_1 = sheet.createRow(1);
row_1.createCell(0).setCellValue("some data");
}
}
How to make the cell data to be a link pointing to a file in the system directory ?
CreationHelper createHelper = workbook.getCreationHelper();
Cell cell = row_1.createCell((short)0);
cell.setCellValue("System File Link");
link = createHelper.createHyperlink(Hyperlink.LINK_FILE);
link.setAddress("/usr/somedir/somefile.someext");
cell.setHyperlink(link);
This would do.

Download A File On click of a link using spring mvc

When I click on any link the content should be downloaded
But this is what I get.
MastercourseController.java
#RequestMapping(value = { ControllerUriConstant.download_file }, method = RequestMethod.GET)
#ResponseBody
public void downloadingAFileById(#RequestParam("id") String id, Model model, HttpServletRequest request)
throws TechnoShineException, IOException {
String filePath = "D:/dev/testFIle.txt";
long download = Long.parseLong(id);
byte[] b = masterCourseFileFormService.getAllDownloadable(download);
OutputStream outputStream = new FileOutputStream(filePath);
outputStream.write(b);
outputStream.close();
}
MasterCourseService
public byte[] getAllDownloadable(long id) throws TechnoShineException
{
return masterCourseFormUploadDao.getAllDownloadableFiles(id);
}
MasterCourseDao
public byte[] getAllDownloadableFiles(long id) throws TechnoShineException
{
return masterCourseFormUploadMapper.getAllDownloadable(id);
}
MasterCourseMapper
public byte[] getAllDownloadable(long id) throws TechnoShineException;
You are writing the data returned by getAllDownloadable(..) to a hard-coded file. Are you sure that is what you want? I think you want to write the content returned by getAllDownloadable(..) to be written into the response. That can be done by adding a method parameter of the type HttpServletResponse to your mapping and writing into the output stream returned by HttpServletResponse#getOutputStream() and flushing (not closing!) that stream at the end.
Furthermore you have to remove the #ResponseBody annotation as this is meant to be used if the value that is returned by the mapping method returns the data that should directly be sent to the client (i.e. when sending a JSON data object or a string) without passing it to the template engine. As you are not returning anything you can remove this annotation.
Furthermore you have to set the content type of your response by invoking HttpServletResponse#setContentType(contentType: String).
In your case, the invocation would be the following:
response.setContentType("text/plain");
You complete method would look like this:
#RequestMapping(
value = ControllerUriConstant.download_file,
method = RequestMethod.GET
)
public void downloadingAFileById(#RequestParam("id") String id, HttpServletResponse response)
throws TechnoShineException, IOException {
long download = Long.parseLong(id);
byte[] b = masterCourseFileFormService.getAllDownloadable(download);
response.getOutputStream().write(b);
response.getOutputStream().flush();
}

Resources