com.adobe.pdfservices.operation.pdfops.ReorderPagesOperation Maven / Gradle / Ivy
Show all versions of pdfservices-sdk Show documentation
/*
* 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.pdfservices.operation.pdfops;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import com.adobe.pdfservices.operation.exception.ServiceApiException;
import com.adobe.pdfservices.operation.exception.ServiceUsageException;
import com.adobe.pdfservices.operation.internal.ExtensionMediaTypeMapping;
import com.adobe.pdfservices.operation.internal.FileRefImpl;
import com.adobe.pdfservices.operation.internal.InternalExecutionContext;
import com.adobe.pdfservices.operation.internal.MediaType;
import com.adobe.pdfservices.operation.internal.api.FileDownloadApi;
import com.adobe.pdfservices.operation.internal.cpf.dto.response.platform.CPFContentAnalyzerResponse;
import com.adobe.pdfservices.operation.internal.exception.OperationException;
import com.adobe.pdfservices.operation.internal.options.CombineOperationInput;
import com.adobe.pdfservices.operation.internal.service.CombinePDFService;
import com.adobe.pdfservices.operation.internal.util.FileUtil;
import com.adobe.pdfservices.operation.internal.util.PathUtil;
import com.adobe.pdfservices.operation.internal.util.StringUtil;
import com.adobe.pdfservices.operation.internal.util.ValidationUtil;
import com.adobe.pdfservices.operation.ExecutionContext;
import com.adobe.pdfservices.operation.Operation;
import com.adobe.pdfservices.operation.io.FileRef;
import com.adobe.pdfservices.operation.pdfops.options.PageRanges;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An operation that allows to rearrange pages in a PDF file according to the specified order.
*
*
* Sample Usage:
*
{@code ReorderPagesOperation reorderPagesOperation = ReorderPagesOperation.createNew();
* reorderPagesOperation.setInput(FileRef.createFromLocalFile("~/Documents/reorderPagesOperationInput.pdf",
* ReorderPagesOperation.SupportedSourceFormat.PDF.getMediaType()));
* PageRanges pageRanges = new PageRanges();
* pageRanges.addSinglePage(3);
* pageRanges.addRange(1,2);
* reorderPagesOperation.setPagesOrder(pageRanges);
* Credentials credentials = Credentials.serviceAccountCredentialsBuilder().fromFile("pdfservices-api-credentials.json").build();
* FileRef result = reorderPagesOperation.execute(ExecutionContext.create(credentials));
* result.saveAs("output/reorderPagesOperationOutput.pdf");
* }
*/
public class ReorderPagesOperation implements Operation {
private static final Logger LOGGER = LoggerFactory.getLogger(ReorderPagesOperation.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 ReorderPagesOperation() {}
/**
* Constructs a {@code ReorderPagesOperation} instance.
*
* @return a new {@code ReorderPagesOperation} instance
*/
public static ReorderPagesOperation createNew() {
return new ReorderPagesOperation();
}
/**
* 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;
}
/**
* Sets the order of the pages.
*
* @param pageRanges page ranges for reordering; can not be null or empty
*/
public void setPagesOrder(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 Reorder Pages operation execution");
long startTimeMs = System.currentTimeMillis();
List sourcefileRefs = new ArrayList<>();
sourcefileRefs.add(CombineOperationInput.createNew(sourceFileRef, pageRanges));
String location = CombinePDFService.combinePdf(internalExecutionContext, sourcefileRefs, 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(), oe.getReportErrorCode());
}
}
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 ReorderPagesOperation}.
*/
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();
}
}
}