com.adobe.platform.operation.pdfops.InsertPagesOperation Maven / Gradle / Ivy
/*
* Copyright 2019 Adobe
* All Rights Reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute this file in
* accordance with the terms of the Adobe license agreement accompanying
* it. If you have received this file from a source other than Adobe,
* then your use, modification, or distribution of it requires the prior
* written permission of Adobe.
*/
package com.adobe.platform.operation.pdfops;
import com.adobe.platform.operation.ExecutionContext;
import com.adobe.platform.operation.Operation;
import com.adobe.platform.operation.exception.ServiceApiException;
import com.adobe.platform.operation.exception.ServiceUsageException;
import com.adobe.platform.operation.internal.ExtensionMediaTypeMapping;
import com.adobe.platform.operation.internal.FileRefImpl;
import com.adobe.platform.operation.internal.InternalExecutionContext;
import com.adobe.platform.operation.internal.MediaType;
import com.adobe.platform.operation.internal.api.FileDownloadApi;
import com.adobe.platform.operation.internal.cpf.dto.response.ContentAnalyzerResponse;
import com.adobe.platform.operation.internal.exception.OperationException;
import com.adobe.platform.operation.internal.options.CombineOperationInput;
import com.adobe.platform.operation.internal.service.InsertPagesService;
import com.adobe.platform.operation.internal.util.FileUtil;
import com.adobe.platform.operation.internal.util.PathUtil;
import com.adobe.platform.operation.internal.util.StringUtil;
import com.adobe.platform.operation.internal.util.ValidationUtil;
import com.adobe.platform.operation.io.FileRef;
import com.adobe.platform.operation.pdfops.options.PageRanges;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
/**
* An operation that can be used to insert pages of multiple PDF files into a base PDF file.
*
* For more complex use cases, refer the {@link CombineFilesOperation}.
*
* Sample Usage:
*
{@code InsertPagesOperation insertPagesOperation = InsertPagesOperation.createNew();
* insertPagesOperation.setBaseInput(FileRef.createFromLocalFile("~/Documents/insertPagesOperationBaseInput.pdf",
* InsertPagesOperation.SupportedSourceFormat.PDF.getMediaType()));
* insertPagesOperation.addPagesToInsertAt(FileRef.createFromLocalFile("~/Documents/insertPagesOperationFileToInsertInput.pdf",
* InsertPagesOperation.SupportedSourceFormat.PDF.getMediaType()), 1);
* Credentials credentials = Credentials.serviceAccountCredentialsBuilder().fromFile("pdftools-api-credentials.json").build();
* FileRef result = insertPagesOperation.execute(ExecutionContext.create(credentials));
* result.saveAs("output/insertPagesOperationOutput.pdf");
* }
*/
public class InsertPagesOperation implements Operation {
private static final Logger LOGGER = LoggerFactory.getLogger(InsertPagesOperation.class);
/**
* Supported media types for this operation
*/
private static final Set SUPPORTED_SOURCE_MEDIA_TYPES =
new HashSet<>(Collections.singletonList(ExtensionMediaTypeMapping.PDF.getMediaType()));
/**
* Field representing the extension of the operation result
*/
private static final String TARGET_FILE_EXTENSION = ExtensionMediaTypeMapping.PDF.getExtension();
/**
* Variable to check if the operation instance was invoked more than once
*/
private boolean isInvoked = false;
private FileRefImpl baseSourceFileRef;
private Map> filesToInsert;
private InsertPagesOperation() {
this.filesToInsert = new TreeMap<>();
}
/**
* Constructs a {@code InsertPagesOperation} instance.
*
* @return a new {@code InsertPagesOperation} instance
*/
public static InsertPagesOperation createNew() {
return new InsertPagesOperation();
}
/**
* Sets the base input file.
*
* @param sourceFileRef the base input file; can not be null
*/
public void setBaseInput(FileRef sourceFileRef) {
Objects.requireNonNull(sourceFileRef, "No base input was set for operation");
this.baseSourceFileRef = (FileRefImpl) sourceFileRef;
}
/**
* Adds all the pages of the input PDF file to be inserted at the specified page of the base PDF file.
*
* This method can be invoked multiple times with the same or different input PDF files.
*
* @param inputFile a PDF file for insertion; can not be null
* @param basePage page of the base PDF file
*/
public void addPagesToInsertAt(FileRef inputFile, int basePage) {
PageRanges pageRanges = new PageRanges();
pageRanges.addAll();
addPagesToInsertAt(inputFile, pageRanges, basePage);
}
/**
* Adds the specified pages of the input PDF file to be inserted at the specified page of the base PDF file
*
* This method can be invoked multiple times with the same or different input PDF files.
*
* @param inputFile a PDF file for insertion; can not be null
* @param pageRanges page ranges of the input PDF file; can not be null or empty
* @param basePage page of the base PDF file
*/
public void addPagesToInsertAt(FileRef inputFile, PageRanges pageRanges, int basePage) {
Objects.requireNonNull(inputFile, "File to be inserted can not be null");
Objects.requireNonNull(pageRanges, "Page ranges can not be null");
CombineOperationInput combineOperationInput = CombineOperationInput.createNew((FileRefImpl)inputFile, pageRanges);
updateFilesToInsert(basePage, combineOperationInput);
}
/**
* Executes this operation synchronously using the supplied context and returns a new FileRef instance for the resulting PDF file.
*
* The resulting file may be stored in the system temporary directory (per java.io.tmpdir System property).
* See {@link FileRef} for how temporary resources are cleaned up.
*
* @param context the context in which to execute the operation
* @return the resulting PDF file
* @throws ServiceApiException if an API call results in an error response
* @throws IOException if there is an error in reading either the input source or the resulting PDF file
* @throws ServiceUsageException if service usage limits have been reached or credentials quota has been exhausted
*/
public FileRef execute(ExecutionContext context) throws ServiceApiException, IOException, ServiceUsageException {
validateInvocationCount();
InternalExecutionContext internalExecutionContext = (InternalExecutionContext) context;
this.validate(internalExecutionContext);
try {
LOGGER.info("All validations successfully done. Beginning Insert Pages operation execution");
long startTimeMs = System.currentTimeMillis();
String location = InsertPagesService.insertPages(internalExecutionContext,
baseSourceFileRef, filesToInsert, this.getClass().getSimpleName());
String targetFileName = FileUtil.getRandomFileName(TARGET_FILE_EXTENSION);
String temporaryDestinationPath = PathUtil.getTemporaryDestinationPath(targetFileName, TARGET_FILE_EXTENSION);
FileDownloadApi.downloadAndSave(internalExecutionContext, location, temporaryDestinationPath, ContentAnalyzerResponse.class);
LOGGER.info("Operation successfully completed. Stored requisite PDF at {}", temporaryDestinationPath);
LOGGER.debug("Operation Success Info - Request ID: {}, Latency(ms): {}",
StringUtil.getRequestIdFromLocation(location), System.currentTimeMillis() - startTimeMs);
isInvoked = true;
return FileRef.createFromLocalFile(temporaryDestinationPath);
} catch (OperationException oe) {
throw new ServiceApiException(oe.getErrorMessage(), oe.getRequestTrackingId(), oe.getStatusCode());
}
}
private void validateInvocationCount() {
if (isInvoked) {
LOGGER.error("Operation instance must only be invoked once");
throw new IllegalStateException("Operation instance must not be reused, can only be invoked once");
}
}
private void validate(InternalExecutionContext context) {
if (baseSourceFileRef == null) {
throw new IllegalArgumentException("No input was set for operation");
}
ValidationUtil.validateExecutionContext(context);
ValidationUtil.validateMediaType(SUPPORTED_SOURCE_MEDIA_TYPES, this.baseSourceFileRef.getMediaType());
ValidationUtil.validateInsertFilesInputs(SUPPORTED_SOURCE_MEDIA_TYPES, filesToInsert);
}
private void updateFilesToInsert(int index, CombineOperationInput combineOperationInput) {
if (filesToInsert.containsKey(index)) {
List inputList = filesToInsert.get(index);
inputList.add(combineOperationInput);
}
else {
List inputList = new ArrayList<>();
inputList.add(combineOperationInput);
filesToInsert.put(index, inputList);
}
}
/**
* Supported source file formats for {@link InsertPagesOperation}.
*/
public enum SupportedSourceFormat implements MediaType {
/**
* Represents "application/pdf" media type
*/
PDF;
/**
* Returns the corresponding media type for this format, intended to be used for {@code mediaType} parameter in
* {@link FileRef} methods.
*
* @return the corresponding media type
*/
public String getMediaType() {
return ExtensionMediaTypeMapping.valueOf(name()).getMediaType().toLowerCase();
}
}
}