Skip to content

Commit

Permalink
Revert "Consolidate download endpoints (#662)"
Browse files Browse the repository at this point in the history
This reverts commit 03854ee.
  • Loading branch information
spokenbird committed Feb 9, 2022
1 parent f5497f6 commit 47a9a2f
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 189 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@ public class FileDownloadController {
private static final String NOT_FOUND_MESSAGE = "Could not find any application with this ID for download";
private static final String UNSUBMITTED_APPLICATION_MESSAGE = "Submitted time was not set for this application. It is either still in progress or the submitted time was cleared for some reason.";
private static final String NON_APPLICABLE_DOCUMENT_TYPE = "Could not find a %s application with this ID for download";
private static final String DOWNLOAD_DOCUMENT_ZIP = "Download zip file for application ID %s";
private static final String NO_DOWNLOAD_DOCUMENT_ZIP = "No documents to download in zip file for application ID %s";
private final XmlGenerator xmlGenerator;
private final PdfGenerator pdfGenerator;
private final ApplicationData applicationData;
Expand Down Expand Up @@ -69,54 +67,6 @@ ResponseEntity<byte[]> downloadPdf(HttpSession httpSession) {
ApplicationFile applicationFile = pdfGenerator.generate(applicationData.getId(), CAF, CLIENT);
return createResponse(applicationFile);
}

@GetMapping("/download/{applicationId}")
ResponseEntity<byte[]> downloadAllDocumentsWithApplicationId(@PathVariable String applicationId, HttpSession httpSession)
throws IOException{
if (applicationData == null || applicationData.getId() == null){
log.info("Application is empty or the applicationId is null when client attempts to download pdfs zip file.");
return createRootPageResponse();
}
MDC.put("applicationId", applicationData.getId());
MDC.put("sessionId", httpSession.getId());
log.info("Client with session: " + httpSession.getId() + " Downloading application with id: " + applicationData.getId());
Application application = applicationRepository.find(applicationId);
List<ApplicationFile> applicationFiles = new ArrayList<>();

if(applicationData.isCAFApplication()) {
ApplicationFile applicationFileCAF = pdfGenerator.generate(applicationId, CAF, CLIENT);
if (null != applicationFileCAF && applicationFileCAF.getFileBytes().length > 0) {
applicationFiles.add(applicationFileCAF);
}
}
if(applicationData.isCCAPApplication()) {
ApplicationFile applicationFileCCAP = pdfGenerator.generate(applicationId, CCAP, CLIENT);
if (null != applicationFileCCAP && applicationFileCCAP.getFileBytes().length > 0) {
applicationFiles.add(applicationFileCCAP);
}
}
if(applicationData.isCertainPopsApplication()) {
ApplicationFile applicationFileCP = pdfGenerator.generate(applicationId, CERTAIN_POPS, CLIENT);
if (null != applicationFileCP && applicationFileCP.getFileBytes().length > 0) {
applicationFiles.add(applicationFileCP);
}
}

List<UploadedDocument> uploadedDocs = applicationData.getUploadedDocs();
if(null !=uploadedDocs) {
for (int i = 0; i < uploadedDocs.size(); i++) {
UploadedDocument uploadedDocument = uploadedDocs.get(i);
ApplicationFile fileToSend = pdfGenerator
.generateForUploadedDocument(uploadedDocument, i, application, null);

if (null != fileToSend && fileToSend.getFileBytes().length > 0) {
applicationFiles.add(fileToSend);
}
}
}

return createZipFileFromApplications(applicationFiles, applicationId);
}

@GetMapping("/download-ccap")
ResponseEntity<byte[]> downloadCcapPdf() {
Expand Down Expand Up @@ -168,42 +118,35 @@ ResponseEntity<byte[]> downloadDocsWithApplicationId(@PathVariable String applic
applicationFiles.add(fileToSend);
}
}
return createZipFileFromApplications(applicationFiles, applicationId);
}

private ResponseEntity<byte[]> createZipFileFromApplications(List<ApplicationFile> applicationFiles,
String applicationId) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos)) {

try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos)) {

applicationFiles.forEach(file -> {
ZipEntry entry = new ZipEntry(file.getFileName());
entry.setSize(file.getFileBytes().length);
try {
zos.putNextEntry(entry);
zos.write(file.getFileBytes());
zos.closeEntry();
} catch (IOException e) {
log.error("Unable to write file, " + file.getFileName(), e);
}
ZipEntry entry = new ZipEntry(file.getFileName());
entry.setSize(file.getFileBytes().length);
try {
zos.putNextEntry(entry);
zos.write(file.getFileBytes());
zos.closeEntry();
} catch (IOException e) {
log.error("Unable to write file, " + file.getFileName(), e);
}
});

zos.close();
baos.close();

// The minimum size of a .ZIP file is 22 bytes even when empty because of metadata
if (baos.size() > 22) {
String msg = String.format(DOWNLOAD_DOCUMENT_ZIP, applicationId);
log.info(msg);
return createResponse(baos.toByteArray(), "MNB_application_" + applicationId + ".zip");
return createResponse(baos.toByteArray(), applicationId + ".zip");
} else {
// Applicant should not have been able to "submit" documents without uploading any.
String msg = String.format(NO_DOWNLOAD_DOCUMENT_ZIP, applicationId);
log.warn(msg);
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
// Applicant should not have been able to "submit" documents without uploading any.
log.warn("No documents to download");
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}
}
}

private ResponseEntity<byte[]> createResponse(ApplicationFile applicationFile) {
return createResponse(applicationFile.getFileBytes(), applicationFile.getFileName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public ApplicationFile generateForUploadedDocument(UploadedDocument uploadedDocu
log.warn("Unsupported file-type: " + extension);
}

if (extension.equals("pdf") && coverPage != null) {
if (extension.equals("pdf")) {
fileBytes = addCoverPageToPdf(coverPage, fileBytes);
}

Expand Down
3 changes: 1 addition & 2 deletions src/main/resources/messages.properties
Original file line number Diff line number Diff line change
Expand Up @@ -456,8 +456,7 @@ success.title=Success
success.done-your-application-has-been-submitted=Done! Your application has been submitted.
success.done-your-application-and-docs-have-been-submitted=Done! Your application and documents have been submitted.
success.helpful-resources=Helpful resources
success.download-my-application=Save a copy of your application for your records:
success.download-your-application=Download your application
success.download-my-application=Download a copy of your application for your records:
success.combined-application={0} Application
success.child-care-application=Child Care Application
success.apply-for-healthcare-coverage=Apply for healthcare coverage!
Expand Down
14 changes: 12 additions & 2 deletions src/main/resources/templates/success.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,20 @@ <h2 class="h3" th:text="#{success.helpful-resources}"></h2>
<div class="grid__item width-five-sixths">
<div class="spacing-above-0 spacing-below-15"
th:text="#{success.download-my-application}"></div>
<th:block
th:if="${documents.contains(T(org.codeforamerica.shiba.output.Document).CAF)}">
<div class="spacing-below-10">
<a class="link--subtle" th:href="@{/download/{id}(id=${applicationId})}" id="download"
th:text="#{success.download-your-application}"></a>
<a class="link--subtle" href="/download" id="download-caf"
th:text="#{success.combined-application(${combinedFormText})}"></a>
</div>
</th:block>
<th:block
th:if="${documents.contains(T(org.codeforamerica.shiba.output.Document).CCAP)}">
<div>
<a class="link--subtle spacing-below-0" href="/download-ccap" id="download-ccap"
th:text="#{success.child-care-application}"></a>
</div>
</th:block>
</div>
</div>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ void fullApplicationWithDocumentUploads() {
SuccessPage successPage = new SuccessPage(driver);
assertThat(successPage.findElementById("submission-date").getText()).contains(
"Your application was submitted to Hennepin County (612-596-1300) and Mille Lacs Band of Ojibwe Tribal Nation Servicing Agency (320-532-7407) on January 1, 2020.");
applicationId = downloadPdfs();
applicationId = downloadPdfs(true, true);

// CCAP fields
assertCcapFieldEquals("APPLICATION_ID", applicationId);
Expand Down
29 changes: 15 additions & 14 deletions src/test/java/org/codeforamerica/shiba/journeys/JourneyTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,9 @@ protected void assertCcapFieldEquals(String fieldName, String expectedVal) {
TestUtils.assertPdfFieldEquals(fieldName, expectedVal, ccap);
}

protected String signApplicationAndDownloadApplicationZipFiles(String signature) {
protected String signApplicationAndDownloadPdfs(String signature,
boolean shouldHaveCafDownloadLink,
boolean shouldHaveCcapDownloadLink) {
testPage.enter("applicantSignature", signature);
testPage.clickButton("Submit");
testPage.clickContinue();
Expand All @@ -111,36 +113,35 @@ protected String signApplicationAndDownloadApplicationZipFiles(String signature)

// Next steps screen
testPage.clickContinue();
return downloadPdfs();
return downloadPdfs(shouldHaveCafDownloadLink, shouldHaveCcapDownloadLink);
}

protected String downloadPdfs() {
protected String downloadPdfs(boolean shouldHaveCafDownloadLink,
boolean shouldHaveCcapDownloadLink) {
// Download CAF
SuccessPage successPage = new SuccessPage(driver);
successPage.downloadPdfZipFile();
await().until(zipDownloadCompletes(successPage));
unzipFiles();
var pdfs = getAllFiles();
caf = pdfs.getOrDefault(CAF, null);
ccap = pdfs.getOrDefault(CCAP,null);
assertThat(successPage.CAFdownloadPresent()).isEqualTo(shouldHaveCafDownloadLink);
assertThat(successPage.CCAPdownloadPresent()).isEqualTo(shouldHaveCcapDownloadLink);
successPage.downloadPdfs();
await().until(pdfDownloadCompletes(successPage));
var pdfs = getAllFiles();
caf = pdfs.getOrDefault(CAF, null);
ccap = pdfs.getOrDefault(CCAP, null);
return getApplicationId();
}

private String getApplicationId() {
// Retrieves the application id from the filename of a downloaded PDF
return Arrays.stream(Objects.requireNonNull(path.toFile().listFiles()))
.filter(file -> file.getName().endsWith(".pdf"))
.sorted((f1,f2)-> Long.compare(f2.lastModified(), f1.lastModified()))
.map(File::getName)
.findFirst()
.orElseThrow()
.split("_")[4];
}

@NotNull
protected Callable<Boolean> zipDownloadCompletes(SuccessPage successPage) {
return () -> getZipFile().size() == successPage.countDownloadLinks();
protected Callable<Boolean> pdfDownloadCompletes(SuccessPage successPage) {
return () -> getAllFiles().size() == successPage.pdfDownloadLinks();
}

protected void getToHomeAddress(String county, List<String> programSelections) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ void nonExpeditedFlow() {
testPage.clickContinue();

// Finish Application
applicationId = signApplicationAndDownloadApplicationZipFiles(signature);
applicationId = signApplicationAndDownloadPdfs(signature, true, false);
assertApplicationSubmittedEventWasPublished(applicationId, MINIMUM, 1);

// PDF assertions
Expand Down Expand Up @@ -171,7 +171,7 @@ void expeditedFlow() {
testPage.clickContinue();

// Finish Application
applicationId = signApplicationAndDownloadApplicationZipFiles(signature);
applicationId = signApplicationAndDownloadPdfs(signature, true, false);
SuccessPage successPage = new SuccessPage(driver);
assertThat(successPage.findElementById("snapExpeditedNotice").getText()).contains(
"You were recommended for expedited food assistance (SNAP).");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
package org.codeforamerica.shiba.output;

import static org.assertj.core.api.Assertions.assertThat;
import static org.codeforamerica.shiba.Program.CASH;
import static org.codeforamerica.shiba.Program.EA;
import static org.codeforamerica.shiba.Program.GRH;
import static org.codeforamerica.shiba.Program.SNAP;
import static org.codeforamerica.shiba.application.Status.DELIVERED;
import static org.codeforamerica.shiba.output.Document.CAF;
import static org.codeforamerica.shiba.output.Document.CCAP;
Expand Down Expand Up @@ -34,7 +30,6 @@
import org.codeforamerica.shiba.output.xml.XmlGenerator;
import org.codeforamerica.shiba.pages.data.ApplicationData;
import org.codeforamerica.shiba.pages.data.UploadedDocument;
import org.codeforamerica.shiba.testutilities.PagesDataBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
Expand All @@ -57,9 +52,6 @@ class FileDownloadControllerTest {
void setUp() {
applicationData = new ApplicationData();
applicationData.setId("some-app-id");
applicationData.setPagesData(new PagesDataBuilder()
.withPageData("choosePrograms", "programs", List.of(SNAP, CASH, GRH, EA))
.build());
application = Application.builder()
.completedAt(ZonedDateTime.now())
.documentStatuses(List.of(new DocumentStatus("", CCAP, "", DELIVERED)))
Expand All @@ -74,26 +66,7 @@ void setUp() {
.build();

}
@Test
void shouldPassScreensToServiceWithApplicationIDToGeneratePdfFile() throws Exception {

var applicationId = "9870000123";
ApplicationData applicationData = new ApplicationData();
applicationData.setId(applicationId);

Application application = Application.builder().applicationData(applicationData)
.build();

when(pdfGenerator.generate(anyString(), any(), any())).thenReturn(new ApplicationFile("TEST".getBytes(), ""));
when(applicationRepository.find(applicationId)).thenReturn(application);
MvcResult result = mockMvc.perform(get("/download/9870000123"))
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION,
String.format("filename=\"%s\"", "MNB_application_"+applicationId + ".zip")))
.andExpect(status().is2xxSuccessful()).andReturn();

byte[] actualBytes = result.getResponse().getContentAsByteArray();
assertThat(actualBytes).hasSizeGreaterThan(22);
}
@Test
void shouldPassScreensToServiceToGeneratePdfFile() throws Exception {
when(pdfGenerator.generate(anyString(), any(), any()))
Expand Down Expand Up @@ -220,7 +193,7 @@ void shouldReturnDocumentsForApplicationId() throws Exception {
MvcResult result = mockMvc.perform(
get("/download-docs/9870000123"))
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION,
String.format("filename=\"%s\"", "MNB_application_"+applicationId + ".zip")))
String.format("filename=\"%s\"", applicationId + ".zip")))
.andExpect(status().is2xxSuccessful())
.andReturn();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,11 @@ void userCanCompleteTheExpeditedFlowWithoutBeingExpedited() throws Exception {
void partialFlow() throws Exception {
getToDocumentUploadScreen();
completeDocumentUploadFlow();

FormPage page = new FormPage(getPage("success"));
assertThat(page.getLinksContainingText("Download your application")).hasSizeGreaterThan(0);
assertThat(page.getLinksContainingText("Download your application").get(0).attr("href"))
.contains("/download/");
assertThat(page.getLinksContainingText("Emergency Application")).hasSizeGreaterThan(0);
assertThat(page.getLinksContainingText("Emergency Application").get(0).attr("href"))
.isEqualTo("/download");

PDAcroForm caf = this.downloadCaf();
assertPdfFieldEquals("APPLICANT_WRITTEN_LANGUAGE_PREFERENCE", "ENGLISH", caf);
Expand Down
Loading

0 comments on commit 47a9a2f

Please sign in to comment.