Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into feature/dynamic-fil…
Browse files Browse the repository at this point in the history
…e-name

# Conflicts:
#	src/test/java/uk/gov/hmcts/reform/prl/documentgenerator/service/impl/DocumentManagementServiceImplTest.java
  • Loading branch information
khurshedk committed Jan 24, 2024
2 parents fefe953 + 95f2086 commit c603fc5
Show file tree
Hide file tree
Showing 11 changed files with 191 additions and 7 deletions.
2 changes: 1 addition & 1 deletion charts/prl-dgs/values.preview.template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ java:
MANAGEMENT_ENDPOINT_HEALTH_CACHE_TIMETOLIVE: "30000"
DOCMOSIS_SERVICE_DEV_MODE_FLAG: "true"
PDF_TEST_ENABLED: "true"
CCD_CASE_DOCS_AM_API: "http://ccd-case-document-am-api-aat.service.core-compute-aat.internal"
CCD_CASE_DOCS_AM_API: http://prl-ccd-definitions-pr-1730-cdam
AUTH_PROVIDER_SERVICE_CLIENT_BASEURL: "http://rpe-service-auth-provider-{{ .Values.global.environment }}.service.core-compute-{{ .Values.global.environment }}.internal"
IDAM_S2S_URL: "http://rpe-service-auth-provider-{{ .Values.global.environment }}.service.core-compute-{{ .Values.global.environment }}.internal"
DOCMOSIS_SERVICE_BASE_URL: "https://docmosis.aat.platform.hmcts.net"
Expand Down
32 changes: 30 additions & 2 deletions config/owasp/suppressions.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.3.xsd">
<suppress>
<notes><![CDATA[
<suppress>
<notes><![CDATA[log4j-api-2.17.2.jar ,log4j-to-slf4j-2.17.2.jar]]></notes>
<cve>CVE-2022-33915</cve>
</suppress>
<suppress>
<notes><![CDATA[
tomcat-embed-core-9.0.63.jar ]]></notes>
<cve>CVE-2022-34305</cve>
</suppress>
<suppress>
<notes><![CDATA[
tomcat-embed-websocket-9.0.69.jar ]]></notes>
<cve>CVE-2023-41080</cve>
</suppress>
<suppress>
<notes><![CDATA[
spring-core-5.3.20.jar ]]></notes>
<cve>CVE-2016-1000027</cve>
</suppress>
Expand All @@ -11,6 +25,20 @@
<cve>CVE-2023-35116</cve>
<cve>CVE-2022-45688</cve>
</suppress>
<suppress>
<notes><![CDATA[
tomcat-embed-core-9.0.80.jar ]]></notes>
<cve>CVE-2023-42794</cve>
<cve>CVE-2023-42795</cve>
<cve>CVE-2023-45648</cve>
</suppress>
<suppress>
<notes><![CDATA[
tomcat-embed-websocket-9.0.80.jar ]]></notes>
<cve>CVE-2023-42794</cve>
<cve>CVE-2023-42795</cve>
<cve>CVE-2023-45648</cve>
</suppress>
<suppress>
<notes><![CDATA[
spring-security-core-5.6.2.jar]]></notes>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
Expand Down Expand Up @@ -86,9 +87,27 @@ public GeneratedDocumentInfo generateAndUploadDraftPdf(
GenerateDocumentRequest templateData) {
//This service is internal to Divorce system. No need to do service authentication here
log.info("Document generation requested with templateName [{}], placeholders map of size[{}]",
templateData.getTemplate(), templateData.getValues().size());
templateData.getTemplate(), templateData.getValues().size()
);
return documentManagementService.generateAndStoreDraftDocument(templateData.getTemplate(),
templateData.getValues(), authorizationToken);
templateData.getValues(), authorizationToken
);
}

@PostMapping("/convertDocToPdf/{fileName}")
public GeneratedDocumentInfo convertDocumentToPdf(
@PathVariable("fileName") String fileName,
@RequestHeader(value = "Authorization", required = false)
String authorizationToken,
@Parameter(name = "GenerateDocumentRequest", description = "JSON object containing the "
+ "templateName and the placeholder text map", required = true)
@RequestBody
@Valid
GenerateDocumentRequest templateData) {
//This service is internal to Divorce system. No need to do service authentication here
log.info("convertDocumentToPdf is getting called");
return documentManagementService.converToPdf(
templateData.getValues(), authorizationToken, fileName);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ GeneratedDocumentInfo generateAndStoreDocument(String templateName, Map<String,
String authorizationToken);

GeneratedDocumentInfo generateAndStoreDraftDocument(String templateName, Map<String, Object> placeholders,
String authorizationToken);
String authorizationToken);

GeneratedDocumentInfo storeDocument(byte[] document, String authorizationToken, String fileName);

byte[] generateDocument(String templateName, Map<String, Object> placeholders);

GeneratedDocumentInfo converToPdf(Map<String, Object> placeholders, String authorizationToken, String filename);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ public interface PDFGenerationService {

byte[] generate(String templateName, Map<String, Object> placeholders);

byte[] converToPdf(Map<String, Object> placeholders, String fileName);

}
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
package uk.gov.hmcts.reform.prl.documentgenerator.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import uk.gov.hmcts.reform.prl.documentgenerator.domain.request.PdfDocumentRequest;
import uk.gov.hmcts.reform.prl.documentgenerator.exception.PDFGenerationException;
import uk.gov.hmcts.reform.prl.documentgenerator.mapper.TemplateDataMapper;
import uk.gov.hmcts.reform.prl.documentgenerator.service.PDFGenerationService;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
Expand All @@ -40,6 +48,9 @@ public class DocmosisPDFGenerationServiceImpl implements PDFGenerationService {
@Value("${docmosis.service.pdf-service.devMode}")
private String docmosisDevMode;

@Value("${docmosis.service.pdf-service.convert}")
private String docmosisPdfConvertEndpoint;

@Override
public byte[] generate(String templateName, Map<String, Object> placeholders) {
checkArgument(!isNullOrEmpty(templateName), "document generation template cannot be empty");
Expand Down Expand Up @@ -76,4 +87,44 @@ private PdfDocumentRequest request(String templateName, Map<String, Object> plac
.build();
}

@Override
public byte[] converToPdf(Map<String, Object> placeholders, String fileName) {

try {
String filename = FilenameUtils.getBaseName(fileName) + ".pdf";
ObjectMapper objectMapper = new ObjectMapper();
byte[] docInBytes = objectMapper.convertValue(placeholders.get("fileName"), byte[].class);
File file = new File(fileName);
Files.write(docInBytes, file);

return restTemplate
.postForObject(
docmosisPdfConvertEndpoint,
createRequest(file, filename),
byte[].class
);

} catch (IOException e) {
throw new RuntimeException(e);
}

}


private HttpEntity<MultiValueMap<String, Object>> createRequest(
File file,
String outputFilename
) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("accessKey", docmosisPdfServiceAccessKey);
body.add("outputName", outputFilename);
body.add("outputFormat", "pdf");
body.add("file", new FileSystemResource(file));

return new HttpEntity<>(body, headers);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator;
Expand Down Expand Up @@ -127,7 +128,8 @@ public GeneratedDocumentInfo storeDocument(byte[] document, String authorization
@Override
public byte[] generateDocument(String templateName, Map<String, Object> placeholders) {
log.debug("Generate document requested with templateName [{}], placeholders of size[{}]",
templateName, placeholders.size());
templateName, placeholders.size()
);

return generatorService.generate(templateName, placeholders);
}
Expand All @@ -136,4 +138,15 @@ private String getCaseId(Map<String, Object> placeholders) {
Map<String, Object> caseDetails = (Map<String, Object>) placeholders.getOrDefault("caseDetails", emptyMap());
return (String) caseDetails.get("id");
}

@Override
public GeneratedDocumentInfo converToPdf(Map<String, Object> placeholders, String authorizationToken, String fileName) {
log.debug(
"Generate document requested with templateName [{}], placeholders of size[{}]",
placeholders.size()
);

byte[] generatedDocument = generatorService.converToPdf(placeholders, fileName);
return storeDocument(generatedDocument, authorizationToken, FilenameUtils.getBaseName(fileName) + ".pdf");
}
}
2 changes: 2 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ docmosis:
pdf-service:
accessKey: ${DOCMOSIS_SERVICE_ACCESS_KEY:replace_me}
renderEndpoint: "/rs/render"
convertEndpoint: "/rs/convert"
uri: ${DOCMOSIS_SERVICE_BASE_URL:http://localhost:5501}${docmosis.service.pdf-service.renderEndpoint}
health: ${DOCMOSIS_SERVICE_BASE_URL:http://localhost:5501}/health
convert: ${DOCMOSIS_SERVICE_BASE_URL:http://localhost:5501}${docmosis.service.pdf-service.convertEndpoint}
devMode: ${DOCMOSIS_SERVICE_DEV_MODE_FLAG:false}

case_document_am:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import uk.gov.hmcts.reform.prl.documentgenerator.service.DocumentManagementService;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;
Expand Down Expand Up @@ -64,4 +65,23 @@ public void whenGeneratePDF_thenReturnGeneratedDraftPDFDocumentInfo() {
.generateAndStoreDraftDocument(templateName, placeholder, "testToken");
}

@Test
public void whenConvertPDF_thenReturnConvertedPDFDocumentInfo() {
final String templateName = "templateName";
Map<String, Object> placeholder = new HashMap<>();

final GeneratedDocumentInfo expected = GeneratedDocumentInfo.builder().build();

when(documentManagementService.converToPdf(placeholder, "authToken","fileName"))
.thenReturn(expected);

GeneratedDocumentInfo actual = classUnderTest
.convertDocumentToPdf("fileName","authToken", new GenerateDocumentRequest(templateName, placeholder));

assertEquals(expected, actual);

verify(documentManagementService, times(1))
.converToPdf(placeholder, "authToken","fileName");
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package uk.gov.hmcts.reform.prl.documentgenerator.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.Assert;
import org.junit.Before;
Expand All @@ -24,10 +25,12 @@
import uk.gov.hmcts.reform.prl.documentgenerator.util.NullOrEmptyValidator;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class DocmosisPdfGenerationServiceImplUTest {
Expand All @@ -41,6 +44,9 @@ public class DocmosisPdfGenerationServiceImplUTest {
@Mock
private TemplateDataMapper templateDataMapper;

@Mock
ObjectMapper objectMapper;


@InjectMocks
@Spy
Expand All @@ -49,6 +55,9 @@ public class DocmosisPdfGenerationServiceImplUTest {
@Before
public void before() throws IllegalAccessException {
FieldUtils.writeField(classUnderTest, "docmosisPdfServiceEndpoint", "test", true);
FieldUtils.writeField(classUnderTest, "docmosisPdfConvertEndpoint", "test", true);
FieldUtils.writeField(classUnderTest, "docmosisPdfServiceAccessKey", "test", true);

}

@Test
Expand Down Expand Up @@ -99,4 +108,23 @@ public void givenHttpRequestGoesThrough_whenGenerateFromHtml_thenReturnProperRes
Assert.assertNotNull(expected);
}

@Test
public void givenFileNAme_whenConvertPDf_thenReturnProperResponse() throws Exception {
final Map<String, Object> placeholders = new HashMap<>();

byte[] test = "Any String you want".getBytes();
placeholders.put("fileName",test);

HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
Mockito.when(restTemplate.postForObject(ArgumentMatchers.any(String.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<byte[]>>any())).thenReturn(test);


byte[] expected = classUnderTest.converToPdf(placeholders,"testFile");

Assert.assertNotNull(expected);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,25 @@ public void testGenerateAndStoreDraftDocument_WithDraftPrefixMock() {
assertThat("Draft value set ", value.get(IS_DRAFT), is(true));
}

@Test
public void testConvertToPdf() {
final Map<String, Object> placeholders = new HashMap<>();

byte[] test = "Any String you want".getBytes();
placeholders.put("fileName",test);
Mockito.when(authTokenGenerator.generate()).thenReturn(s2sToken);
Mockito.when(pdfGenerationService.converToPdf(placeholders,"fileName")).thenReturn(test);

Mockito.when(caseDocumentClient.uploadDocuments(eq(authToken),
eq(s2sToken), eq("PRLAPPS"), eq("PRIVATELAW"), any()))
.thenReturn(uploadResponse);

classUnderTest.converToPdf(placeholders, authToken,"fileName");

verify(pdfGenerationService).converToPdf(placeholders,"fileName");
}


@Test
public void testGenerateAndStoreFinalDocument_WithDynamicFileName() {
placeholderMap.put("dynamic_fileName","test-file.pdf");
Expand Down

0 comments on commit c603fc5

Please sign in to comment.