com.adobe.platform.operation.pdfops.DeletePagesOperation 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 java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.platform.CPFContentAnalyzerResponse;
import com.adobe.platform.operation.internal.exception.OperationException;
import com.adobe.platform.operation.internal.service.DeletePagesService;
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;
/**
* An operation to delete pages in a PDF file.
*
*
* Sample Usage:
*
{@code DeletePagesOperation deletePagesOperation = DeletePagesOperation.createNew();
* deletePagesOperation.setInput(FileRef.createFromLocalFile("~/Documents/deletePagesOperationInput.pdf",
* DeletePagesOperation.SupportedSourceFormat.PDF.getMediaType()));
* PageRanges pageRanges = new PageRanges();
* pageRanges.addSinglePage(1);
* deletePagesOperation.setPageRanges(pageRanges);
* Credentials credentials = Credentials.serviceAccountCredentialsBuilder().fromFile("pdftools-api-credentials.json").build();
* FileRef result = deletePagesOperation.execute(ExecutionContext.create(credentials));
* result.saveAs("output/deletePagesOperationOutput.pdf");
* }
*/
public class DeletePagesOperation implements Operation {
private static final Logger LOGGER = LoggerFactory.getLogger(DeletePagesOperation.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 sourceFileRef;
private PageRanges pageRanges;
private DeletePagesOperation() {
}
/**
* Constructs a {@code DeletePagesOperation} instance.
*
* @return a new {@code DeletePagesOperation} instance
*/
public static DeletePagesOperation createNew() {
return new DeletePagesOperation();
}
/**
* Sets an input file.
*
* @param sourceFileRef an input file; can not be null
*/
public void setInput(FileRef sourceFileRef) {
Objects.requireNonNull(sourceFileRef, "No input was set for operation");
this.sourceFileRef = (FileRefImpl) sourceFileRef;
}
/**
* Specifies the pages to delete from the input PDF file
*
* @param pageRanges page ranges for deletion; can not be null or empty
*/
public void setPageRanges(PageRanges pageRanges) {
Objects.requireNonNull(pageRanges, "Page ranges can not be null");
this.pageRanges = pageRanges;
}
/**
* 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 Delete Pages operation execution");
long startTimeMs = System.currentTimeMillis();
String location = DeletePagesService.deletePages(internalExecutionContext,
sourceFileRef, pageRanges, this.getClass().getSimpleName());
String targetFileName = FileUtil.getRandomFileName(TARGET_FILE_EXTENSION);
String temporaryDestinationPath = PathUtil.getTemporaryDestinationPath(targetFileName, TARGET_FILE_EXTENSION);
FileDownloadApi.downloadAndSave(internalExecutionContext, location, temporaryDestinationPath, CPFContentAnalyzerResponse.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 (sourceFileRef == null) {
throw new IllegalArgumentException("No input was set for operation");
}
ValidationUtil.validatePageRanges(pageRanges);
ValidationUtil.validateExecutionContext(context);
ValidationUtil.validateMediaType(SUPPORTED_SOURCE_MEDIA_TYPES, this.sourceFileRef.getMediaType());
}
/**
* Supported source file formats for {@link DeletePagesOperation}.
*/
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();
}
}
}