Skip to content

Commit 937eb4c

Browse files
committed
✨ Updated GeneratePdf Rest Service Adapter to use RestClient interface
1 parent 9d2c33e commit 937eb4c

File tree

3 files changed

+414
-453
lines changed

3 files changed

+414
-453
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
1-
package com._4point.aem.docservices.rest_services.client.generatePDF;
1+
package com._4point.aem.docservices.rest_services.client.generatePDF;
22

33
import java.io.IOException;
44
import java.io.InputStream;
55
import java.util.Base64;
66
import java.util.Objects;
7+
import java.util.Optional;
78
import java.util.function.Supplier;
89

9-
import jakarta.ws.rs.client.Client;
10-
import jakarta.ws.rs.client.WebTarget;
11-
import jakarta.ws.rs.core.MediaType;
12-
import jakarta.ws.rs.core.Response;
13-
import jakarta.ws.rs.core.Response.Status.Family;
14-
import jakarta.ws.rs.core.Response.StatusType;
1510
import javax.xml.parsers.DocumentBuilder;
1611
import javax.xml.parsers.DocumentBuilderFactory;
1712
import javax.xml.parsers.ParserConfigurationException;
1813

19-
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
2014
import org.w3c.dom.Element;
2115
import org.xml.sax.SAXException;
2216

17+
import com._4point.aem.docservices.rest_services.client.RestClient;
18+
import com._4point.aem.docservices.rest_services.client.RestClient.ContentType;
19+
import com._4point.aem.docservices.rest_services.client.RestClient.MultipartPayload;
20+
import com._4point.aem.docservices.rest_services.client.RestClient.Response;
21+
import com._4point.aem.docservices.rest_services.client.RestClient.RestClientException;
22+
import com._4point.aem.docservices.rest_services.client.helpers.AemConfig;
2323
import com._4point.aem.docservices.rest_services.client.helpers.AemServerType;
2424
import com._4point.aem.docservices.rest_services.client.helpers.Builder;
2525
import com._4point.aem.docservices.rest_services.client.helpers.BuilderImpl;
26-
import com._4point.aem.docservices.rest_services.client.helpers.MultipartTransformer;
26+
import com._4point.aem.docservices.rest_services.client.helpers.BuilderImpl.TriFunction;
2727
import com._4point.aem.docservices.rest_services.client.helpers.RestServicesServiceAdapter;
2828
import com._4point.aem.fluentforms.api.Document;
2929
import com._4point.aem.fluentforms.api.generatePDF.CreatePDFResult;
@@ -46,81 +46,47 @@ public class RestServicesGeneratePDFServiceAdapter extends RestServicesServiceAd
4646
private static final String SETTING_DOC = "settingDoc";
4747
private static final String XMP_DOC = "xmpDoc";
4848

49-
// protected RestServicesGeneratePDFServiceAdapter(WebTarget baseTarget) {
50-
// super(baseTarget);
51-
// }
52-
//
49+
50+
private final RestClient createPdf2RestClient;
51+
5352
// Only callable from Builder
54-
private RestServicesGeneratePDFServiceAdapter(WebTarget target, Supplier<String> correlationId, AemServerType aemServerType) {
55-
super(target, correlationId, aemServerType);
53+
private RestServicesGeneratePDFServiceAdapter(BuilderImpl builder, Supplier<String> correlationId) {
54+
super(correlationId);
55+
this.createPdf2RestClient = builder.createClient(GENERATE_PDF_SERVICE_NAME, CREATE_PDF_METHOD_NAME);
5656
}
5757

58-
@Override
59-
public CreatePDFResult createPDF2(Document inputDoc, String inputFileExtension, String fileTypeSettings,
60-
PDFSettings pdfSettings, SecuritySettings securitySettings, Document settingsDoc, Document xmpDoc)
61-
throws GeneratePDFServiceException {
62-
WebTarget geneWebTarget = baseTarget.path(constructStandardPath(GENERATE_PDF_SERVICE_NAME, CREATE_PDF_METHOD_NAME));
63-
64-
try (final FormDataMultiPart multipart = new FormDataMultiPart()) {
65-
multipart.field(DATA_PARAM_NAME,
66-
Objects.requireNonNull(inputDoc, "inputDoc can not be null").getInputStream(),
67-
MediaType.MULTIPART_FORM_DATA_TYPE);
68-
multipart.field(FILE_EXTENSION,
69-
Objects.requireNonNull(inputFileExtension, "file extension can not be null"));
70-
71-
byte[] settingsData = settingsDoc != null ? settingsDoc.getInlineData() : null;
72-
byte[] xmpDocData = xmpDoc != null ? xmpDoc.getInlineData() : null;
73-
MultipartTransformer.create(multipart)
74-
.transform((t) -> fileTypeSettings == null ? t : t.field(FILE_TYPE_SETTINGS, fileTypeSettings))
75-
.transform((t) -> pdfSettings == null ? t : t.field(PDF_SETTINGS, pdfSettings.toString()))
76-
.transform((t) -> securitySettings == null ? t
77-
: t.field(SECURITY_SETTINGS, securitySettings.toString()))
78-
.transform((t) -> settingsData == null ? t
79-
: t.field(SETTING_DOC, settingsData, MediaType.MULTIPART_FORM_DATA_TYPE))
80-
.transform((t) -> xmpDocData == null ? t
81-
: t.field(XMP_DOC, xmpDocData, MediaType.MULTIPART_FORM_DATA_TYPE));
82-
83-
Response result = postToServer(geneWebTarget, multipart, MediaType.APPLICATION_XML_TYPE);
84-
StatusType resultStatus = result.getStatusInfo();
85-
if (!Family.SUCCESSFUL.equals(resultStatus.getFamily())) {
86-
String msg = "Call to server failed, statusCode='" + resultStatus.getStatusCode() + "', reason='"
87-
+ resultStatus.getReasonPhrase() + "'.";
88-
if (result.hasEntity()) {
89-
InputStream entityStream = (InputStream) result.getEntity();
90-
msg += "\n" + inputStreamtoString(entityStream);
91-
}
92-
throw new GeneratePDFServiceException(msg);
93-
}
94-
95-
if (!result.hasEntity()) {
96-
throw new GeneratePDFServiceException(
97-
"Call to server succeeded but server failed to return createPDFResult xml. This should never happen.");
98-
}
99-
100-
MediaType responseContentType = result.getMediaType();
101-
102-
if (responseContentType == null || !responseContentType.isCompatible(MediaType.APPLICATION_XML_TYPE)) {
103-
String msg = "Response from AEM server was "
104-
+ (responseContentType != null ? "content-type='" + responseContentType.toString() + "'"
105-
: "content-type was null")
106-
+ ".";
107-
InputStream entityStream = (InputStream) result.getEntity();
108-
msg += "\n" + inputStreamtoString(entityStream);
109-
throw new GeneratePDFServiceException(msg);
110-
}
111-
CreatePDFResult createPDFResult = convertXmlToCreatePDFResult((InputStream) result.getEntity());
112-
return createPDFResult;
113-
} catch (IOException e) {
114-
throw new GeneratePDFServiceException(
115-
"I/O Error while converting document to pdf. (" + baseTarget.getUri().toString() + ").", e);
116-
} catch (RestServicesServiceException e) {
117-
throw new GeneratePDFServiceException("Error while posting to server", e);
118-
}
119-
}
58+
@Override
59+
public CreatePDFResult createPDF2(Document inputDoc, String inputFileExtension, String fileTypeSettings,
60+
PDFSettings pdfSettings, SecuritySettings securitySettings, Document settingsDoc, Document xmpDoc)
61+
throws GeneratePDFServiceException {
62+
try (MultipartPayload payload = createPdf2RestClient.multipartPayloadBuilder()
63+
.add(DATA_PARAM_NAME, Objects.requireNonNull(inputDoc, "inputDoc can not be null"), ContentType.APPLICATION_OCTET_STREAM)
64+
.add(FILE_EXTENSION, Objects.requireNonNull(inputFileExtension, "file extension can not be null"))
65+
.addIfNotNull(FILE_TYPE_SETTINGS, fileTypeSettings)
66+
.addStringVersion(PDF_SETTINGS, pdfSettings)
67+
.addStringVersion(SECURITY_SETTINGS, securitySettings)
68+
.addIfNotNull(SETTING_DOC, settingsDoc, ContentType.APPLICATION_XML)
69+
.addIfNotNull(XMP_DOC, xmpDoc, ContentType.APPLICATION_XML)
70+
.build()) {
71+
72+
Optional<Response> postToServerResult = payload.postToServer(ContentType.APPLICATION_XML);
73+
74+
return postToServerResult
75+
.map(RestServicesServiceAdapter::responseToDoc)
76+
.map(uncheck(Document::getInputStream))
77+
.map(RestServicesGeneratePDFServiceAdapter::convertXmlToCreatePDFResult)
78+
.orElseThrow(() -> new GeneratePDFServiceException("Error - empty response from AEM server."));
79+
} catch (IOException e) {
80+
throw new GeneratePDFServiceException("I/O Error while generating PDF. (" + createPdf2RestClient.target() + ").", e);
81+
} catch (RestClientException e) {
82+
throw new GeneratePDFServiceException("Error while POSTing to server (" + createPdf2RestClient.target() + ").", e);
83+
} catch (GeneratePDFServiceResponseParsingException e) {
84+
throw new GeneratePDFServiceException("Error while converting server response to PdfResult.", e);
85+
}
86+
}
12087

12188
// Package visibility so that it can be unit tested.
122-
/* package */public static CreatePDFResult convertXmlToCreatePDFResult(InputStream createPDFResultXml)
123-
throws GeneratePDFServiceException {
89+
/* package */ static CreatePDFResult convertXmlToCreatePDFResult(InputStream createPDFResultXml) throws GeneratePDFServiceResponseParsingException {
12490
CreatePDFResultImpl createPDFResult = new CreatePDFResultImpl();
12591
try {
12692
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
@@ -130,7 +96,7 @@ public CreatePDFResult createPDF2(Document inputDoc, String inputFileExtension,
13096
getNodeValueForAttribute(doc, "logDoc", "logDocValue", createPDFResult);
13197

13298
} catch (ParserConfigurationException | SAXException | IOException e) {
133-
throw new GeneratePDFServiceException("Error while parsing xml", e);
99+
throw new GeneratePDFServiceResponseParsingException("Error while parsing xml", e);
134100
}
135101
return createPDFResult;
136102
}
@@ -141,19 +107,23 @@ private static void getNodeValueForAttribute(org.w3c.dom.Document doc, String pa
141107
byte[] bytesJobLog = Base64.getDecoder().decode(eElement.getAttribute(attributeName));
142108
if (parentNodeName.equals("createdDoc")) {
143109
createPDFResult.setCreatedDocument(SimpleDocumentFactoryImpl.getFactory().create(bytesJobLog));
144-
createPDFResult.getCreatedDocument().setContentType(APPLICATION_PDF.toString());
110+
createPDFResult.getCreatedDocument().setContentType(ContentType.APPLICATION_PDF.contentType());
145111
} else {
146112
createPDFResult.setLogDocument(SimpleDocumentFactoryImpl.getFactory().create(bytesJobLog));
147-
createPDFResult.getLogDocument().setContentType(MediaType.TEXT_PLAIN_TYPE.toString());
113+
createPDFResult.getLogDocument().setContentType(ContentType.TEXT_PLAIN.contentType());
148114
}
149115
}
150116

151-
public static GeneratePDFServiceBuilder builder() {
152-
return new GeneratePDFServiceBuilder();
117+
public static GeneratePDFServiceBuilder builder(TriFunction<AemConfig, String, Supplier<String>, RestClient> clientFactory) {
118+
return new GeneratePDFServiceBuilder(clientFactory);
153119
}
154120

155121
public static class GeneratePDFServiceBuilder implements Builder {
156-
private BuilderImpl builder = new BuilderImpl();
122+
private BuilderImpl builder;
123+
124+
public GeneratePDFServiceBuilder(TriFunction<AemConfig, String, Supplier<String>, RestClient> clientFactory) {
125+
this.builder = new BuilderImpl(clientFactory);
126+
}
157127

158128
@Override
159129
public GeneratePDFServiceBuilder machineName(String machineName) {
@@ -173,12 +143,6 @@ public GeneratePDFServiceBuilder useSsl(boolean useSsl) {
173143
return this;
174144
}
175145

176-
@Override
177-
public GeneratePDFServiceBuilder clientFactory(Supplier<Client> clientFactory) {
178-
builder.clientFactory(clientFactory);
179-
return this;
180-
}
181-
182146
@Override
183147
public GeneratePDFServiceBuilder basicAuthentication(String username, String password) {
184148
builder.basicAuthentication(username, password);
@@ -196,11 +160,6 @@ public Supplier<String> getCorrelationIdFn() {
196160
return builder.getCorrelationIdFn();
197161
}
198162

199-
@Override
200-
public WebTarget createLocalTarget() {
201-
return builder.createLocalTarget();
202-
}
203-
204163
@Override
205164
public GeneratePDFServiceBuilder aemServerType(AemServerType serverType) {
206165
builder.aemServerType(serverType);
@@ -213,9 +172,15 @@ public AemServerType getAemServerType() {
213172
}
214173

215174
public RestServicesGeneratePDFServiceAdapter build() {
216-
return new RestServicesGeneratePDFServiceAdapter(this.createLocalTarget(), this.getCorrelationIdFn(), this.getAemServerType());
175+
return new RestServicesGeneratePDFServiceAdapter(builder, this.getCorrelationIdFn());
217176
}
218-
219177
}
220178

179+
@SuppressWarnings("serial")
180+
private static class GeneratePDFServiceResponseParsingException extends RuntimeException {
181+
182+
public GeneratePDFServiceResponseParsingException(String message, Throwable cause) {
183+
super(message, cause);
184+
}
185+
}
221186
}

0 commit comments

Comments
 (0)