Need a way to instantiate ZipOutputStream object in the service layer
-
16-06-2021 - |
Question
I have the following block of code in my bean class -
HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
From my bean I call my service layer, which in turn calls the database layer, retrieves data and writes the files generated in a ZIP file in the service layer. I have an issue where I do not have a clue what to do if there are no files generated.
When I instantiate ZipOutputStream object in my bean, it creates a ZIP file and opens up a "Opening Extracts.zip" window, and when I click on OK, I get an error because there are no files in the ZIP folder.
Can somoone please tell me if there is any way I can move the zos instantiation to the service layer without having to pass the response object?
Thanks, Raaz
Solution
I found I can do the following to fix my issue -
In my bean class, I wrote the following code -
HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
ByteArrayOutputStream outputStream = null;
try {
outputStream = //Call service to generate the extract, return outputStream ;
if(outputStream != null){
response.setContentType(T3Constants.MIME_ZIP);
response.setHeader(T3Constants.CONTENT_DISPOSITION, ATTACH_FILE_NAME);
response.getOutputStream().write(outputStream.toByteArray());
response.flushBuffer();
FacesContext.getCurrentInstance().responseComplete();
outputStream.close();
} else {
formatFacesMessage(FacesMessage.SEVERITY_WARN, "No data for selected filter", "No data for selected filter");
}
}
In my service, I wrote the following code -
ByteArrayOutputStream outputStream = null;
if(CollectionUtils.isNotEmpty(list returned from DB)) {
outputStream = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(outputStream);
//Add files to ZIP
outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
zos.putNextEntry(new ZipEntry(xlsName.toString()));
zos.write(outputStream.toByteArray());
zos.flush();
zos.close();
return outputStream;
}
Thanks, Raaz