Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Validate tool input, apply documented defaults and fix tool crashes (#8464)

Anthony Stirlingc687f2f5eb91
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 599e74fea3..7b5dc21eb2 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -1,6 +1,7 @@
name: Build and Test Workflow
-# Top-level PR / merge-queue gate. Detects which paths changed and dispatches
+# PR / merge-queue gate, including stacked PRs targeting feature branches.
+# Detects which paths changed and dispatches
# to the dedicated reusable workflows under .github/workflows/. Each child
# workflow keeps its own setup/teardown so this file stays a routing layer.
#
@@ -10,7 +11,6 @@ name: Build and Test Workflow
on:
pull_request:
- branches: ["main"]
merge_group:
branches: ["main"]
workflow_dispatch:
diff --git a/.github/workflows/gradle-cache-prime.yml b/.github/workflows/gradle-cache-prime.yml
index f3b127314a..ae987a0d52 100644
--- a/.github/workflows/gradle-cache-prime.yml
+++ b/.github/workflows/gradle-cache-prime.yml
@@ -48,7 +48,7 @@ jobs:
- name: Resolve backend dependencies
if: steps.cache-gradle-restore.outputs.cache-hit != 'true'
- run: ./gradlew :stirling-pdf:classes --no-daemon
+ run: ./gradlew :stirling-pdf:classes copyJacocoAgent --no-daemon
env:
STIRLING_FLAVOR: saas
MAVEN_USER: ${{ secrets.MAVEN_USER }}
diff --git a/app/common/src/main/java/stirling/software/common/model/api/converters/HTMLToPdfRequest.java b/app/common/src/main/java/stirling/software/common/model/api/converters/HTMLToPdfRequest.java
index 106d36f171..cedf892747 100644
--- a/app/common/src/main/java/stirling/software/common/model/api/converters/HTMLToPdfRequest.java
+++ b/app/common/src/main/java/stirling/software/common/model/api/converters/HTMLToPdfRequest.java
@@ -15,5 +15,5 @@ public class HTMLToPdfRequest extends PDFFile {
description = "Zoom level for displaying the website. Default is '1'.",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "1")
- private float zoom;
+ private float zoom = 1;
}
diff --git a/app/common/src/main/java/stirling/software/common/model/tool/ToolDiagnostic.java b/app/common/src/main/java/stirling/software/common/model/tool/ToolDiagnostic.java
index adda7579dd..fd103722d1 100644
--- a/app/common/src/main/java/stirling/software/common/model/tool/ToolDiagnostic.java
+++ b/app/common/src/main/java/stirling/software/common/model/tool/ToolDiagnostic.java
@@ -18,6 +18,9 @@ public record ToolDiagnostic(int stepIndex, Severity severity, String code, Stri
/** The step declares no {@link ToolIO}, so nothing past it can be checked. */
public static final String UNDECLARED = "undeclared-operation";
+ /** The step names no operation, or one the pipeline runner cannot dispatch to. */
+ public static final String UNKNOWN_OPERATION = "unknown-operation";
+
/** The previous step's output is not a format this step accepts. */
public static final String FORMAT_MISMATCH = "format-mismatch";
diff --git a/app/common/src/main/java/stirling/software/common/model/tool/ToolIOSource.java b/app/common/src/main/java/stirling/software/common/model/tool/ToolIOSource.java
index 1e0d896fbd..3c1882bae5 100644
--- a/app/common/src/main/java/stirling/software/common/model/tool/ToolIOSource.java
+++ b/app/common/src/main/java/stirling/software/common/model/tool/ToolIOSource.java
@@ -12,6 +12,14 @@ public interface ToolIOSource {
Optional<ToolIOSpec> find(String operationPath);
+ /**
+ * Whether a pipeline step may name this path at all. A source that cannot list every runnable
+ * endpoint answers true, leaving a missing declaration to be reported as merely undeclared.
+ */
+ default boolean isKnown(String operationPath) {
+ return true;
+ }
+
static ToolIOSource of(Map<String, ToolIOSpec> specs) {
Map<String, ToolIOSpec> copy = Map.copyOf(specs);
return path -> Optional.ofNullable(copy.get(path));
diff --git a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
index ed48ed52be..295c27d7cc 100644
--- a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
+++ b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
@@ -51,10 +51,14 @@ public class InternalApiClient {
// ConsignO). They reach outside the JVM, so the namespace is deliberately kept to tools that
// dereference an admin-owned connection rather than a caller-supplied host — see
// ApiConnectionResolver.
+ //
+ // Of `/api/v1/form/*` only filling and listing fields are dispatchable; the editor's own
+ // field editing endpoints stay out.
private static final Pattern ALLOWED_ENDPOINT_PATH =
Pattern.compile(
"^/api/v1/(general|misc|security|convert|filter|integration|docparse)(/[A-Za-z0-9_-]+)+$"
- + "|^/api/v1/ai/tools(/[A-Za-z0-9_-]+)+$");
+ + "|^/api/v1/ai/tools(/[A-Za-z0-9_-]+)+$"
+ + "|^/api/v1/form/(fill|fields)$");
/**
* Marker propagated on every internal sub-step dispatch so the saas PAYG interceptor classifies
@@ -156,15 +160,13 @@ public class InternalApiClient {
}
}
- // A no-file ai/tools call (e.g. create-pdf-from-html-agent) sends only string params, so
- // without this RestTemplate would use urlencoded instead of the multipart the controller
- // expects. File-bearing calls get the right multipart content-type from RestTemplate.
- boolean isAiTool = endpointPath.startsWith("/api/v1/ai/tools/");
+ // This dispatcher sends multipart forms. Without a Resource part, RestTemplate would
+ // choose urlencoded instead, even for generators such as /api/v1/convert/url/pdf.
boolean hasFilePart =
body.values().stream()
.flatMap(java.util.List::stream)
.anyMatch(Resource.class::isInstance);
- if (isAiTool && !hasFilePart) {
+ if (!hasFilePart) {
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
}
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
@@ -254,8 +256,13 @@ public class InternalApiClient {
return userService.getApiKeyForUser(Role.INTERNAL_API_USER.getRoleId());
}
+ /** Whether {@link #post} would dispatch to this path rather than refuse it. */
+ public static boolean isDispatchable(String endpointPath) {
+ return endpointPath != null && ALLOWED_ENDPOINT_PATH.matcher(endpointPath).matches();
+ }
+
private void validateUrl(String endpointPath) {
- if (endpointPath == null || !ALLOWED_ENDPOINT_PATH.matcher(endpointPath).matches()) {
+ if (!isDispatchable(endpointPath)) {
log.warn("Blocked internal API request to disallowed path: {}", endpointPath);
throw new SecurityException(
"Internal API dispatch not permitted for endpoint: " + endpointPath);
diff --git a/app/common/src/main/java/stirling/software/common/service/ToolChainValidator.java b/app/common/src/main/java/stirling/software/common/service/ToolChainValidator.java
index 074a127925..b1ba48412d 100644
--- a/app/common/src/main/java/stirling/software/common/service/ToolChainValidator.java
+++ b/app/common/src/main/java/stirling/software/common/service/ToolChainValidator.java
@@ -19,7 +19,8 @@ import stirling.software.common.model.tool.ToolIOSpec;
*
* <p>The frontend and the AI engine implement the same rules against their generated copies, so a
* chain can be checked without a round trip. {@code testing/tool-io-cases.json} pins all three to
- * the same answers.
+ * the same answers. Only this copy can tell an unknown operation from an undeclared one, since only
+ * the server knows every endpoint the pipeline runner can dispatch to.
*/
@Service
@RequiredArgsConstructor
@@ -43,14 +44,31 @@ public class ToolChainValidator {
for (int i = 0; i < steps.size(); i++) {
Step step = steps.get(i);
- Optional<ToolIOSpec> found = toolIO.find(step.operation());
+ String operation = step.operation();
+ if (operation == null || operation.isBlank()) {
+ diagnostics.add(
+ ToolDiagnostic.error(
+ i, ToolDiagnostic.UNKNOWN_OPERATION, "The step has no operation."));
+ carried = null;
+ continue;
+ }
+ if (!toolIO.isKnown(operation)) {
+ diagnostics.add(
+ ToolDiagnostic.error(
+ i,
+ ToolDiagnostic.UNKNOWN_OPERATION,
+ "Unknown operation " + operation + ": no tool runs at that path."));
+ carried = null;
+ continue;
+ }
+ Optional<ToolIOSpec> found = toolIO.find(operation);
if (found.isEmpty()) {
diagnostics.add(
ToolDiagnostic.warn(
i,
ToolDiagnostic.UNDECLARED,
"Step "
- + step.operation()
+ + operation
+ " does not declare what it accepts or produces, so the"
+ " rest of the chain cannot be checked."));
// Nothing is known past an undeclared step.
diff --git a/app/common/src/main/java/stirling/software/common/service/ToolIORegistry.java b/app/common/src/main/java/stirling/software/common/service/ToolIORegistry.java
index c2219536d1..eb373c301b 100644
--- a/app/common/src/main/java/stirling/software/common/service/ToolIORegistry.java
+++ b/app/common/src/main/java/stirling/software/common/service/ToolIORegistry.java
@@ -1,6 +1,7 @@
package stirling.software.common.service;
import java.lang.reflect.Method;
+import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -11,10 +12,16 @@ import java.util.TreeMap;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
+import org.springframework.http.MediaType;
+import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Service;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
+import org.springframework.web.util.pattern.PathPattern;
+import org.springframework.web.util.pattern.PathPatternParser;
import lombok.extern.slf4j.Slf4j;
@@ -37,6 +44,11 @@ public class ToolIORegistry implements ToolMetadataService, ToolIOSource {
// happens-before, so no volatile (same as AiEngineEndpointResolver).
private Map<String, ToolIOSpec> specsByPath = Map.of();
+ // POST endpoints InternalApiClient may dispatch to, declared or not.
+ private Set<String> dispatchablePaths = Set.of();
+ private List<PathPattern> dispatchablePatterns = List.of();
+ private Map<PathPattern, ToolIOSpec> patternedSpecs = Map.of();
+
// Keep this the only constructor: with two, Spring falls back to a no-arg one that isn't here.
public ToolIORegistry(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
@@ -52,13 +64,59 @@ public class ToolIORegistry implements ToolMetadataService, ToolIOSource {
@EventListener(ContextRefreshedEvent.class)
public void discoverToolIO() {
Map<String, ToolIOSpec> discovered = new TreeMap<>();
+ Set<String> dispatchable = new HashSet<>();
for (RequestMappingHandlerMapping mapping :
applicationContext.getBeansOfType(RequestMappingHandlerMapping.class).values()) {
mapping.getHandlerMethods()
- .forEach((info, handler) -> register(discovered, info, handler));
+ .forEach(
+ (info, handler) -> {
+ register(discovered, info, handler);
+ registerDispatchable(dispatchable, info, handler);
+ });
}
specsByPath = Map.copyOf(discovered);
- log.debug("Discovered {} endpoints declaring @ToolIO", specsByPath.size());
+ dispatchablePaths = Set.copyOf(dispatchable);
+ dispatchablePatterns =
+ dispatchable.stream()
+ .filter(ToolIORegistry::hasPattern)
+ .map(PathPatternParser.defaultInstance::parse)
+ .toList();
+ Map<PathPattern, ToolIOSpec> patterns = new java.util.HashMap<>();
+ discovered.forEach(
+ (path, spec) -> {
+ if (hasPattern(path))
+ patterns.put(PathPatternParser.defaultInstance.parse(path), spec);
+ });
+ patternedSpecs = Map.copyOf(patterns);
+ log.debug(
+ "Discovered {} endpoints declaring @ToolIO, {} dispatchable",
+ specsByPath.size(),
+ dispatchablePaths.size());
+ }
+
+ private static void registerDispatchable(
+ Set<String> target, RequestMappingInfo info, HandlerMethod handler) {
+ Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
+ if (!methods.isEmpty() && !methods.contains(RequestMethod.POST)) {
+ return;
+ }
+ Set<MediaType> consumes = info.getConsumesCondition().getConsumableMediaTypes();
+ if ((!consumes.isEmpty()
+ && consumes.stream()
+ .noneMatch(type -> type.includes(MediaType.MULTIPART_FORM_DATA)))
+ || Arrays.stream(handler.getMethod().getParameters())
+ .anyMatch(parameter -> parameter.isAnnotationPresent(RequestBody.class))) {
+ return;
+ }
+ for (String pattern : extractPatterns(info)) {
+ String probe =
+ Arrays.stream(pattern.split("/", -1))
+ .map(segment -> hasPattern(segment) ? "path" : segment)
+ .collect(java.util.stream.Collectors.joining("/"));
+ if (InternalApiClient.isDispatchable(probe)) {
+ target.add(pattern);
+ }
+ }
}
private static void register(
@@ -78,7 +136,27 @@ public class ToolIORegistry implements ToolMetadataService, ToolIOSource {
@Override
public Optional<ToolIOSpec> find(String operationPath) {
- return Optional.ofNullable(specsByPath.get(operationPath));
+ ToolIOSpec direct = specsByPath.get(operationPath);
+ if (direct != null) return Optional.of(direct);
+ PathContainer path = PathContainer.parsePath(operationPath);
+ return patternedSpecs.entrySet().stream()
+ .filter(entry -> entry.getKey().matches(path))
+ .min(Map.Entry.comparingByKey(PathPattern.SPECIFICITY_COMPARATOR))
+ .map(Map.Entry::getValue);
+ }
+
+ @Override
+ public boolean isKnown(String operationPath) {
+ // Empty only before discovery has run (or in forSpecs); rejecting every step then would
+ // block every save.
+ return dispatchablePaths.isEmpty()
+ || (!hasPattern(operationPath) && dispatchablePaths.contains(operationPath))
+ || (InternalApiClient.isDispatchable(operationPath)
+ && dispatchablePatterns.stream()
+ .anyMatch(
+ pattern ->
+ pattern.matches(
+ PathContainer.parsePath(operationPath))));
}
@Override
@@ -109,22 +187,11 @@ public class ToolIORegistry implements ToolMetadataService, ToolIOSource {
.orElse(false);
}
+ private static boolean hasPattern(String path) {
+ return path.indexOf('{') >= 0 || path.indexOf('*') >= 0 || path.indexOf('?') >= 0;
+ }
+
private static Set<String> extractPatterns(RequestMappingInfo info) {
- try {
- Method getDirectPaths = info.getClass().getMethod("getDirectPaths");
- Object result = getDirectPaths.invoke(info);
- if (result instanceof Set<?> set) {
- Set<String> patterns = new HashSet<>();
- for (Object value : set) {
- if (value instanceof String s) {
- patterns.add(s);
- }
- }
- return patterns;
- }
- } catch (Exception e) {
- log.trace("getDirectPaths unavailable on RequestMappingInfo", e);
- }
- return Set.of();
+ return info.getPatternValues();
}
}
diff --git a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
index 1b64ea76f0..f3a451470a 100644
--- a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java
@@ -350,7 +350,7 @@ public class GeneralUtils {
* @param host the hostname to resolve
* @return {@code true} if the host should be considered unsafe
*/
- private boolean isDisallowedNetworkLocation(String host) {
+ public boolean isDisallowedNetworkLocation(String host) {
// Resolution is delegated to the JVM/OS resolver which already applies system
// configured query limits and timeouts. We only need the resolved addresses here so
// that we can enforce the MAX_DNS_ADDRESSES limit and perform the sensitive range
@@ -815,6 +815,101 @@ public class GeneralUtils {
return text;
}
+ /**
+ * Rejects malformed selections (negatives, text, backwards ranges, only commas) and ones that
+ * match no page at all; numbers outside the document are fine while something else matches, as
+ * batches mix sizes. A range may start at 0, which the parser reads as page 1.
+ */
+ public void requireValidPageSelection(String selection, int totalPages) {
+ checkPageSelection(selection, totalPages, true);
+ }
+
+ /**
+ * Rejects only malformed selections, including one made only of commas; one that matches no
+ * page is allowed, for callers such as filters where a short file simply has nothing to match.
+ */
+ public void requireWellFormedPageSelection(String selection, int totalPages) {
+ checkPageSelection(selection, totalPages, false);
+ }
+
+ private void checkPageSelection(String selection, int totalPages, boolean requireMatch) {
+ if (selection == null || selection.isBlank()) {
+ return;
+ }
+ List<String> malformed = new ArrayList<>();
+ List<String> outOfRange = new ArrayList<>();
+ boolean matchesAPage = false;
+ boolean hasToken = false;
+ for (String raw : selection.split(",")) {
+ String token = raw.trim();
+ if (token.isEmpty()) {
+ continue;
+ }
+ hasToken = true;
+ if ("all".equalsIgnoreCase(token)) {
+ matchesAPage = matchesAPage || totalPages > 0;
+ continue;
+ }
+ if (token.contains("n") && isNFunction(token)) {
+ if (totalPages > 0 && !evaluateNFunc(token, totalPages).isEmpty()) {
+ matchesAPage = true;
+ } else {
+ outOfRange.add(token);
+ }
+ continue;
+ }
+ switch (classifyPageToken(token, totalPages)) {
+ case IN_RANGE -> matchesAPage = true;
+ case OUT_OF_RANGE -> outOfRange.add(token);
+ case MALFORMED -> malformed.add(token);
+ }
+ }
+ List<String> invalid = hasToken ? malformed : List.of(selection);
+ if (requireMatch && invalid.isEmpty() && !matchesAPage) {
+ invalid = outOfRange.isEmpty() ? List.of(selection) : outOfRange;
+ }
+ if (!invalid.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Invalid page selection '"
+ + String.join(",", invalid)
+ + "': pages are numbered 1 to "
+ + totalPages
+ + ".");
+ }
+ }
+
+ private enum PageToken {
+ IN_RANGE,
+ OUT_OF_RANGE,
+ MALFORMED
+ }
+
+ private static PageToken classifyPageToken(String token, int totalPages) {
+ try {
+ if (token.matches("\\d+")) {
+ int page = Integer.parseInt(token);
+ return page >= 1 && page <= totalPages
+ ? PageToken.IN_RANGE
+ : PageToken.OUT_OF_RANGE;
+ }
+ if (token.matches("\\d+\\s*-\\s*\\d*")) {
+ String[] range = token.split("-", -1);
+ int start = Math.max(1, Integer.parseInt(range[0].trim()));
+ int end =
+ range[1].isBlank()
+ ? Math.max(start, totalPages)
+ : Integer.parseInt(range[1].trim());
+ if (end < start) {
+ return PageToken.MALFORMED;
+ }
+ return start <= totalPages ? PageToken.IN_RANGE : PageToken.OUT_OF_RANGE;
+ }
+ } catch (NumberFormatException e) {
+ return PageToken.MALFORMED;
+ }
+ return PageToken.MALFORMED;
+ }
+
private List<Integer> handlePart(String part, int totalPages, int offset) {
List<Integer> partResult = new ArrayList<>();
String trimmedPart = part == null ? "" : part.trim();
diff --git a/app/common/src/main/java/stirling/software/common/util/PdfUtils.java b/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
index aef52520d5..575d1bec51 100644
--- a/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
@@ -121,6 +121,8 @@ public class PdfUtils {
}
public boolean hasImages(PDDocument document, String pagesToCheck) throws IOException {
+ pagesToCheck = pagesToCheck == null || pagesToCheck.isBlank() ? "all" : pagesToCheck;
+ GeneralUtils.requireWellFormedPageSelection(pagesToCheck, document.getNumberOfPages());
String[] pageOrderArr = pagesToCheck.split(",");
List<Integer> pageList =
GeneralUtils.parsePageList(pageOrderArr, document.getNumberOfPages());
@@ -137,6 +139,12 @@ public class PdfUtils {
public boolean hasText(PDDocument document, String pageNumbersToCheck, String phrase)
throws IOException {
+ pageNumbersToCheck =
+ pageNumbersToCheck == null || pageNumbersToCheck.isBlank()
+ ? "all"
+ : pageNumbersToCheck;
+ GeneralUtils.requireWellFormedPageSelection(
+ pageNumbersToCheck, document.getNumberOfPages());
String[] pageOrderArr = pageNumbersToCheck.split(",");
List<Integer> pageList =
GeneralUtils.parsePageList(pageOrderArr, document.getNumberOfPages());
diff --git a/app/common/src/test/java/stirling/software/common/service/InternalApiClientTest.java b/app/common/src/test/java/stirling/software/common/service/InternalApiClientTest.java
index febee045e1..6bb98d0268 100644
--- a/app/common/src/test/java/stirling/software/common/service/InternalApiClientTest.java
+++ b/app/common/src/test/java/stirling/software/common/service/InternalApiClientTest.java
@@ -15,6 +15,8 @@ import java.nio.file.Path;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.ByteArrayResource;
@@ -22,6 +24,9 @@ import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.env.MockEnvironment;
+import org.springframework.mock.http.client.MockClientHttpRequest;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RequestCallback;
@@ -241,6 +246,54 @@ class InternalApiClientTest {
assertThrows(SecurityException.class, () -> client.post("/api/v1/ai/orchestrate", body));
}
+ @Test
+ void postAllowsOnlyFillingAndListingFormFields() {
+ MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
+ // The editor's field editing endpoints stay out of internal dispatch.
+ assertThrows(SecurityException.class, () -> client.post("/api/v1/form/edit-fields", body));
+ assertThrows(SecurityException.class, () -> client.post("/api/v1/form/fill/x", body));
+ assertTrue(InternalApiClient.isDispatchable("/api/v1/form/fill"));
+ assertTrue(InternalApiClient.isDispatchable("/api/v1/form/fields"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {"/api/v1/convert/url/pdf", "/api/v1/ai/tools/create-pdf-from-html-agent"})
+ void generatorsWithoutFilesAreSentAsMultipart(String endpoint) throws Exception {
+ RestTemplate template = (RestTemplate) ReflectionTestUtils.getField(client, "restTemplate");
+ MockRestServiceServer server = MockRestServiceServer.createServer(template);
+ MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
+ body.add("urlInput", "https://example.com");
+ Path tempPath = Files.createTempFile("internal-api-generator-test", ".pdf");
+ TempFile tempFile = mock(TempFile.class);
+ when(tempFile.getPath()).thenReturn(tempPath);
+ when(tempFile.getFile()).thenReturn(tempPath.toFile());
+ when(tempFileManager.createManagedTempFile("internal-api")).thenReturn(tempFile);
+
+ server.expect(
+ org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo(
+ "http://localhost:8080" + endpoint))
+ .andExpect(
+ request -> {
+ MediaType contentType = request.getHeaders().getContentType();
+ assertNotNull(contentType);
+ assertTrue(MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType));
+ assertNotNull(contentType.getParameter("boundary"));
+ String encoded = ((MockClientHttpRequest) request).getBodyAsString();
+ assertTrue(encoded.contains("name=\"urlInput\""));
+ assertTrue(encoded.contains("https://example.com"));
+ })
+ .andRespond(
+ org.springframework.test.web.client.response.MockRestResponseCreators
+ .withSuccess("pdf", MediaType.APPLICATION_PDF));
+ try {
+ assertEquals(HttpStatus.OK, client.post(endpoint, body).getStatusCode());
+ server.verify();
+ } finally {
+ Files.deleteIfExists(tempPath);
+ }
+ }
+
@Test
void postAcceptsAiToolsSubnamespace() throws Exception {
// Agent tool paths like /api/v1/ai/tools/pdf-comment-agent are on the allowlist and
diff --git a/app/common/src/test/java/stirling/software/common/service/ToolChainValidatorTest.java b/app/common/src/test/java/stirling/software/common/service/ToolChainValidatorTest.java
new file mode 100644
index 0000000000..d60137906e
--- /dev/null
+++ b/app/common/src/test/java/stirling/software/common/service/ToolChainValidatorTest.java
@@ -0,0 +1,114 @@
+package stirling.software.common.service;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.common.model.tool.ToolArity;
+import stirling.software.common.model.tool.ToolDiagnostic;
+import stirling.software.common.model.tool.ToolFormat;
+import stirling.software.common.model.tool.ToolIOSource;
+import stirling.software.common.model.tool.ToolIOSpec;
+
+/** Unknown operations, which only the server can detect and so sit outside the shared cases. */
+class ToolChainValidatorTest {
+
+ private static final String ROTATE = "/api/v1/general/rotate-pdf";
+ private static final String EXTRACT_IMAGES = "/api/v1/misc/extract-images";
+ private static final String UNDECLARED = "/api/v1/misc/undeclared";
+
+ private static final Map<String, ToolIOSpec> SPECS =
+ Map.of(
+ ROTATE,
+ new ToolIOSpec(
+ Set.of(ToolFormat.PDF), ToolFormat.PDF, ToolArity.SISO, List.of()),
+ EXTRACT_IMAGES,
+ new ToolIOSpec(
+ Set.of(ToolFormat.PDF), ToolFormat.IMAGE, ToolArity.SIMO, List.of()));
+
+ private static final ToolIOSource SOURCE =
+ new ToolIOSource() {
+ @Override
+ public Optional<ToolIOSpec> find(String operationPath) {
+ return Optional.ofNullable(SPECS.get(operationPath));
+ }
+
+ @Override
+ public boolean isKnown(String operationPath) {
+ return Set.of(ROTATE, EXTRACT_IMAGES, UNDECLARED).contains(operationPath);
+ }
+ };
+
+ private final ToolChainValidator validator = new ToolChainValidator(SOURCE);
+
+ @Test
+ void anUnknownOperationIsAnErrorNamingIt() {
+ List<ToolDiagnostic> diagnostics =
+ validator.validate(steps(ROTATE, "/api/v1/misc/no-such-tool"));
+
+ assertEquals(1, diagnostics.size());
+ ToolDiagnostic diagnostic = diagnostics.get(0);
+ assertEquals(1, diagnostic.stepIndex());
+ assertEquals(ToolDiagnostic.Severity.ERROR, diagnostic.severity());
+ assertEquals(ToolDiagnostic.UNKNOWN_OPERATION, diagnostic.code());
+ assertTrue(diagnostic.message().contains("/api/v1/misc/no-such-tool"));
+ assertTrue(ToolChainValidator.hasErrors(diagnostics));
+ }
+
+ @Test
+ void aBlankOperationIsUnknown() {
+ List<ToolDiagnostic> diagnostics =
+ validator.validate(
+ List.of(
+ new ToolChainValidator.Step(null, null),
+ new ToolChainValidator.Step("", null)));
+
+ assertEquals(2, diagnostics.size());
+ assertTrue(
+ diagnostics.stream()
+ .allMatch(d -> ToolDiagnostic.UNKNOWN_OPERATION.equals(d.code())));
+ }
+
+ @Test
+ void aKnownButUndeclaredOperationOnlyWarns() {
+ List<ToolDiagnostic> diagnostics = validator.validate(steps(UNDECLARED, ROTATE));
+
+ assertEquals(1, diagnostics.size());
+ assertEquals(ToolDiagnostic.UNDECLARED, diagnostics.get(0).code());
+ assertFalse(ToolChainValidator.hasErrors(diagnostics));
+ }
+
+ @Test
+ void nothingPastAnUnknownStepIsJudged() {
+ // Extract-images then rotate is a mismatch, but the unknown step between them breaks the
+ // carry, so only the unknown step is reported.
+ List<ToolDiagnostic> diagnostics =
+ validator.validate(steps(EXTRACT_IMAGES, "/api/v1/misc/nope", ROTATE));
+
+ assertEquals(1, diagnostics.size());
+ assertEquals(ToolDiagnostic.UNKNOWN_OPERATION, diagnostics.get(0).code());
+ }
+
+ @Test
+ void aSourceThatCannotListEndpointsTreatsEveryPathAsKnown() {
+ ToolChainValidator lenient = new ToolChainValidator(ToolIOSource.of(SPECS));
+
+ List<ToolDiagnostic> diagnostics = lenient.validate(steps("/api/v1/misc/anything"));
+
+ assertEquals(ToolDiagnostic.UNDECLARED, diagnostics.get(0).code());
+ assertEquals(ToolDiagnostic.Severity.WARN, diagnostics.get(0).severity());
+ }
+
+ private static List<ToolChainValidator.Step> steps(String... operations) {
+ return java.util.Arrays.stream(operations)
+ .map(op -> new ToolChainValidator.Step(op, null))
+ .toList();
+ }
+}
diff --git a/app/common/src/test/java/stirling/software/common/service/ToolIODiscoveryTest.java b/app/common/src/test/java/stirling/software/common/service/ToolIODiscoveryTest.java
index 4059382a55..b1ca2469e1 100644
--- a/app/common/src/test/java/stirling/software/common/service/ToolIODiscoveryTest.java
+++ b/app/common/src/test/java/stirling/software/common/service/ToolIODiscoveryTest.java
@@ -9,7 +9,10 @@ import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.StaticWebApplicationContext;
@@ -66,12 +69,55 @@ class ToolIODiscoveryTest {
}
}
+ @RestController
+ @RequestMapping("/api/v1/misc")
+ static class DispatchableFixtureController {
+
+ @PostMapping("/fixture-session/{sessionId}/finalize")
+ @ToolIO(produces = ToolFormat.PDF)
+ public String finalizeSession() {
+ return "";
+ }
+
+ @PostMapping("/fixture-undeclared")
+ public String undeclared() {
+ return "";
+ }
+
+ @GetMapping("/fixture-get-only")
+ public String getOnly() {
+ return "";
+ }
+
+ @PostMapping(value = "/fixture-json", consumes = MediaType.APPLICATION_JSON_VALUE)
+ public String json() {
+ return "";
+ }
+
+ @PostMapping("/fixture-request-body")
+ public String requestBody(@RequestBody Map<String, String> body) {
+ return "";
+ }
+
+ @PostMapping(value = "/fixture-generator", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ public String generator() {
+ return "";
+ }
+
+ @PostMapping(value = "/fixture-any-content", consumes = MediaType.ALL_VALUE)
+ public String anyContent() {
+ return "";
+ }
+ }
+
private static ToolIORegistry registry;
@BeforeAll
static void discover() {
StaticWebApplicationContext context = new StaticWebApplicationContext();
context.registerSingleton("fixtureController", FixtureController.class);
+ context.registerSingleton(
+ "dispatchableFixtureController", DispatchableFixtureController.class);
RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping();
mapping.setApplicationContext(context);
mapping.afterPropertiesSet();
@@ -112,6 +158,42 @@ class ToolIODiscoveryTest {
spec.resolveOutput(Map.of("password", "", "ownerPassword", "")).format());
}
+ @Test
+ void knowsDispatchablePostEndpointsWhetherOrNotTheyDeclareToolIO() {
+ assertTrue(registry.isKnown("/api/v1/misc/fixture-undeclared"));
+ assertFalse(registry.isKnown("/api/v1/misc/no-such-tool"));
+ }
+
+ @Test
+ void doesNotKnowEndpointsThePipelineRunnerCannotDispatchTo() {
+ assertFalse(registry.isKnown("/api/v1/misc/fixture-get-only"));
+ // Declared, but outside InternalApiClient's allow-list.
+ assertFalse(registry.isKnown("/api/v1/fixture/rotate"));
+ }
+
+ @Test
+ void onlyKnowsEndpointsThatAcceptTheDispatchersMultipartForm() {
+ assertFalse(registry.isKnown("/api/v1/misc/fixture-json"));
+ assertFalse(registry.isKnown("/api/v1/misc/fixture-request-body"));
+ assertTrue(registry.isKnown("/api/v1/misc/fixture-generator"));
+ assertTrue(registry.isKnown("/api/v1/misc/fixture-any-content"));
+ }
+
+ @Test
+ void matchesConcreteVariableRoutesWithoutAcceptingUnrelatedPaths() {
+ String concrete = "/api/v1/misc/fixture-session/abc/finalize";
+ assertTrue(registry.isKnown(concrete));
+ assertEquals(ToolFormat.PDF, registry.find(concrete).orElseThrow().produces());
+ assertFalse(registry.isKnown("/api/v1/misc/fixture-session/{sessionId}/finalize"));
+ assertFalse(registry.isKnown(concrete + "/extra"));
+ assertFalse(registry.isKnown("/api/v1/misc/fixture-session/abc/other"));
+ }
+
+ @Test
+ void knowsEveryPathBeforeDiscoveryHasRun() {
+ assertTrue(new ToolIORegistry(null).isKnown("/api/v1/misc/anything"));
+ }
+
@Test
void exposesInputExtensionsForRunTimeFileChecks() {
assertEquals(List.of("pdf"), registry.getExtensionTypes(false, "/api/v1/fixture/rotate"));
diff --git a/app/common/src/test/java/stirling/software/common/util/GeneralUtilsPageSelectionTest.java b/app/common/src/test/java/stirling/software/common/util/GeneralUtilsPageSelectionTest.java
new file mode 100644
index 0000000000..56005a2bd3
--- /dev/null
+++ b/app/common/src/test/java/stirling/software/common/util/GeneralUtilsPageSelectionTest.java
@@ -0,0 +1,77 @@
+package stirling.software.common.util;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class GeneralUtilsPageSelectionTest {
+
+ @ParameterizedTest
+ @ValueSource(strings = {"100n", "n+100", ",,", "99", "100n,99", "0"})
+ void rejectsSelectionsThatResolveToNoPages(String selection) {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> GeneralUtils.requireValidPageSelection(selection, 5));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"1 2", "a ll", "-1", "3-1", "n+"})
+ void rejectsMalformedTokensInsteadOfRemovingInternalWhitespace(String selection) {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> GeneralUtils.requireValidPageSelection(selection, 15));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"0-3", "0 - 3"})
+ void acceptsARangeStartingAtZeroAsStartingAtPageOne(String selection) {
+ assertDoesNotThrow(() -> GeneralUtils.requireValidPageSelection(selection, 5));
+ assertEquals(List.of(1, 2, 3), GeneralUtils.parsePageList(selection, 5, true));
+ }
+
+ @Test
+ void acceptsAZeroAlongsideAPageThatMatches() {
+ assertDoesNotThrow(() -> GeneralUtils.requireValidPageSelection("0,2", 5));
+ assertEquals(List.of(2), GeneralUtils.parsePageList("0,2", 5, true));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"1,99", "1,100n", "1,n+100"})
+ void acceptsSelectionsThatMatchSomePagesInASmallerBatchDocument(String selection) {
+ assertDoesNotThrow(() -> GeneralUtils.requireValidPageSelection(selection, 5));
+ assertEquals(List.of(1), GeneralUtils.parsePageList(selection, 5, true));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {" 1 - 3 ", "1-3", "1 - "})
+ void acceptsRangeWhitespaceSupportedByTheParser(String selection) {
+ assertDoesNotThrow(() -> GeneralUtils.requireValidPageSelection(selection, 3));
+ assertEquals(List.of(1, 2, 3), GeneralUtils.parsePageList(selection, 3, true));
+ }
+
+ @Test
+ void acceptsNFunctionsThatActuallyMatch() {
+ GeneralUtils.requireValidPageSelection("2n+1", 5);
+ assertEquals(List.of(3, 5), GeneralUtils.parsePageList("2n+1", 5, true));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"99", "5-10", "100n", "0", "0-2"})
+ void wellFormedCheckAllowsSelectionsThatMatchNoPage(String selection) {
+ assertDoesNotThrow(() -> GeneralUtils.requireWellFormedPageSelection(selection, 3));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"-1", "abc", "3-1", ",,,", " , "})
+ void wellFormedCheckStillRejectsMalformedTokens(String selection) {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> GeneralUtils.requireWellFormedPageSelection(selection, 3));
+ }
+}
diff --git a/app/common/src/test/java/stirling/software/common/util/PdfUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/PdfUtilsTest.java
index 1e1729ed2d..d543d8fb78 100644
--- a/app/common/src/test/java/stirling/software/common/util/PdfUtilsTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/PdfUtilsTest.java
@@ -19,6 +19,43 @@ import org.junit.jupiter.params.provider.CsvSource;
class PdfUtilsTest {
+ @ParameterizedTest
+ @CsvSource(
+ value = {"-1", "abc", "3-1", ",,,"},
+ delimiter = ';')
+ void filtersRejectMalformedSelections(String selection) throws IOException {
+ try (PDDocument doc = new PDDocument()) {
+ doc.addPage(new PDPage());
+ assertThrows(IllegalArgumentException.class, () -> PdfUtils.hasImages(doc, selection));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> PdfUtils.hasText(doc, selection, "hello"));
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"99", "5-10", "100n", "n+100", "0"})
+ void filtersTreatPagesPastTheEndAsNoMatch(String selection) throws IOException {
+ try (PDDocument doc = new PDDocument()) {
+ PDPage page = new PDPage();
+ page.setResources(new PDResources());
+ doc.addPage(page);
+ assertFalse(PdfUtils.hasImages(doc, selection));
+ assertFalse(PdfUtils.hasText(doc, selection, "hello"));
+ }
+ }
+
+ @Test
+ void filtersTreatBlankSelectionsAsAllPages() throws IOException {
+ try (PDDocument doc = new PDDocument()) {
+ PDPage page = new PDPage();
+ page.setResources(new PDResources());
+ doc.addPage(page);
+ assertFalse(PdfUtils.hasImages(doc, " "));
+ assertFalse(PdfUtils.hasText(doc, " ", "hello"));
+ }
+ }
+
@ParameterizedTest
@CsvSource({"A0", "A1", "A2", "A3", "A4", "A5", "A6", "LETTER", "LEGAL"})
void textToPageSize_validSizes_returnsCorrectRectangle(String size) {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
index 57c32f0712..734999ff43 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
@@ -133,11 +133,31 @@ public class CropController {
return endpointConfiguration.isGroupEnabled("Ghostscript");
}
+ /** A zero or negative crop box would blank every page while reporting success. */
+ private static void requirePositiveSize(CropPdfForm request) {
+ Float width = request.getWidth();
+ Float height = request.getHeight();
+ if (width == null || height == null) {
+ return; // Reported by the existing "coordinates are required" check.
+ }
+ if (width <= 0 || height <= 0) {
+ throw new IllegalArgumentException(
+ "Invalid crop size: width and height must be greater than 0 (got width="
+ + width
+ + ", height="
+ + height
+ + ").");
+ }
+ }
+
private static BitSet pageSelection(CropPdfForm request, PDDocument document) {
BitSet selected = new BitSet(document.getNumberOfPages());
request.getPageNumbersList(document, false).forEach(selected::set);
String pageNumbers = request.getPageNumbers();
- if (selected.isEmpty() && pageNumbers != null && !pageNumbers.isBlank()) {
+ if (selected.isEmpty()
+ && pageNumbers != null
+ && !pageNumbers.isBlank()
+ && !"all".equalsIgnoreCase(pageNumbers.trim())) {
throw new IllegalArgumentException(
"pageNumbers '" + pageNumbers + "' does not select any page");
}
@@ -159,6 +179,7 @@ public class CropController {
if (request.isAutoCrop()) {
return cropWithAutomaticDetection(request);
}
+ requirePositiveSize(request);
if (request.getX() == null
|| request.getY() == null
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/RearrangePagesPDFController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/RearrangePagesPDFController.java
index cbd7b7c28b..956178af52 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/RearrangePagesPDFController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/RearrangePagesPDFController.java
@@ -70,11 +70,19 @@ public class RearrangePagesPDFController {
try (PDDocument document = pdfDocumentFactory.load(pdfFile)) {
+ GeneralUtils.requireValidPageSelection(pagesToDelete, document.getNumberOfPages());
// Split the page order string into an array of page numbers or range of numbers
String[] pageOrderArr = pagesToDelete.split(",");
List<Integer> pagesToRemove =
GeneralUtils.parsePageList(pageOrderArr, document.getNumberOfPages(), false);
+ // pageNumbers defaults to "all", which here would delete the whole document.
+ if (new HashSet<>(pagesToRemove).size() >= document.getNumberOfPages()) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.invalidArgument",
+ "Invalid argument: {0}",
+ "pageNumbers must list the pages to remove and leave at least one page");
+ }
Collections.sort(pagesToRemove);
@@ -251,11 +259,16 @@ public class RearrangePagesPDFController {
@StandardPdfResponse
@ToolIO(produces = ToolFormat.PDF)
@Operation(
- summary = "Rearrange pages in a PDF file",
+ summary =
+ "Extract, reorder or duplicate pages: pageNumbers = pages to keep in order"
+ + " ('3-7' extracts 3-7), or customMode",
description =
- "This endpoint rearranges pages in a given PDF file based on the specified page"
- + " order or custom mode. Users can provide a page order as a comma-separated list"
- + " of page numbers or page ranges, or a custom mode.")
+ "Builds the output from pageNumbers, in the order given: '3-7' keeps only pages"
+ + " 3 to 7, '3,1,2' keeps pages 3, 1 and 2 in that order, and pages not"
+ + " listed are dropped (a page listed twice is kept once). Or set"
+ + " customMode to a preset such as REVERSE_ORDER, DUPLEX_SORT or"
+ + " REMOVE_FIRST; with DUPLICATE, pageNumbers is how many copies of"
+ + " each page to make.")
public ResponseEntity<Resource> rearrangePages(@ModelAttribute RearrangePagesRequest request)
throws IOException {
MultipartFile pdfFile = request.getFileInput();
@@ -274,6 +287,7 @@ public class RearrangePagesPDFController {
&& !"custom".equals(sortType.toLowerCase(Locale.ROOT))) {
newPageOrder = processSortTypes(sortType, totalPages, pageOrder);
} else {
+ GeneralUtils.requireValidPageSelection(pageOrder, totalPages);
newPageOrder = GeneralUtils.parsePageList(pageOrderArr, totalPages, false);
}
log.debug(
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java
index b217976812..acb145efa3 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java
@@ -47,23 +47,21 @@ public class ScalePagesController {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
- private static PDRectangle getTargetSize(
- String targetPDRectangle, String orientation, PDDocument sourceDocument) {
- if ("KEEP".equals(targetPDRectangle)) {
- if (sourceDocument.getNumberOfPages() == 0) {
- throw ExceptionUtils.createPdfNoPages();
- }
-
- PDPage sourcePage = sourceDocument.getPage(0);
- PDRectangle sourceSize = sourcePage.getMediaBox();
-
- if (sourceSize == null) {
- throw ExceptionUtils.createInvalidPageSizeException("KEEP");
- }
+ private static boolean keepsPageSize(String targetPDRectangle) {
+ return targetPDRectangle == null
+ || targetPDRectangle.isBlank()
+ || "KEEP".equals(targetPDRectangle);
+ }
- return sourceSize;
+ /** The page's own size, at the origin like the named sizes so the content lands centred. */
+ private static PDRectangle ownSize(PDRectangle mediaBox) {
+ if (mediaBox == null) {
+ throw ExceptionUtils.createInvalidPageSizeException("KEEP");
}
+ return new PDRectangle(mediaBox.getWidth(), mediaBox.getHeight());
+ }
+ private static PDRectangle getTargetSize(String targetPDRectangle, String orientation) {
Map<String, PDRectangle> sizeMap = getSizeMap();
PDRectangle base = sizeMap.get(targetPDRectangle);
if (base == null) {
@@ -111,7 +109,11 @@ public class ScalePagesController {
PDDocument outputDocument =
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument)) {
- PDRectangle targetSize = getTargetSize(targetPDRectangle, orientation, sourceDocument);
+ boolean keepSize = keepsPageSize(targetPDRectangle);
+ if (keepSize && sourceDocument.getNumberOfPages() == 0) {
+ throw ExceptionUtils.createPdfNoPages();
+ }
+ PDRectangle fixedSize = keepSize ? null : getTargetSize(targetPDRectangle, orientation);
// Create LayerUtility once outside the loop for better performance
LayerUtility layerUtility = new LayerUtility(outputDocument);
@@ -121,6 +123,8 @@ public class ScalePagesController {
PDPage sourcePage = sourceDocument.getPage(i);
flattenStampAppearances(sourceDocument, sourcePage);
PDRectangle sourceSize = sourcePage.getMediaBox();
+ // Per page, so a mixed-size document stays mixed.
+ PDRectangle targetSize = keepSize ? ownSize(sourceSize) : fixedSize;
float scaleWidth = targetSize.getWidth() / sourceSize.getWidth();
float scaleHeight = targetSize.getHeight() / sourceSize.getHeight();
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySectionsController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySectionsController.java
index 0e8619f644..5be9ccd4ae 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySectionsController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySectionsController.java
@@ -309,6 +309,7 @@ public class SplitPdfBySectionsController {
"page numbers",
"custom");
}
+ GeneralUtils.requireValidPageSelection(pageNumbers, totalPages);
String[] pageOrderArr = pageNumbers.split(",");
List<Integer> pageListToSplit =
GeneralUtils.parsePageList(pageOrderArr, totalPages, false);
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java
index 8721fd3b70..becf119130 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java
@@ -66,6 +66,9 @@ public class SplitPdfBySizeController {
public ResponseEntity<Resource> autoSplitPdf(
@ModelAttribute SplitPdfBySizeOrCountRequest request) throws Exception {
+ if (request.getSplitType() == 1 || request.getSplitType() == 2) {
+ requirePositiveCount(request.getSplitValue());
+ }
MultipartFile file = request.getFileInput();
String filename = GeneralUtils.generateFilename(file.getOriginalFilename(), "");
@@ -112,6 +115,18 @@ public class SplitPdfBySizeController {
}
}
+ private static int requirePositiveCount(String value) {
+ try {
+ int count = Integer.parseInt(value);
+ if (count > 0) return count;
+ } catch (NumberFormatException ignored) {
+ }
+ throw ExceptionUtils.createIllegalArgumentException(
+ ExceptionUtils.ErrorCode.INVALID_ARGUMENT,
+ "splitValue",
+ "must be a positive integer for page-count or document-count splitting");
+ }
+
private List<int[]> computeRanges(SplitPdfBySizeOrCountRequest request, PdfDocument sourceDoc)
throws IOException {
int type = request.getSplitType();
@@ -119,9 +134,9 @@ public class SplitPdfBySizeController {
if (type == 0) {
return computeSizeRanges(sourceDoc, GeneralUtils.convertSizeToBytes(value));
} else if (type == 1) {
- return computePageCountRanges(sourceDoc, Integer.parseInt(value));
+ return computePageCountRanges(sourceDoc, requirePositiveCount(value));
} else if (type == 2) {
- return computeDocCountRanges(sourceDoc, Integer.parseInt(value));
+ return computeDocCountRanges(sourceDoc, requirePositiveCount(value));
}
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument", "Invalid argument: {0}", "split type: " + type);
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java
index 309ce4ee5a..bd33e00484 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java
@@ -444,6 +444,7 @@ public class ConvertImgPDFController {
try (PDDocument document = pdfDocumentFactory.load(pdfFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
int totalPages = document.getNumberOfPages();
+ GeneralUtils.requireValidPageSelection(String.join(",", pageOrderArr), totalPages);
List<Integer> newPageOrder =
GeneralUtils.parsePageList(pageOrderArr, totalPages, false);
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java
index 2a4ed8a125..b4b5e6ea4e 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java
@@ -21,6 +21,8 @@ import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.WebDataBinder;
+import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import io.swagger.v3.oas.annotations.Operation;
@@ -57,6 +59,9 @@ import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempDirectory;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import stirling.software.common.util.propertyeditor.JsonListPropertyEditor;
+
+import tools.jackson.core.type.TypeReference;
@MiscApi
@Slf4j
@@ -78,6 +83,14 @@ public class AutoRotateController {
private final RuntimePathConfig runtimePathConfig;
private final ApplicationProperties applicationProperties;
+ @InitBinder
+ public void initBinder(WebDataBinder binder) {
+ binder.registerCustomEditor(
+ List.class,
+ "pageRotations",
+ new JsonListPropertyEditor<>(new TypeReference<List<PageRotation>>() {}));
+ }
+
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/auto-rotate-pdf",
@@ -95,8 +108,9 @@ public class AutoRotateController {
"Detects each page's orientation (embedded-text direction first, Tesseract OSD"
+ " for scanned pages) and sets the page rotation so the content"
+ " displays upright. With dryRun=true, returns a JSON per-page report"
- + " instead of the PDF. With pageRotations set, applies the given"
- + " corrections without running detection.")
+ + " instead of the PDF. With pageRotations set (a JSON list such as"
+ + " [{\"pageNumber\":3,\"rotation\":90}]), applies only those"
+ + " clockwise turns without running detection.")
public ResponseEntity<?> autoRotatePdf(@Valid @ModelAttribute AutoRotatePdfRequest request)
throws IOException, InterruptedException {
String mode =
@@ -330,6 +344,12 @@ public class AutoRotateController {
int pageCount = document.getNumberOfPages();
Set<Integer> seen = new HashSet<>();
for (PageRotation entry : rotations) {
+ if (entry == null) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ ExceptionUtils.ErrorCode.INVALID_ARGUMENT,
+ "pageRotations",
+ "entries must not be null");
+ }
Integer pageNumber = entry.getPageNumber();
Integer angle = entry.getRotation();
if (pageNumber == null
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java
index 5bf857bb8d..65cbeba2db 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java
@@ -10,6 +10,8 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -65,6 +67,11 @@ public class OCRController {
// Tesseract's recommended minimum; more pixels cost time without improving recognition
private static final int OCR_RENDER_DPI = 300;
+ // OCRmyPDF's PriorOcrFoundError: a page has text and neither skip nor force was requested
+ private static final int OCRMYPDF_PRIOR_OCR_FOUND = 6;
+ private static final Pattern PROCESS_EXIT_CODE_PATTERN =
+ Pattern.compile("failed with exit code (\\d+)");
+
private final ApplicationProperties applicationProperties;
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
@@ -304,18 +311,14 @@ public class OCRController {
tempOutputFile.toString()));
// Run CLI command
- ProcessExecutorResult result =
- ProcessExecutor.getInstance(ProcessExecutor.Processes.OCR_MY_PDF)
- .runCommandWithOutputHandling(command);
+ ProcessExecutorResult result = runOcrMyPdf(command);
if (result.getRc() != 0
&& result.getMessages().contains("multiprocessing/synchronize.py")
&& result.getMessages().contains("OSError: [Errno 38] Function not implemented")) {
command.add("--jobs");
command.add("1");
- result =
- ProcessExecutor.getInstance(ProcessExecutor.Processes.OCR_MY_PDF)
- .runCommandWithOutputHandling(command);
+ result = runOcrMyPdf(command);
}
if (result.getRc() != 0) {
@@ -346,6 +349,40 @@ public class OCRController {
}
}
+ // Turns OCRmyPDF's "page already has text" exit into a 400 naming the fix. The executor
+ // reports a non-zero exit either as a result or as an IOException, so both are checked.
+ private ProcessExecutorResult runOcrMyPdf(List<String> command)
+ throws IOException, InterruptedException {
+ ProcessExecutorResult result;
+ try {
+ result =
+ ProcessExecutor.getInstance(ProcessExecutor.Processes.OCR_MY_PDF)
+ .runCommandWithOutputHandling(command);
+ } catch (IOException e) {
+ if (exitCodeOf(e) == OCRMYPDF_PRIOR_OCR_FOUND) {
+ throw priorTextFoundException();
+ }
+ throw e;
+ }
+ if (result.getRc() == OCRMYPDF_PRIOR_OCR_FOUND) {
+ throw priorTextFoundException();
+ }
+ return result;
+ }
+
+ private static int exitCodeOf(IOException e) {
+ Matcher matcher =
+ PROCESS_EXIT_CODE_PATTERN.matcher(e.getMessage() == null ? "" : e.getMessage());
+ return matcher.find() ? Integer.parseInt(matcher.group(1)) : -1;
+ }
+
+ private static IllegalArgumentException priorTextFoundException() {
+ return ExceptionUtils.createInvalidArgumentException(
+ "ocrType",
+ "the PDF already contains text. Use ocrType 'skip-text' to OCR only pages"
+ + " without text, or 'force-ocr' to redo OCR on every page.");
+ }
+
private void processWithTesseract(
List<String> selectedLanguages, String ocrType, Path tempInputFile, Path tempOutputFile)
throws IOException, InterruptedException {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PageNumbersController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PageNumbersController.java
index bcced01ba9..5a966019bb 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PageNumbersController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PageNumbersController.java
@@ -98,6 +98,7 @@ public class PageNumbersController {
customText = "{n}";
}
+ GeneralUtils.requireValidPageSelection(pagesToNumber, document.getNumberOfPages());
List<Integer> pagesToNumberList =
GeneralUtils.parsePageList(
pagesToNumber.split(","), document.getNumberOfPages());
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/StampController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/StampController.java
index 86c9d39b2f..b05c9b2fba 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/StampController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/StampController.java
@@ -27,8 +27,6 @@ import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
-import org.apache.pdfbox.pdmodel.font.PDType1Font;
-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
@@ -122,11 +120,16 @@ public class StampController {
"error.invalid.filepath", "Invalid PDF file path: " + pdfFileName);
}
- String stampType = request.getStampType();
String stampText = request.getStampText();
MultipartFile stampImage = request.getStampImage();
+ String stampType = resolveStampType(request.getStampType(), stampImage);
+ if ("text".equalsIgnoreCase(stampType) && (stampText == null || stampText.isBlank())) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.stamp.text.required",
+ "Stamp text must be provided when stamp type is 'text'");
+ }
if ("image".equalsIgnoreCase(stampType)) {
- if (stampImage == null) {
+ if ((stampImage == null || stampImage.isEmpty())) {
throw ExceptionUtils.createIllegalArgumentException(
"error.stamp.image.required",
"Stamp image file must be provided when stamp type is 'image'");
@@ -166,6 +169,9 @@ public class StampController {
try (PDDocument document = pdfDocumentFactory.load(pdfFile)) {
List<Integer> pageNumbers = request.getPageNumbersList(document, true);
+ // CJK fonts are several MB, so load once per document rather than per page.
+ PDFont stampFont =
+ "text".equalsIgnoreCase(stampType) ? loadStampFont(document, alphabet) : null;
for (int pageIndex : pageNumbers) {
int zeroBasedIndex = pageIndex - 1;
@@ -210,7 +216,7 @@ public class StampController {
rotation,
position,
fontSize,
- alphabet,
+ stampFont,
overrideX,
overrideY,
margin,
@@ -253,48 +259,59 @@ public class StampController {
}
}
- private void addTextStamp(
- PDPageContentStream contentStream,
- String stampText,
- PDDocument document,
- PDPage page,
- float rotation,
- int position, // 1-9 positioning logic
- float fontSize,
- String alphabet,
- float overrideX, // X override
- float overrideY, // Y override
- float margin,
- String colorString,
- int currentPageNumber,
- String filename)
- throws IOException {
- String resourceDir;
- PDFont font = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
- resourceDir =
+ private static String resolveStampType(String stampType, MultipartFile stampImage) {
+ if (stampType == null || stampType.isBlank()) {
+ return stampImage != null && !stampImage.isEmpty() ? "image" : "text";
+ }
+ if (!"text".equalsIgnoreCase(stampType)
+ && !"image".equalsIgnoreCase(stampType)
+ && !"qr".equalsIgnoreCase(stampType)) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.stamp.type.invalid",
+ "Invalid stampType ''{0}'': must be ''text'', ''image'' or ''qr''",
+ stampType);
+ }
+ return stampType;
+ }
+
+ private PDFont loadStampFont(PDDocument document, String alphabet) throws IOException {
+ String resourceDir =
switch (alphabet) {
case "arabic" -> "static/fonts/NotoSansArabic-Regular.ttf";
- case "japanese" -> "static/fonts/Meiryo.ttf";
- case "korean" -> "static/fonts/malgun.ttf";
- case "chinese" -> "static/fonts/SimSun.ttf";
+ case "japanese" -> "static/fonts/NotoSansJP-Regular.ttf";
+ case "korean" -> "static/fonts/NotoSansKR-Regular.ttf";
+ case "chinese" -> "static/fonts/NotoSansSC-Regular.ttf";
case "thai" -> "static/fonts/NotoSansThai-Regular.ttf";
- case "roman" -> "static/fonts/NotoSans-Regular.ttf";
default -> "static/fonts/NotoSans-Regular.ttf";
};
-
ClassPathResource classPathResource = new ClassPathResource(resourceDir);
String fileExtension = resourceDir.substring(resourceDir.lastIndexOf('.'));
-
- // Use TempFile with try-with-resources for automatic cleanup
try (TempFile tempFileWrapper = new TempFile(tempFileManager, fileExtension)) {
File tempFile = tempFileWrapper.getFile();
try (InputStream is = classPathResource.getInputStream();
FileOutputStream os = new FileOutputStream(tempFile)) {
IOUtils.copy(is, os);
- font = PDType0Font.load(document, tempFile);
}
+ return PDType0Font.load(document, tempFile);
}
+ }
+ private void addTextStamp(
+ PDPageContentStream contentStream,
+ String stampText,
+ PDDocument document,
+ PDPage page,
+ float rotation,
+ int position, // 1-9 positioning logic
+ float fontSize,
+ PDFont font,
+ float overrideX, // X override
+ float overrideY, // Y override
+ float margin,
+ String colorString,
+ int currentPageNumber,
+ String filename)
+ throws IOException {
Color redactColor;
try {
if (!colorString.startsWith("#")) {
@@ -511,6 +528,12 @@ public class StampController {
// Load the stamp image
BufferedImage image = ImageIO.read(stampImage.getInputStream());
+ if (image == null) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ ExceptionUtils.ErrorCode.INVALID_ARGUMENT,
+ "stampImage",
+ "must be a supported image");
+ }
// Compute width based on original aspect ratio
float aspectRatio = (float) image.getWidth() / (float) image.getHeight();
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java
index 4e829245ba..cdb4a09b2e 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java
@@ -137,7 +137,8 @@ public class CertSignController {
String name,
String location,
String reason,
- Boolean showLogo) {
+ Boolean showLogo)
+ throws IOException {
try (PDDocument doc = pdfDocumentFactory.load(input)) {
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
@@ -147,10 +148,11 @@ public class CertSignController {
signature.setReason(reason);
signature.setSignDate(Calendar.getInstance()); // PDFBox requires Calendar
if (Boolean.TRUE.equals(showSignature)) {
+ int pageIndex = resolveSignaturePage(pageNumber, doc.getNumberOfPages());
try (SignatureOptions signatureOptions = new SignatureOptions()) {
signatureOptions.setVisualSignature(
- instance.createVisibleSignature(doc, signature, pageNumber, showLogo));
- signatureOptions.setPage(pageNumber);
+ instance.createVisibleSignature(doc, signature, pageIndex, showLogo));
+ signatureOptions.setPage(pageIndex);
doc.addSignature(signature, instance, signatureOptions);
doc.saveIncremental(output);
@@ -159,11 +161,24 @@ public class CertSignController {
doc.addSignature(signature, instance);
doc.saveIncremental(output);
}
- } catch (Exception e) {
- ExceptionUtils.logException("PDF signing", e);
}
}
+ // pageNumber is 0-based here and null means the first page, as the UI shows it.
+ private static int resolveSignaturePage(Integer pageNumber, int pageCount) {
+ int pageIndex = pageNumber == null ? 0 : pageNumber;
+ if (pageIndex < 0 || pageIndex >= pageCount) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.invalidArgument",
+ "Invalid argument: {0}",
+ "pageNumber "
+ + (pageIndex + 1)
+ + " - the visible signature needs a page from 1 to "
+ + pageCount);
+ }
+ return pageIndex;
+ }
+
@AutoJobPostMapping(
consumes = {
MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -174,11 +189,19 @@ public class CertSignController {
@StandardPdfResponse
@ToolIO(produces = ToolFormat.PDF)
@Operation(
- summary = "Sign PDF with a Digital Certificate",
+ summary =
+ "Digitally sign a PDF; certType SERVER uses the server's own certificate. Run"
+ + " last: later edits invalidate it",
description =
- "This endpoint accepts a PDF file, a digital certificate and related"
- + " information to sign the PDF. It then returns the digitally signed PDF"
- + " file.")
+ "Adds a digital signature to the PDF and returns the signed file. certType"
+ + " SERVER signs with this server's own certificate, so no file or"
+ + " password is needed, and the signer shown is the server's"
+ + " organisation rather than the user. PEM, PKCS12/PFX and JKS sign"
+ + " with an uploaded certificate and key; WINDOWS_STORE and PKCS11 work"
+ + " only in the desktop app. Make signing the last change to the file:"
+ + " any later edit (compress, watermark, add a password, flatten and"
+ + " so on) invalidates the signature. Set showSignature to add a"
+ + " visible signature box on pageNumber.")
public ResponseEntity<Resource> signPDFWithCert(
@ModelAttribute SignPDFWithCertRequest request, HttpServletRequest httpRequest)
throws Exception {
@@ -205,7 +228,8 @@ public class CertSignController {
}
KeyStore ks = null;
- String keystorePassword = password;
+ // Unencrypted keys and password-less keystores arrive with no password: use an empty one.
+ String keystorePassword = password != null ? password : "";
Provider signingProvider = null;
HardwareKeyStoreService.Pkcs11Session pkcs11Session = null;
@@ -219,8 +243,6 @@ public class CertSignController {
certFile, "PEM certificate", "certificate file is required");
ks = KeyStore.getInstance("JKS");
ks.load(null);
- // An unencrypted key needs no password, but the JKS entry still needs one.
- keystorePassword = password != null ? password : "";
PrivateKey privateKey =
getPrivateKeyFromPEM(privateKeyFile.getBytes(), keystorePassword);
Certificate cert = (Certificate) getCertificateFromPEM(certFile.getBytes());
@@ -236,14 +258,14 @@ public class CertSignController {
validateFilePresent(
p12File, "PKCS12 keystore", "PKCS12/PFX keystore file is required");
ks = KeyStore.getInstance("PKCS12");
- ks.load(p12File.getInputStream(), password.toCharArray());
+ loadKeyStore(ks, p12File, keystorePassword, "PKCS12 keystore");
break;
case "JKS":
jksfile =
validateFilePresent(
jksfile, "JKS keystore", "JKS keystore file is required");
ks = KeyStore.getInstance("JKS");
- ks.load(jksfile.getInputStream(), password.toCharArray());
+ loadKeyStore(ks, jksfile, keystorePassword, "JKS keystore");
break;
case "SERVER":
if (serverCertificateService == null) {
@@ -311,7 +333,7 @@ public class CertSignController {
location,
reason,
showLogo);
- } catch (IOException e) {
+ } catch (IOException | RuntimeException e) {
signedOut.close();
throw e;
} finally {
@@ -339,6 +361,29 @@ public class CertSignController {
return file;
}
+ // A wrong password surfaces as an IOException caused by UnrecoverableKeyException.
+ private static void loadKeyStore(KeyStore ks, MultipartFile file, String password, String label)
+ throws IOException, NoSuchAlgorithmException, CertificateException {
+ try (InputStream in = file.getInputStream()) {
+ ks.load(in, password.toCharArray());
+ } catch (IOException e) {
+ if (e.getCause() instanceof UnrecoverableKeyException) {
+ throw wrongPassword(label);
+ }
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.invalidArgument",
+ "Invalid argument: {0}",
+ label + " - the file could not be read as a " + label);
+ }
+ }
+
+ private static IllegalArgumentException wrongPassword(String label) {
+ return ExceptionUtils.createIllegalArgumentException(
+ "error.invalidArgument",
+ "Invalid argument: {0}",
+ "password - the " + label + " password is incorrect or missing");
+ }
+
private PrivateKey getPrivateKeyFromPEM(byte[] pemBytes, String password)
throws IOException, OperatorCreationException, PKCSException {
try (PEMParser pemParser =
@@ -348,26 +393,46 @@ public class CertSignController {
PrivateKeyInfo pkInfo;
if (pemObject instanceof PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo) {
InputDecryptorProvider decProv =
- new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
- pkInfo = pkcs8EncryptedPrivateKeyInfo.decryptPrivateKeyInfo(decProv);
+ new JceOpenSSLPKCS8DecryptorProviderBuilder()
+ .build(requirePemPassword(password));
+ try {
+ pkInfo = pkcs8EncryptedPrivateKeyInfo.decryptPrivateKeyInfo(decProv);
+ } catch (PKCSException e) {
+ throw wrongPassword("PEM private key");
+ }
} else if (pemObject instanceof PEMEncryptedKeyPair pemEncryptedKeyPair) {
PEMDecryptorProvider decProv =
- new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
- pkInfo = pemEncryptedKeyPair.decryptKeyPair(decProv).getPrivateKeyInfo();
+ new JcePEMDecryptorProviderBuilder().build(requirePemPassword(password));
+ try {
+ pkInfo = pemEncryptedKeyPair.decryptKeyPair(decProv).getPrivateKeyInfo();
+ } catch (IOException e) {
+ throw wrongPassword("PEM private key");
+ }
} else if (pemObject instanceof PEMKeyPair pemKeyPair) {
pkInfo = pemKeyPair.getPrivateKeyInfo();
} else if (pemObject instanceof PrivateKeyInfo privateKeyInfo) {
+ // Unencrypted PKCS#8 ("BEGIN PRIVATE KEY"), the usual openssl output.
pkInfo = privateKeyInfo;
} else {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument",
"Invalid argument: {0}",
- "PEM private key - file does not contain a private key");
+ "PEM private key - no private key found in the file");
}
return converter.getPrivateKey(pkInfo);
}
}
+ private static char[] requirePemPassword(String password) {
+ if (password == null || password.isEmpty()) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.invalidArgument",
+ "Invalid argument: {0}",
+ "PEM private key - the key is encrypted, so its password is required");
+ }
+ return password.toCharArray();
+ }
+
private Certificate getCertificateFromPEM(byte[] pemBytes)
throws IOException, CertificateException {
try (ByteArrayInputStream bis = new ByteArrayInputStream(pemBytes)) {
@@ -485,8 +550,10 @@ public class CertSignController {
cs.showText("Signed by " + name);
cs.newLine();
cs.showText(date);
- cs.newLine();
- cs.showText(reason);
+ if (StringUtils.isNotBlank(reason)) {
+ cs.newLine();
+ cs.showText(reason);
+ }
cs.endText();
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java
index 72d0c2e60f..564e787fe2 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java
@@ -407,23 +407,24 @@ public class GetInfoOnPDF {
for (PDFVerificationResult result : verificationResults) {
if (result == null) continue;
if (result.isCompliant()) {
- String std = result.getStandard().toLowerCase();
- if (std.contains("pdf_a") || std.contains("pdfa")) {
+ // The id is short ("2b", "ua1"); the name reads "PDF/A-2B", so match on that.
+ String std = standardFamily(result);
+ boolean notPdfa = "not-pdfa".equals(result.getStandard());
+ if (!notPdfa && (std.contains("pdfa") || result.isDeclaredPdfa())) {
isPdfA = true;
String profile = result.getValidationProfile();
if (profile != null) {
- if (profile.contains("1b")
- || profile.contains("2b")
- || profile.contains("3b")) {
+ String p = profile.toLowerCase();
+ if (p.contains("1b") || p.contains("2b") || p.contains("3b")) {
isPdfB = true;
}
// Simple extraction: remove "pdfa-" prefix
pdfAConformanceLevel = profile.replace("pdfa-", "");
}
}
- if (std.contains("pdf_ua") || std.contains("pdfua")) isPdfUA = true;
- if (std.contains("pdf_x") || std.contains("pdfx")) isPdfX = true;
- if (std.contains("pdf_e") || std.contains("pdfe")) isPdfE = true;
+ if (std.contains("pdfua")) isPdfUA = true;
+ if (std.contains("pdfx")) isPdfX = true;
+ if (std.contains("pdfe")) isPdfE = true;
}
}
}
@@ -457,6 +458,21 @@ public class GetInfoOnPDF {
return compliancy;
}
+ /** Lower-case letters and digits of the result's readable standard name, e.g. "pdfa2b". */
+ private static String standardFamily(PDFVerificationResult result) {
+ String name = result.getStandardName();
+ if (name == null || name.isBlank()) {
+ name = result.getValidationProfileName();
+ }
+ if (name == null || name.isBlank()) {
+ name = result.getStandard();
+ }
+ String family = name == null ? "" : name.toLowerCase().replaceAll("[^a-z0-9]", "");
+ String id = result.getStandard() == null ? "" : result.getStandard().toLowerCase();
+ // Bare veraPDF ids for PDF/UA ("ua1") carry no "pdf" prefix.
+ return id.startsWith("ua") ? "pdfua" + family : family;
+ }
+
private static boolean isSECCompliant(PDDocument doc) {
try {
// 1. Check Encryption
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ManualRedactionService.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ManualRedactionService.java
index 15a233f1f7..f9ee9764e7 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ManualRedactionService.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ManualRedactionService.java
@@ -393,6 +393,7 @@ class ManualRedactionService {
private List<Integer> getPageNumbers(ManualRedactPdfRequest request, int pagesCount) {
String pageNumbersInput = request.getPageNumbers();
+ GeneralUtils.requireValidPageSelection(pageNumbersInput, pagesCount);
String[] parsedPageNumbers =
pageNumbersInput != null ? pageNumbersInput.split(",") : new String[0];
List<Integer> pageNumbers =
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/RedactController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/RedactController.java
index 8254ec4afe..0e3e8d6102 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/RedactController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/RedactController.java
@@ -182,8 +182,13 @@ public class RedactController {
try {
RegexPatternUtils.getInstance().getPattern(term);
} catch (PatternSyntaxException e) {
+ // The error is logged, so it names the problem rather than the search term.
throw ExceptionUtils.createIllegalArgumentException(
- "error.redaction.no.patterns", "Invalid regex pattern: " + term);
+ "error.redaction.no.patterns",
+ "Invalid regex pattern: "
+ + e.getDescription()
+ + " near index "
+ + e.getIndex());
}
}
}
@@ -257,7 +262,9 @@ public class RedactController {
"JPDFium auto-redact: {} matches processed into {}",
result.totalMatches(),
filename);
- return WebResponseUtils.pdfFileToWebResponse(tempOutput, filename);
+ return withMatchCount(
+ WebResponseUtils.pdfFileToWebResponse(tempOutput, filename),
+ result.totalMatches());
} finally {
if (result.document() != null) {
result.document().close();
@@ -287,7 +294,9 @@ public class RedactController {
request.getCustomPadding(),
request.getConvertPDFToImage(),
false);
- return WebResponseUtils.pdfFileToWebResponse(finalized, filename);
+ int matches = foundTexts.values().stream().mapToInt(List::size).sum();
+ return withMatchCount(
+ WebResponseUtils.pdfFileToWebResponse(finalized, filename), matches);
}
}
} catch (IllegalArgumentException | ToolFailedException e) {
@@ -324,7 +333,23 @@ public class RedactController {
request.getFileInput().getOriginalFilename())))
+ "_redacted.pdf";
- TempFile out = redactExecuteService.execute(request);
- return WebResponseUtils.pdfFileToWebResponse(out, filename);
+ RedactExecuteService.Outcome outcome = redactExecuteService.executeWithOutcome(request);
+ ResponseEntity<Resource> response =
+ WebResponseUtils.pdfFileToWebResponse(outcome.file(), filename);
+ // Only a text-only plan can be judged by its match count.
+ return outcome.textOnly() ? withMatchCount(response, outcome.textMatches()) : response;
+ }
+
+ /** How many matches were redacted; callers can tell "nothing matched" from success. */
+ static final String MATCHES_HEADER = "X-Stirling-Redaction-Matches";
+
+ private static <T> ResponseEntity<T> withMatchCount(ResponseEntity<T> response, long matches) {
+ return ResponseEntity.status(response.getStatusCode())
+ .headers(
+ h -> {
+ h.addAll(response.getHeaders());
+ h.set(MATCHES_HEADER, Long.toString(matches));
+ })
+ .body(response.getBody());
}
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/RedactExecuteService.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/RedactExecuteService.java
index 1ab68cd1c0..28113203dc 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/RedactExecuteService.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/RedactExecuteService.java
@@ -10,6 +10,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
@@ -33,6 +34,7 @@ import stirling.software.SPDF.pdf.parser.PageImageLocator;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.ExceptionUtils.ToolFailedException;
+import stirling.software.common.util.RegexPatternUtils;
import stirling.software.common.util.TempFile;
@Service
@@ -44,10 +46,17 @@ class RedactExecuteService {
private final ManualRedactionService manualRedactionService;
private final TextRedactionService textRedactionService;
+ /** The redacted file and how many text matches it covered (text-only requests only). */
+ record Outcome(TempFile file, int textMatches, boolean textOnly) {}
+
TempFile execute(RedactExecuteRequest request) throws IOException {
+ return executeWithOutcome(request).file();
+ }
+
+ Outcome executeWithOutcome(RedactExecuteRequest request) throws IOException {
RedactStyle style = request.getStyle() != null ? request.getStyle() : new RedactStyle();
- List<String> textValues = orEmpty(request.getTextValues());
- List<String> regexPatterns = orEmpty(request.getRegexPatterns());
+ List<String> textValues = Arrays.asList(cleanStrings(request.getTextValues()));
+ List<String> regexPatterns = Arrays.asList(cleanStrings(request.getRegexPatterns()));
List<Integer> wipePages = orEmpty(request.getWipePages());
List<TextRange> ranges = orEmpty(request.getRanges());
List<ImageBox> imageBoxes = orEmpty(request.getImageBoxes());
@@ -72,6 +81,13 @@ class RedactExecuteService {
boolean convertToImage = imageFinalize || style.isConvertToImage();
boolean hasTextOps = !textValues.isEmpty() || !regexPatterns.isEmpty();
+ boolean textOnly =
+ hasTextOps
+ && wipePages.isEmpty()
+ && ranges.isEmpty()
+ && imageBoxes.isEmpty()
+ && request.getRedactImagePages() == null;
+ requireValidPatterns(regexPatterns);
log.info(
"[redact/execute] strategy={} textValues={} regexPatterns={} wipePages={} ranges={} imageBoxes={} imagePages={}",
@@ -90,6 +106,9 @@ class RedactExecuteService {
PDDocument document = null;
try {
document = pdfDocumentFactory.load(request.getFileInput());
+ int pageCount = document.getNumberOfPages();
+ requirePagesExist("wipePages", wipePages, pageCount);
+ requirePagesExist("redactImagePages", request.getRedactImagePages(), pageCount);
// Single-pass text scan: collect all text-based targets so we run the PDF
// stripper only once across the entire execute() call rather than once per target.
@@ -141,15 +160,17 @@ class RedactExecuteService {
applyAllImagesRedaction(document, request.getRedactImagePages(), style);
}
- return manualRedactionService.finalizeRedaction(
- document,
- foundTexts,
- style.getColor(),
- style.getPadding(),
- convertToImage,
- !needsOverlayOnly);
-
- } catch (ToolFailedException e) {
+ TempFile out =
+ manualRedactionService.finalizeRedaction(
+ document,
+ foundTexts,
+ style.getColor(),
+ style.getPadding(),
+ convertToImage,
+ !needsOverlayOnly);
+ return new Outcome(out, totalMatches, textOnly);
+
+ } catch (IllegalArgumentException | ToolFailedException e) {
throw e;
} catch (Exception e) {
log.error("Execute redaction failed: {}", e.getMessage(), e);
@@ -165,6 +186,41 @@ class RedactExecuteService {
}
}
+ /** A malformed pattern would otherwise match nothing and the request would "succeed". */
+ private static void requireValidPatterns(List<String> patterns) {
+ for (int i = 0; i < patterns.size(); i++) {
+ try {
+ RegexPatternUtils.getInstance().getPattern(patterns.get(i));
+ } catch (PatternSyntaxException e) {
+ // Logged by the exception handler, so the pattern itself stays out.
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.invalidArgument",
+ "Invalid argument: {0}",
+ "regexPatterns["
+ + i
+ + "] is not a valid regular expression ("
+ + e.getDescription()
+ + " near index "
+ + e.getIndex()
+ + ")");
+ }
+ }
+ }
+
+ private static void requirePagesExist(String field, List<Integer> pages, int pageCount) {
+ if (pages == null) {
+ return;
+ }
+ List<Integer> missing =
+ pages.stream().filter(p -> p == null || p < 1 || p > pageCount).toList();
+ if (!missing.isEmpty()) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.invalidArgument",
+ "Invalid argument: {0}",
+ field + " " + missing + ": pages are numbered 1 to " + pageCount);
+ }
+ }
+
// -----------------------------------------------------------------------
// Single-pass text scan (one stripper pass per execute() call)
// -----------------------------------------------------------------------
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/TimestampController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/TimestampController.java
index 2329ca2484..a96d3eff7e 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/TimestampController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/TimestampController.java
@@ -88,11 +88,15 @@ public class TimestampController {
@StandardPdfResponse
@ToolIO(produces = ToolFormat.PDF)
@Operation(
- summary = "Add RFC 3161 document timestamp to a PDF",
+ summary =
+ "Add an RFC 3161 document timestamp to a PDF. Run last: any later edit"
+ + " invalidates it",
description =
"Contacts a trusted Time Stamp Authority (TSA) server and embeds an RFC 3161"
+ " document timestamp into the PDF. Only a SHA-256 hash of the document is sent"
- + " to the TSA - the PDF itself never leaves the server.")
+ + " to the TSA - the PDF itself never leaves the server. Make the"
+ + " timestamp the last change to the file: any later edit invalidates"
+ + " it.")
public ResponseEntity<Resource> timestampPdf(@ModelAttribute TimestampPdfRequest request)
throws Exception {
MultipartFile inputFile = request.getFileInput();
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/WatermarkController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/WatermarkController.java
index 1fcfd18fa4..5688e6673b 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/WatermarkController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/WatermarkController.java
@@ -40,6 +40,7 @@ import stirling.software.common.enumeration.ResourceWeight;
import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.PdfUtils;
import stirling.software.common.util.RegexPatternUtils;
@@ -84,9 +85,21 @@ public class WatermarkController {
if (pdfFileName != null && (pdfFileName.contains("..") || pdfFileName.startsWith("/"))) {
throw new SecurityException("Invalid file path in pdfFile");
}
- String watermarkType = request.getWatermarkType();
String watermarkText = request.getWatermarkText();
MultipartFile watermarkImage = request.getWatermarkImage();
+ String watermarkType = resolveWatermarkType(request.getWatermarkType(), watermarkImage);
+ if ("text".equalsIgnoreCase(watermarkType)
+ && (watermarkText == null || watermarkText.isBlank())) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.watermark.text.required",
+ "watermarkText must be provided when watermarkType is 'text'");
+ }
+ if ("image".equalsIgnoreCase(watermarkType)
+ && (watermarkImage == null || watermarkImage.isEmpty())) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.watermark.image.required",
+ "watermarkImage must be provided when watermarkType is 'image'");
+ }
if (watermarkImage != null) {
String watermarkImageFileName = watermarkImage.getOriginalFilename();
if (watermarkImageFileName != null
@@ -173,6 +186,19 @@ public class WatermarkController {
}
}
+ private static String resolveWatermarkType(String watermarkType, MultipartFile image) {
+ if (watermarkType == null || watermarkType.isBlank()) {
+ return image != null && !image.isEmpty() ? "image" : "text";
+ }
+ if (!"text".equalsIgnoreCase(watermarkType) && !"image".equalsIgnoreCase(watermarkType)) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.watermark.type.invalid",
+ "Invalid watermarkType ''{0}'': must be ''text'' or ''image''",
+ watermarkType);
+ }
+ return watermarkType;
+ }
+
/**
* Load the watermark font once for the whole document. {@link PDType0Font#load} embeds a font
* object into {@code document} on every call, so calling this per page holds one full copy of
@@ -282,6 +308,12 @@ public class WatermarkController {
// Load the watermark image
BufferedImage image = ImageIO.read(watermarkImage.getInputStream());
+ if (image == null) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ ExceptionUtils.ErrorCode.INVALID_ARGUMENT,
+ "watermarkImage",
+ "must be a supported image");
+ }
// Compute width based on original aspect ratio
float aspectRatio = (float) image.getWidth() / (float) image.getHeight();
diff --git a/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java b/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
index c80493de8a..700785bcab 100644
--- a/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
+++ b/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
@@ -624,6 +624,10 @@ public class GlobalExceptionHandler {
getLocalizedMessage(
"error.validation.title", ErrorTitles.REQUEST_VALIDATION_FAILED_DEFAULT);
String detail = getLocalizedMessage("error.validation.detail", "Validation failed");
+ // Clients that read only the detail (MCP, API callers) still learn which fields failed.
+ if (!errors.isEmpty()) {
+ detail = detail + ": " + String.join("; ", errors);
+ }
ProblemDetail problemDetail =
createBaseProblemDetail(HttpStatus.BAD_REQUEST, detail, request);
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithImageFormatRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithImageFormatRequest.java
index c2e8d2658a..bb809ed51a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithImageFormatRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithImageFormatRequest.java
@@ -16,5 +16,5 @@ public class PDFWithImageFormatRequest extends PDFFile {
allowableValues = {"png", "jpeg", "gif"},
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "png")
- private String format;
+ private String format = "png";
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java b/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java
index 062c890fc8..cc01270601 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java
@@ -24,12 +24,14 @@ public class PDFWithPageNums extends PDFFile {
+ " format 'an+b' where 'a' is the multiplier of the page number 'n', and 'b' is a"
+ " constant (e.g., '2n+1', '3n', '6n-5')",
defaultValue = "all",
- requiredMode = RequiredMode.REQUIRED)
- private String pageNumbers;
+ requiredMode = RequiredMode.NOT_REQUIRED)
+ private String pageNumbers = "all";
@Hidden
public List<Integer> getPageNumbersList(PDDocument doc, boolean oneBased) {
int pageCount = doc.getNumberOfPages();
- return GeneralUtils.parsePageList(pageNumbers, pageCount, oneBased);
+ String pages = pageNumbers == null || pageNumbers.isBlank() ? "all" : pageNumbers;
+ GeneralUtils.requireValidPageSelection(pages, pageCount);
+ return GeneralUtils.parsePageList(pages, pageCount, oneBased);
}
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageSize.java b/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageSize.java
index a8095ac759..269a709da0 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageSize.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/PDFWithPageSize.java
@@ -14,10 +14,10 @@ public class PDFWithPageSize extends PDFFile {
@Schema(
description =
"The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER,"
- + " LEGAL, KEEP.",
- requiredMode = Schema.RequiredMode.REQUIRED,
+ + " LEGAL, KEEP. KEEP keeps each page's own size.",
+ defaultValue = "KEEP",
allowableValues = {"A0", "A1", "A2", "A3", "A4", "A5", "A6", "LETTER", "LEGAL", "KEEP"})
- private String pageSize;
+ private String pageSize = "KEEP";
@Schema(
description =
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPagesRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPagesRequest.java
index 0ae1f75538..6dce34209c 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPagesRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPagesRequest.java
@@ -28,11 +28,12 @@ public class SplitPagesRequest extends PDFFile {
+ " `\"2n+1\"`, `\"3n\"`, `\"6n-5\"`.",
defaultValue = "all",
requiredMode = RequiredMode.REQUIRED)
- private String pageNumbers;
+ private String pageNumbers = "all";
@Hidden
public List<Integer> getPageNumbersList(PDDocument doc, boolean oneBased) {
int pageCount = doc.getNumberOfPages();
+ GeneralUtils.requireValidPageSelection(pageNumbers, pageCount);
return GeneralUtils.parsePageList(pageNumbers, pageCount, oneBased);
}
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPdfByChaptersRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPdfByChaptersRequest.java
index 390a2898cd..9a6c70b6ec 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPdfByChaptersRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPdfByChaptersRequest.java
@@ -7,25 +7,21 @@ import lombok.EqualsAndHashCode;
import stirling.software.common.model.api.PDFFile;
+/** Optional fields default to what the split-by-chapters tool in the web UI sends. */
@Data
@EqualsAndHashCode(callSuper = false)
public class SplitPdfByChaptersRequest extends PDFFile {
- @Schema(
- description = "Whether to include Metadata or not",
- defaultValue = "false",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean includeMetadata;
+ @Schema(description = "Whether to include Metadata or not", defaultValue = "false")
+ private Boolean includeMetadata = false;
- @Schema(
- description = "Whether to allow duplicates or not",
- defaultValue = "false",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean allowDuplicates;
+ @Schema(description = "Whether to allow duplicates or not", defaultValue = "false")
+ private Boolean allowDuplicates = false;
@Schema(
- description = "Maximum bookmark level required",
+ description =
+ "Maximum bookmark nesting level to split on: 0 splits on top-level bookmarks"
+ + " only, 1 also on their children, and so on",
minimum = "0",
- defaultValue = "0",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private Integer bookmarkLevel;
+ defaultValue = "1")
+ private Integer bookmarkLevel = 1;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPdfBySectionsRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPdfBySectionsRequest.java
index d1b988491e..9a89c81305 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPdfBySectionsRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/SplitPdfBySectionsRequest.java
@@ -15,9 +15,12 @@ import stirling.software.common.model.api.PDFFile;
@EqualsAndHashCode(callSuper = true)
public class SplitPdfBySectionsRequest extends PDFFile {
@Schema(
- description = "Pages to be split by section",
- defaultValue = "SPLIT_ALL",
- requiredMode = Schema.RequiredMode.REQUIRED)
+ description =
+ "Pages to split when splitMode is CUSTOM (required in that mode, ignored"
+ + " otherwise). Supports ranges (e.g. '1,3,5-9'), 'all', or functions"
+ + " like '2n+1'.",
+ example = "1,3,5-9",
+ requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String pageNumbers;
@Schema(
@@ -47,11 +50,11 @@ public class SplitPdfBySectionsRequest extends PDFFile {
requiredMode = Schema.RequiredMode.REQUIRED)
@Min(value = 0, message = "Vertical divisions must be non-negative")
@Max(value = 50, message = "Vertical divisions must not exceed 50")
- private int verticalDivisions;
+ private int verticalDivisions = 1;
@Schema(
description = "Merge the split documents into a single PDF",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean merge;
+ private Boolean merge = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequest.java
index 9461bbb155..636cb4646a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequest.java
@@ -27,21 +27,21 @@ public class ConvertEbookToPdfRequest {
allowableValues = {"true", "false"},
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "false")
- private Boolean embedAllFonts;
+ private Boolean embedAllFonts = false;
@Schema(
description = "Add a generated table of contents to the resulting PDF",
requiredMode = Schema.RequiredMode.REQUIRED,
allowableValues = {"true", "false"},
defaultValue = "false")
- private Boolean includeTableOfContents;
+ private Boolean includeTableOfContents = false;
@Schema(
description = "Add page numbers to the generated PDF",
requiredMode = Schema.RequiredMode.REQUIRED,
allowableValues = {"true", "false"},
defaultValue = "false")
- private Boolean includePageNumbers;
+ private Boolean includePageNumbers = false;
@Schema(
description =
@@ -49,5 +49,5 @@ public class ConvertEbookToPdfRequest {
+ " eInk devices)",
allowableValues = {"true", "false"},
defaultValue = "false")
- private Boolean optimizeForEbook;
+ private Boolean optimizeForEbook = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertToImageRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertToImageRequest.java
index 5e144b8d4a..188e68f982 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertToImageRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertToImageRequest.java
@@ -18,7 +18,7 @@ public class ConvertToImageRequest extends PDFWithPageNums {
defaultValue = "png",
allowableValues = {"png", "jpeg", "jpg", "gif", "webp"},
requiredMode = Schema.RequiredMode.REQUIRED)
- private String imageFormat;
+ private String imageFormat = "png";
@Schema(
description =
@@ -27,14 +27,14 @@ public class ConvertToImageRequest extends PDFWithPageNums {
defaultValue = "multiple",
allowableValues = {"single", "multiple"},
requiredMode = Schema.RequiredMode.REQUIRED)
- private String singleOrMultiple;
+ private String singleOrMultiple = "multiple";
@Schema(
description = "The color type of the output image(s)",
defaultValue = "color",
allowableValues = {"color", "greyscale", "blackwhite"},
requiredMode = Schema.RequiredMode.REQUIRED)
- private String colorType;
+ private String colorType = "color";
@Schema(
description = "The DPI (dots per inch) for the output image(s)",
@@ -45,5 +45,5 @@ public class ConvertToImageRequest extends PDFWithPageNums {
@Schema(
description = "Include annotations such as comments in the output image(s)",
defaultValue = "false")
- private Boolean includeAnnotations;
+ private Boolean includeAnnotations = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertToPdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertToPdfRequest.java
index 9b2fb90ad4..2588758453 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertToPdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertToPdfRequest.java
@@ -26,18 +26,18 @@ public class ConvertToPdfRequest {
"fitDocumentToPage",
"maintainAspectRatio"
})
- private String fitOption;
+ private String fitOption = "fillPage";
@Schema(
description = "The color type of the output image(s)",
defaultValue = "color",
requiredMode = Schema.RequiredMode.REQUIRED,
allowableValues = {"color", "greyscale", "blackwhite"})
- private String colorType;
+ private String colorType = "color";
@Schema(
description = "Whether to automatically rotate the images to better fit the PDF page",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "false")
- private Boolean autoRotate;
+ private Boolean autoRotate = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToPdfARequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToPdfARequest.java
index 921663912b..77e4cb9816 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToPdfARequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToPdfARequest.java
@@ -25,7 +25,7 @@ public class PdfToPdfARequest extends PDFFile {
"Also declare PDF/UA accessibility alongside PDF/A. Only applies to the level A"
+ " formats, and the claim is written only if it validates.",
defaultValue = "false")
- private Boolean pdfUa;
+ private Boolean pdfUa = false;
@Schema(
description =
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToVideoRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToVideoRequest.java
index 4226646117..06374a8a5a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToVideoRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToVideoRequest.java
@@ -46,8 +46,7 @@ public class PdfToVideoRequest extends PDFFile {
private Float opacity = 0.1f;
@Schema(
- description = "Watermark text to overlay on the video",
- example = "Stirling Software",
- defaultValue = "Stirling Software")
+ description = "Watermark text to overlay on the video. Omit for no watermark.",
+ example = "Stirling Software")
private String watermarkText;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfVectorExportRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfVectorExportRequest.java
index 398d626739..97c79bd021 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfVectorExportRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfVectorExportRequest.java
@@ -25,5 +25,5 @@ public class PdfVectorExportRequest extends PDFFile {
requiredMode = Schema.RequiredMode.REQUIRED,
allowableValues = {"true", "false"},
defaultValue = "false")
- private Boolean prepress;
+ private Boolean prepress = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/SvgToPdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/SvgToPdfRequest.java
index e7c9a4065f..50baf8405c 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/SvgToPdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/SvgToPdfRequest.java
@@ -25,5 +25,5 @@ public class SvgToPdfRequest {
+ "or create separate PDF files for each SVG.",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "false")
- private Boolean combineIntoSinglePdf;
+ private Boolean combineIntoSinglePdf = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/filter/ContainsTextRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/filter/ContainsTextRequest.java
index 0435e58353..cd58964afe 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/filter/ContainsTextRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/filter/ContainsTextRequest.java
@@ -13,7 +13,7 @@ public class ContainsTextRequest extends PDFWithPageNums {
@Schema(
description = "The text to check for",
- defaultValue = "text",
+ example = "Confidential",
requiredMode = Schema.RequiredMode.REQUIRED)
private String text;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/filter/PageSizeRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/filter/PageSizeRequest.java
index 2fa74f0406..ba9bb358bd 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/filter/PageSizeRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/filter/PageSizeRequest.java
@@ -16,5 +16,5 @@ public class PageSizeRequest extends PDFComparison {
allowableValues = {"A0", "A1", "A2", "A3", "A4", "A5", "A6", "LETTER", "LEGAL"},
defaultValue = "A4",
requiredMode = Schema.RequiredMode.REQUIRED)
- private String standardPageSize;
+ private String standardPageSize = "A4";
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/general/CropPdfForm.java b/app/core/src/main/java/stirling/software/SPDF/model/api/general/CropPdfForm.java
index 4ff2eed2ba..679095d3a4 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/general/CropPdfForm.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/general/CropPdfForm.java
@@ -23,15 +23,14 @@ public class CropPdfForm extends PDFWithPageNums {
@Hidden
public List<Integer> getPageNumbersList(PDDocument doc, boolean oneBased) {
String pageNumbers = getPageNumbers();
+ GeneralUtils.requireValidPageSelection(pageNumbers, doc.getNumberOfPages());
return GeneralUtils.parsePageList(
(pageNumbers == null || pageNumbers.isBlank()) ? "all" : pageNumbers,
doc.getNumberOfPages(),
oneBased);
}
- // The base model marks pageNumbers required, but this endpoint treats an
- // omitted or blank value as "all" (see above): advertise it as optional so
- // generated clients do not fail local validation for a legal request.
+ // Crop-specific wording; omitted or blank still means every page.
@Override
@Schema(
description =
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/general/MergeMultiplePagesRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/general/MergeMultiplePagesRequest.java
index 27b9c539fd..e0751d1a85 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/general/MergeMultiplePagesRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/general/MergeMultiplePagesRequest.java
@@ -18,7 +18,7 @@ public class MergeMultiplePagesRequest extends PDFFile {
type = "string",
defaultValue = "DEFAULT",
allowableValues = {"DEFAULT", "CUSTOM"})
- private String mode;
+ private String mode = "DEFAULT";
@Schema(
description = "The number of pages to fit onto a single sheet in the output PDF.",
@@ -32,7 +32,7 @@ public class MergeMultiplePagesRequest extends PDFFile {
type = "string",
defaultValue = "BY_ROWS",
allowableValues = {"BY_ROWS", "BY_COLUMNS"})
- private String arrangement;
+ private String arrangement = "BY_ROWS";
@Schema(
description =
@@ -40,7 +40,7 @@ public class MergeMultiplePagesRequest extends PDFFile {
type = "string",
defaultValue = "LTR",
allowableValues = {"LTR", "RTL"})
- private String readingDirection;
+ private String readingDirection = "LTR";
@Schema(
description = "Number of rows",
@@ -49,7 +49,7 @@ public class MergeMultiplePagesRequest extends PDFFile {
maximum = "300",
minimum = "1",
example = "3")
- private int rows;
+ private int rows = 1;
@Schema(
description = "Number of columns",
@@ -58,14 +58,14 @@ public class MergeMultiplePagesRequest extends PDFFile {
maximum = "300",
minimum = "1",
example = "2")
- private int cols;
+ private int cols = 2;
@Schema(
description = "The orientation of the output PDF pages",
type = "string",
defaultValue = "PORTRAIT",
allowableValues = {"PORTRAIT", "LANDSCAPE"})
- private String orientation;
+ private String orientation = "PORTRAIT";
@Schema(
description = "Inner margin (in points) to apply around each page when merging",
@@ -113,7 +113,7 @@ public class MergeMultiplePagesRequest extends PDFFile {
defaultValue = "1",
minimum = "0",
example = "2")
- private int borderWidth;
+ private int borderWidth = 1;
@Schema(description = "Boolean for if you wish to add border around the pages")
private Boolean addBorder;
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/general/MergePdfsRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/general/MergePdfsRequest.java
index 2851f018f6..1a5a660b68 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/general/MergePdfsRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/general/MergePdfsRequest.java
@@ -31,7 +31,7 @@ public class MergePdfsRequest extends MultiplePDFFiles {
+ " final merged document.",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "true")
- private Boolean removeCertSign;
+ private Boolean removeCertSign = true;
@Schema(
description =
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/general/ScalePagesRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/general/ScalePagesRequest.java
index 653697f4e7..c5f9018e8e 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/general/ScalePagesRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/general/ScalePagesRequest.java
@@ -14,9 +14,8 @@ public class ScalePagesRequest extends PDFWithPageSize {
@Schema(
minimum = "0",
defaultValue = "1",
- requiredMode = Schema.RequiredMode.REQUIRED,
description =
"The scale of the content on the pages of the output PDF. Acceptable values are"
+ " floats.")
- private float scaleFactor;
+ private float scaleFactor = 1f;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/general/SplitPdfBySizeOrCountRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/general/SplitPdfBySizeOrCountRequest.java
index 0dd5997813..459b27dbae 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/general/SplitPdfBySizeOrCountRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/general/SplitPdfBySizeOrCountRequest.java
@@ -23,5 +23,5 @@ public class SplitPdfBySizeOrCountRequest extends PDFFile {
"Value for split: size in MB (e.g., '10MB') or number of pages (e.g., '5')",
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
defaultValue = "10MB")
- private String splitValue;
+ private String splitValue = "10MB";
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddPageNumbersRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddPageNumbersRequest.java
index 46006c8dcc..88a7c27959 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddPageNumbersRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddPageNumbersRequest.java
@@ -17,14 +17,14 @@ public class AddPageNumbersRequest extends PDFWithPageNums {
allowableValues = {"small", "medium", "large", "x-large"},
defaultValue = "medium",
requiredMode = RequiredMode.NOT_REQUIRED)
- private String customMargin;
+ private String customMargin = "medium";
@Schema(
description = "Font size for page numbers",
minimum = "1",
defaultValue = "12",
- requiredMode = RequiredMode.REQUIRED)
- private float fontSize;
+ requiredMode = RequiredMode.NOT_REQUIRED)
+ private float fontSize = 12;
@Schema(
description = "Font type for page numbers",
@@ -37,7 +37,7 @@ public class AddPageNumbersRequest extends PDFWithPageNums {
example = "#000000",
defaultValue = "#000000",
requiredMode = RequiredMode.NOT_REQUIRED)
- private String fontColor;
+ private String fontColor = "#000000";
@Schema(
description =
@@ -61,14 +61,14 @@ public class AddPageNumbersRequest extends PDFWithPageNums {
description = "Starting number for page numbering",
minimum = "1",
defaultValue = "1",
- requiredMode = RequiredMode.REQUIRED)
- private int startingNumber;
+ requiredMode = RequiredMode.NOT_REQUIRED)
+ private int startingNumber = 1;
@Schema(
description = "Which pages to number (e.g. '1,3-5,7' or 'all')",
defaultValue = "all",
requiredMode = RequiredMode.NOT_REQUIRED)
- private String pagesToNumber;
+ private String pagesToNumber = "all";
@Schema(
description =
@@ -77,5 +77,5 @@ public class AddPageNumbersRequest extends PDFWithPageNums {
example = "Page {n} of {total}",
defaultValue = "{n}",
requiredMode = RequiredMode.NOT_REQUIRED)
- private String customText;
+ private String customText = "{n}";
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddStampRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddStampRequest.java
index 14cefaeefd..bc0029f3db 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddStampRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddStampRequest.java
@@ -9,22 +9,25 @@ import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFWithPageNums;
+/** Optional fields default to what the add-stamp tool in the web UI sends. */
@Data
@EqualsAndHashCode(callSuper = true)
public class AddStampRequest extends PDFWithPageNums {
@Schema(
- description = "The stamp type (text, image or qr)",
- allowableValues = {"text", "image", "qr"},
- requiredMode = Schema.RequiredMode.REQUIRED)
+ description =
+ "The stamp type (text, image or qr). When omitted, image is used if"
+ + " stampImage is supplied, otherwise text.",
+ allowableValues = {"text", "image", "qr"})
private String stampType;
@Schema(
- description = "The stamp text, or the QR code content when the stamp type is qr",
- defaultValue = "Stirling Software")
+ description =
+ "The stamp text, or the QR code content when stampType is qr; required when"
+ + " stampType is text or qr")
private String stampText;
- @Schema(description = "The stamp image")
+ @Schema(description = "The stamp image, required when stampType is image")
private MultipartFile stampImage;
@Schema(
@@ -35,21 +38,14 @@ public class AddStampRequest extends PDFWithPageNums {
@Schema(
description = "The font size of the stamp text and image in points.",
- defaultValue = "40",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private float fontSize;
+ defaultValue = "40")
+ private float fontSize = 40f;
- @Schema(
- description = "The rotation of the stamp in degrees",
- defaultValue = "0",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private float rotation;
+ @Schema(description = "The rotation of the stamp in degrees", defaultValue = "0")
+ private float rotation = 0f;
- @Schema(
- description = "The opacity of the stamp (0.0 - 1.0)",
- defaultValue = "0.5",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private float opacity;
+ @Schema(description = "The opacity of the stamp (0.0 - 1.0)", defaultValue = "0.5")
+ private float opacity = 0.5f;
@Schema(
description =
@@ -57,33 +53,29 @@ public class AddStampRequest extends PDFWithPageNums {
+ " 3: bottom-right, 4: middle-left, 5: middle-center, 6: middle-right,"
+ " 7: top-left, 8: top-center, 9: top-right)",
allowableValues = {"1", "2", "3", "4", "5", "6", "7", "8", "9"},
- defaultValue = "8",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private int position;
+ defaultValue = "5")
+ private int position = 5;
@Schema(
description =
"Override X coordinate for stamp placement. If set, it will override the"
+ " position-based calculation. Negative value means no override.",
- defaultValue = "-1",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private float overrideX; // Default to -1 indicating no override
+ defaultValue = "-1")
+ private float overrideX = -1f;
@Schema(
description =
"Override Y coordinate for stamp placement. If set, it will override the"
+ " position-based calculation. Negative value means no override.",
- defaultValue = "-1",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private float overrideY; // Default to -1 indicating no override
+ defaultValue = "-1")
+ private float overrideY = -1f;
@Schema(
description = "Specifies the margin size for the stamp.",
allowableValues = {"small", "medium", "large", "x-large"},
- defaultValue = "medium",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private String customMargin;
+ defaultValue = "medium")
+ private String customMargin = "medium";
@Schema(description = "The color of the stamp text", defaultValue = "#d3d3d3")
- private String customColor;
+ private String customColor = "#d3d3d3";
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoSplitPdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoSplitPdfRequest.java
index 0ba3ad8bd7..2c13dfcaea 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoSplitPdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AutoSplitPdfRequest.java
@@ -16,5 +16,5 @@ public class AutoSplitPdfRequest extends PDFFile {
"Flag indicating if the duplex mode is active, where the page after the divider also gets removed.",
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
defaultValue = "false")
- private Boolean duplexMode;
+ private Boolean duplexMode = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/CreatePortfolioRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/CreatePortfolioRequest.java
index c54192e55b..fc4a439204 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/CreatePortfolioRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/CreatePortfolioRequest.java
@@ -21,5 +21,5 @@ public class CreatePortfolioRequest {
description = "Title shown on the portfolio cover page.",
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
defaultValue = "PDF Portfolio")
- private String coverTitle;
+ private String coverTitle = "PDF Portfolio";
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractHeaderRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractHeaderRequest.java
index cbb51a3903..190209b22d 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractHeaderRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractHeaderRequest.java
@@ -16,5 +16,5 @@ public class ExtractHeaderRequest extends PDFFile {
"Flag indicating whether to use the first text as a fallback if no suitable title is found. Defaults to false.",
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
defaultValue = "false")
- private Boolean useFirstTextAsFallback;
+ private Boolean useFirstTextAsFallback = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractImageScansRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractImageScansRequest.java
index 6345d44892..99c40a4769 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractImageScansRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ExtractImageScansRequest.java
@@ -19,30 +19,30 @@ public class ExtractImageScansRequest {
@Schema(
description = "The angle threshold for the image scan extraction",
requiredMode = Schema.RequiredMode.REQUIRED,
- defaultValue = "5")
- private int angleThreshold;
+ defaultValue = "10")
+ private int angleThreshold = 10;
@Schema(
description = "The tolerance for the image scan extraction",
requiredMode = Schema.RequiredMode.REQUIRED,
- defaultValue = "20")
- private int tolerance;
+ defaultValue = "30")
+ private int tolerance = 30;
@Schema(
description = "The minimum area for the image scan extraction",
requiredMode = Schema.RequiredMode.REQUIRED,
- defaultValue = "8000")
- private int minArea;
+ defaultValue = "10000")
+ private int minArea = 10000;
@Schema(
description = "The minimum contour area for the image scan extraction",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "500")
- private int minContourArea;
+ private int minContourArea = 500;
@Schema(
description = "The border size for the image scan extraction",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "1")
- private int borderSize;
+ private int borderSize = 1;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/FlattenRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/FlattenRequest.java
index b53653a36f..3be83ad657 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/FlattenRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/FlattenRequest.java
@@ -17,7 +17,7 @@ public class FlattenRequest extends PDFFile {
+ " image)",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "false")
- private Boolean flattenOnlyForms;
+ private Boolean flattenOnlyForms = false;
@Schema(
description = "Optional DPI for page rendering when flattening the full document.",
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/MetadataRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/MetadataRequest.java
index 63b2671962..2bc6e85e07 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/MetadataRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/MetadataRequest.java
@@ -17,61 +17,66 @@ public class MetadataRequest extends PDFFile {
description = "Delete all metadata if set to true",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean deleteAll;
+ private Boolean deleteAll = false;
@Schema(
- description = "The author of the document",
- defaultValue = "author",
+ description = "The author of the document. Omit to remove it.",
+ example = "author",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String author;
@Schema(
- description = "The creation date of the document (format: yyyy/MM/dd HH:mm:ss)",
+ description =
+ "The creation date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to"
+ + " remove it.",
pattern = "yyyy/MM/dd HH:mm:ss",
- defaultValue = "2023/10/01 12:00:00",
+ example = "2023/10/01 12:00:00",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String creationDate;
@Schema(
- description = "The creator of the document",
- defaultValue = "creator",
+ description = "The creator of the document. Omit to remove it.",
+ example = "creator",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String creator;
@Schema(
- description = "The keywords for the document",
- defaultValue = "keywords",
+ description = "The keywords for the document. Omit to remove it.",
+ example = "keywords",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String keywords;
@Schema(
- description = "The modification date of the document (format: yyyy/MM/dd HH:mm:ss)",
+ description =
+ "The modification date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to"
+ + " remove it.",
pattern = "yyyy/MM/dd HH:mm:ss",
- defaultValue = "2023/10/01 12:00:00",
+ example = "2023/10/01 12:00:00",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String modificationDate;
@Schema(
- description = "The producer of the document",
- defaultValue = "producer",
+ description = "The producer of the document. Omit to remove it.",
+ example = "producer",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String producer;
@Schema(
- description = "The subject of the document",
- defaultValue = "subject",
+ description = "The subject of the document. Omit to remove it.",
+ example = "subject",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String subject;
@Schema(
- description = "The title of the document",
- defaultValue = "title",
+ description = "The title of the document. Omit to remove it.",
+ example = "title",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String title;
@Schema(
- description = "The trapped status of the document",
- defaultValue = "False",
+ description =
+ "The trapped status of the document. Omit to remove it, which readers treat"
+ + " as Unknown.",
allowableValues = {"True", "False", "Unknown"},
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String trapped;
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/OptimizePdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/OptimizePdfRequest.java
index d6e5c7021d..fdfda25510 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/OptimizePdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/OptimizePdfRequest.java
@@ -21,9 +21,12 @@ public class OptimizePdfRequest extends PDFFile {
private Integer optimizeLevel = 5;
@Schema(
- description = "The expected output size, e.g. '100MB', '25KB', etc.",
- defaultValue = "25KB",
- requiredMode = Schema.RequiredMode.REQUIRED)
+ description =
+ "Target output size, e.g. '100MB' or '25KB'. When set, the optimization"
+ + " level is chosen automatically to reach it; omit to compress at"
+ + " optimizeLevel.",
+ example = "25KB",
+ requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String expectedOutputSize;
@Schema(
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/OverlayImageRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/OverlayImageRequest.java
index fd1a904baf..007ebb1ff7 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/OverlayImageRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/OverlayImageRequest.java
@@ -38,5 +38,5 @@ public class OverlayImageRequest extends PDFFile {
description = "Whether to overlay the image onto every page of the PDF.",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "false")
- private Boolean everyPage;
+ private Boolean everyPage = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ProcessPdfWithOcrRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ProcessPdfWithOcrRequest.java
index daa6930412..49cbdfe7e2 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ProcessPdfWithOcrRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ProcessPdfWithOcrRequest.java
@@ -1,5 +1,6 @@
package stirling.software.SPDF.model.api.misc;
+import java.util.ArrayList;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -15,40 +16,45 @@ public class ProcessPdfWithOcrRequest extends PDFFile {
@Schema(
description = "List of languages to use in OCR processing, e.g., 'eng', 'deu'",
- requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "[\"eng\"]")
- private List<String> languages;
+ private List<String> languages = new ArrayList<>(List.of("eng"));
- @Schema(description = "Include OCR text in a sidecar text file if set to true")
+ @Schema(
+ description = "Include OCR text in a sidecar text file if set to true",
+ defaultValue = "false")
private boolean sidecar;
- @Schema(description = "Deskew the input file if set to true")
+ @Schema(description = "Deskew the input file if set to true", defaultValue = "false")
private boolean deskew;
@Schema(
description =
- "Auto-correct page orientation (90/180/270) using Tesseract OSD if set to true")
+ "Auto-correct page orientation (90/180/270) using Tesseract OSD if set to true",
+ defaultValue = "false")
private boolean rotatePages;
- @Schema(description = "Clean the input file if set to true")
+ @Schema(description = "Clean the input file if set to true", defaultValue = "false")
private boolean clean;
- @Schema(description = "Clean the final output if set to true")
+ @Schema(description = "Clean the final output if set to true", defaultValue = "false")
private boolean cleanFinal;
@Schema(
- description = "Specify the OCR type, e.g., 'skip-text', 'force-ocr', or 'Normal'",
- requiredMode = Schema.RequiredMode.REQUIRED,
- allowableValues = {"skip-text", "force-ocr", "Normal"})
- private String ocrType;
+ description =
+ "How to treat pages that already contain text: 'skip-text' OCRs only pages"
+ + " without text, 'force-ocr' rasterises and OCRs every page.",
+ allowableValues = {"skip-text", "force-ocr", "Normal"},
+ defaultValue = "skip-text")
+ private String ocrType = "skip-text";
@Schema(
description = "Specify the OCR render type, either 'hocr' or 'sandwich'",
- requiredMode = Schema.RequiredMode.REQUIRED,
allowableValues = {"hocr", "sandwich"},
defaultValue = "hocr")
private String ocrRenderType = "hocr";
- @Schema(description = "Remove images from the output PDF if set to true")
+ @Schema(
+ description = "Remove images from the output PDF if set to true",
+ defaultValue = "false")
private boolean removeImagesAfter;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/RemoveBlankPagesRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/RemoveBlankPagesRequest.java
index cef00dcc0a..c115d32d02 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/RemoveBlankPagesRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/RemoveBlankPagesRequest.java
@@ -17,7 +17,7 @@ public class RemoveBlankPagesRequest extends PDFFile {
minimum = "0",
maximum = "255",
defaultValue = "10")
- private int threshold;
+ private int threshold = 10;
@Schema(
description = "The percentage of white color on a page to consider it as blank",
@@ -25,5 +25,5 @@ public class RemoveBlankPagesRequest extends PDFFile {
minimum = "0.1",
maximum = "100",
defaultValue = "99.9")
- private float whitePercent;
+ private float whitePercent = 99.9f;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ReplaceAndInvertColorRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ReplaceAndInvertColorRequest.java
index 02bbcd6ad5..c010551cc9 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ReplaceAndInvertColorRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/ReplaceAndInvertColorRequest.java
@@ -23,7 +23,7 @@ public class ReplaceAndInvertColorRequest extends PDFFile {
"FULL_INVERSION",
"COLOR_SPACE_CONVERSION"
})
- private ReplaceAndInvert replaceAndInvertOption;
+ private ReplaceAndInvert replaceAndInvertOption = ReplaceAndInvert.HIGH_CONTRAST_COLOR;
@Schema(
description =
@@ -36,7 +36,8 @@ public class ReplaceAndInvertColorRequest extends PDFFile {
"YELLOW_TEXT_ON_BLACK",
"GREEN_TEXT_ON_BLACK"
})
- private HighContrastColorCombination highContrastColorCombination;
+ private HighContrastColorCombination highContrastColorCombination =
+ HighContrastColorCombination.WHITE_TEXT_ON_BLACK;
@Schema(
description =
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddPasswordRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddPasswordRequest.java
index 07008869c6..39008d1de2 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddPasswordRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddPasswordRequest.java
@@ -50,30 +50,30 @@ public class AddPasswordRequest extends PDFFile {
private int keyLength = 256;
@Schema(description = "Whether document assembly is prevented", defaultValue = "false")
- private Boolean preventAssembly;
+ private Boolean preventAssembly = false;
@Schema(description = "Whether content extraction is prevented", defaultValue = "false")
- private Boolean preventExtractContent;
+ private Boolean preventExtractContent = false;
@Schema(
description = "Whether content extraction for accessibility is prevented",
defaultValue = "false")
- private Boolean preventExtractForAccessibility;
+ private Boolean preventExtractForAccessibility = false;
@Schema(description = "Whether form filling is prevented", defaultValue = "false")
- private Boolean preventFillInForm;
+ private Boolean preventFillInForm = false;
@Schema(description = "Whether document modification is prevented", defaultValue = "false")
- private Boolean preventModify;
+ private Boolean preventModify = false;
@Schema(
description = "Whether modification of annotations is prevented",
defaultValue = "false")
- private Boolean preventModifyAnnotations;
+ private Boolean preventModifyAnnotations = false;
@Schema(description = "Whether printing of the document is prevented", defaultValue = "false")
- private Boolean preventPrinting;
+ private Boolean preventPrinting = false;
@Schema(description = "Whether faithful printing is prevented", defaultValue = "false")
- private Boolean preventPrintingFaithful;
+ private Boolean preventPrintingFaithful = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddWatermarkRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddWatermarkRequest.java
index b03d1b48fe..30cb2fa31a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddWatermarkRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddWatermarkRequest.java
@@ -12,52 +12,51 @@ import lombok.EqualsAndHashCode;
import stirling.software.common.model.api.PDFFile;
+/** Optional fields default to what the add-watermark tool in the web UI sends. */
@Data
@EqualsAndHashCode(callSuper = true)
public class AddWatermarkRequest extends PDFFile {
@Schema(
- description = "The watermark type (text or image)",
- allowableValues = {"text", "image"},
- requiredMode = Schema.RequiredMode.REQUIRED)
+ description =
+ "The watermark type (text or image). When omitted, image is used if"
+ + " watermarkImage is supplied, otherwise text.",
+ allowableValues = {"text", "image"})
private String watermarkType;
- @Schema(description = "The watermark text", defaultValue = "Stirling Software")
+ @Schema(description = "The watermark text, required when watermarkType is text")
private String watermarkText;
- @Schema(description = "The watermark image")
+ @Schema(description = "The watermark image, required when watermarkType is image")
private MultipartFile watermarkImage;
@Schema(
description = "The selected alphabet",
allowableValues = {"roman", "arabic", "japanese", "korean", "chinese", "thai"},
defaultValue = "roman")
- private String alphabet;
+ private String alphabet = "roman";
- @Schema(description = "The font size of the watermark text", defaultValue = "30")
+ @Schema(description = "The font size of the watermark text", defaultValue = "12")
@DecimalMin(value = "1.0", message = "Font size must be at least 1.0")
- private float fontSize;
+ private float fontSize = 12f;
@Schema(description = "The rotation of the watermark in degrees", defaultValue = "0")
- private float rotation;
+ private float rotation = 0f;
@Schema(description = "The opacity of the watermark (0.0 - 1.0)", defaultValue = "0.5")
- private float opacity;
+ private float opacity = 0.5f;
@Schema(description = "The width spacer between watermark elements", defaultValue = "50")
@Min(value = 0, message = "Width spacer must be non-negative")
- private int widthSpacer;
+ private int widthSpacer = 50;
@Schema(description = "The height spacer between watermark elements", defaultValue = "50")
@Min(value = 0, message = "Height spacer must be non-negative")
- private int heightSpacer;
+ private int heightSpacer = 50;
@Schema(description = "The color for watermark", defaultValue = "#d3d3d3")
- private String customColor;
+ private String customColor = "#d3d3d3";
- @Schema(
- description = "Convert the redacted PDF to an image",
- defaultValue = "false",
- requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean convertPDFToImage;
+ @Schema(description = "Convert the redacted PDF to an image", defaultValue = "false")
+ private Boolean convertPDFToImage = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/ManualRedactPdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/ManualRedactPdfRequest.java
index 48cb5bc671..85962bce03 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/ManualRedactPdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/ManualRedactPdfRequest.java
@@ -13,6 +13,13 @@ import stirling.software.common.model.api.security.RedactionArea;
@Data
@EqualsAndHashCode(callSuper = true)
public class ManualRedactPdfRequest extends PDFWithPageNums {
+ // Shadows the shared "all" default: here these pages are blacked out entirely.
+ @Schema(
+ description =
+ "Pages to black out completely, e.g. '1,3-5'. Omit to redact only the listed"
+ + " areas.")
+ private String pageNumbers;
+
@Schema(
description = "A list of areas that should be redacted",
requiredMode = Schema.RequiredMode.REQUIRED)
@@ -22,11 +29,11 @@ public class ManualRedactPdfRequest extends PDFWithPageNums {
description = "Convert the redacted PDF to an image",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean convertPDFToImage;
+ private Boolean convertPDFToImage = false;
@Schema(
description = "The color used to fully redact certain pages",
defaultValue = "#000000",
requiredMode = Schema.RequiredMode.REQUIRED)
- private String pageRedactionColor;
+ private String pageRedactionColor = "#000000";
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/RedactPdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/RedactPdfRequest.java
index a81e253733..2fe83f026f 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/RedactPdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/RedactPdfRequest.java
@@ -12,8 +12,8 @@ import stirling.software.common.model.api.PDFFile;
public class RedactPdfRequest extends PDFFile {
@Schema(
- description = "List of text to redact from the PDF",
- defaultValue = "text,text2",
+ description = "Newline-separated list of text to redact from the PDF",
+ example = "text\ntext2",
requiredMode = Schema.RequiredMode.REQUIRED)
private String listOfText;
@@ -21,25 +21,25 @@ public class RedactPdfRequest extends PDFFile {
description = "Whether to use regex for the listOfText",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean useRegex;
+ private Boolean useRegex = false;
@Schema(
description = "Whether to use whole word search",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean wholeWordSearch;
+ private Boolean wholeWordSearch = false;
@Schema(
description = "Whether matching is case-sensitive, for plain text and regex alike",
defaultValue = "false",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
- private Boolean caseSensitive;
+ private Boolean caseSensitive = false;
@Schema(
description = "The color for redaction",
defaultValue = "#000000",
requiredMode = Schema.RequiredMode.REQUIRED)
- private String redactColor;
+ private String redactColor = "#000000";
@Schema(
description = "Custom padding for redaction",
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/SanitizePdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/SanitizePdfRequest.java
index 736fbb20da..3e93b5fe1b 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/SanitizePdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/SanitizePdfRequest.java
@@ -15,35 +15,35 @@ public class SanitizePdfRequest extends PDFFile {
description = "Remove JavaScript actions from the PDF",
defaultValue = "true",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean removeJavaScript;
+ private Boolean removeJavaScript = true;
@Schema(
description = "Remove embedded files from the PDF",
defaultValue = "true",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean removeEmbeddedFiles;
+ private Boolean removeEmbeddedFiles = true;
@Schema(
description = "Remove XMP metadata from the PDF",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean removeXMPMetadata;
+ private Boolean removeXMPMetadata = false;
@Schema(
description = "Remove document info metadata from the PDF",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean removeMetadata;
+ private Boolean removeMetadata = false;
@Schema(
description = "Remove links from the PDF",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean removeLinks;
+ private Boolean removeLinks = false;
@Schema(
description = "Remove fonts from the PDF",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean removeFonts;
+ private Boolean removeFonts = false;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/SignPDFWithCertRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/SignPDFWithCertRequest.java
index 144f516d3a..504c873f5c 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/SignPDFWithCertRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/SignPDFWithCertRequest.java
@@ -15,35 +15,38 @@ public class SignPDFWithCertRequest extends PDFFile {
@Schema(
description =
- "The type of the digital certificate. WINDOWS_STORE and PKCS11 are"
- + " hardware-backed and only available in the desktop app.",
- allowableValues = {"PEM", "PKCS12", "PFX", "JKS", "SERVER", "WINDOWS_STORE", "PKCS11"},
+ "SERVER: this server's own certificate, no file or password. Signer shown is"
+ + " the server's organisation, not the user; self-signed by default, so"
+ + " other PDF readers may show it unverified. PEM needs"
+ + " certFile+privateKeyFile, PKCS12/PFX p12File, JKS jksFile."
+ + " WINDOWS_STORE/PKCS11: desktop app only.",
+ allowableValues = {"SERVER", "PEM", "PKCS12", "PFX", "JKS", "WINDOWS_STORE", "PKCS11"},
requiredMode = Schema.RequiredMode.REQUIRED)
private String certType;
@Schema(
description =
- "The private key for the digital certificate (required for PEM type"
- + " certificates, supports .pem, .der, or .key files)")
+ "Private key for certType PEM, used with certFile: a PEM text file (.pem or"
+ + " .key), unencrypted or password-protected.")
private MultipartFile privateKeyFile;
@Schema(
description =
- "The digital certificate (required for PEM type certificates, supports"
- + " .pem, .der, .crt, or .cer files)")
+ "Certificate for certType PEM, used with privateKeyFile (.pem, .crt, .cer or"
+ + " .der).")
private MultipartFile certFile;
- @Schema(
- description =
- "The PKCS12/PFX keystore file (required for PKCS12 or PFX type certificates)")
+ @Schema(description = "PKCS#12 keystore for certType PKCS12 or PFX (.p12 or .pfx).")
private MultipartFile p12File;
- @Schema(description = "The JKS keystore file (Java Key Store)")
+ @Schema(description = "Java KeyStore for certType JKS (.jks).")
private MultipartFile jksFile;
@Schema(
description =
- "The password for the keystore / private key, or the token PIN for PKCS11",
+ "Password for the PKCS12/PFX or JKS keystore or an encrypted PEM key, or the"
+ + " PKCS11 token PIN. Leave empty if the key has none. Not needed for"
+ + " SERVER or WINDOWS_STORE.",
format = "password")
private String password;
@@ -67,30 +70,41 @@ public class SignPDFWithCertRequest extends PDFFile {
private Integer pkcs11Slot;
@Schema(
- description = "Whether to visually show the signature in the PDF file",
+ description =
+ "Add a visible signature box on pageNumber showing the certificate's name, the"
+ + " date and the reason (if set).",
defaultValue = "false",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean showSignature;
+ private Boolean showSignature = false;
- @Schema(description = "The reason for signing the PDF", defaultValue = "Signed by SPDF")
+ @Schema(
+ description = "The reason for signing the PDF. Omitted from the signature when not set",
+ example = "Signed by SPDF")
private String reason;
- @Schema(description = "The location where the PDF is signed", defaultValue = "SPDF")
+ @Schema(
+ description =
+ "The location where the PDF is signed. Omitted from the signature when not set",
+ example = "SPDF")
private String location;
- @Schema(description = "The name of the signer", defaultValue = "SPDF")
+ @Schema(
+ description =
+ "Signer name stored in the signature properties; the visible box shows the"
+ + " certificate's name instead. Omitted when not set.",
+ example = "SPDF")
private String name;
@Schema(
description =
- "The page number where the signature should be visible. This is required if"
- + " showSignature is set to true",
+ "Page (1-based) for the visible signature. Only used when showSignature is"
+ + " true.",
defaultValue = "1")
- private Integer pageNumber;
+ private Integer pageNumber = 1;
@Schema(
description = "Whether to visually show a signature logo along with the signature",
defaultValue = "true",
requiredMode = Schema.RequiredMode.REQUIRED)
- private Boolean showLogo;
+ private Boolean showLogo = true;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/TimestampPdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/TimestampPdfRequest.java
index 8d4c1484b7..2e6fcf210a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/TimestampPdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/TimestampPdfRequest.java
@@ -17,8 +17,9 @@ public class TimestampPdfRequest extends PDFFile {
+ " Must be one of the built-in presets (DigiCert, Sectigo, SSL.com,"
+ " FreeTSA, MeSign) or an admin-configured URL in"
+ " settings.yml (security.timestamp.customTsaUrls)."
- + " If omitted, the server default is used.",
- defaultValue = "http://timestamp.digicert.com",
+ + " If omitted, the server default is used"
+ + " (security.timestamp.defaultTsaUrl, DigiCert unless changed).",
+ example = "http://timestamp.digicert.com",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String tsaUrl;
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerMoreTest.java
index 3ec1cda16a..2e7cce8bd1 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerMoreTest.java
@@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -118,8 +119,8 @@ class CropControllerMoreTest {
CropPdfForm request = form(file, true);
when(endpointConfiguration.isGroupEnabled("Ghostscript")).thenReturn(false);
- PDDocument source = mock(PDDocument.class);
- PDDocument out = mock(PDDocument.class);
+ PDDocument source = spy(Loader.loadPDF(file.getBytes()));
+ PDDocument out = spy(new PDDocument());
when(pdfDocumentFactory.load(request)).thenReturn(source);
when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(source)).thenReturn(out);
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerTest.java
index d02528e8a5..8903ed2a6a 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/CropControllerTest.java
@@ -232,8 +232,8 @@ class CropControllerTest {
.withAutoCrop(false)
.build();
- PDDocument mockDocument = mock(PDDocument.class);
- PDDocument newDocument = mock(PDDocument.class);
+ PDDocument mockDocument = spy(Loader.loadPDF(testFile.getBytes()));
+ PDDocument newDocument = spy(new PDDocument());
when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(mockDocument))
.thenReturn(newDocument);
@@ -269,8 +269,8 @@ class CropControllerTest {
.withAutoCrop(false)
.build();
- PDDocument mockDocument = mock(PDDocument.class);
- PDDocument newDocument = mock(PDDocument.class);
+ PDDocument mockDocument = spy(Loader.loadPDF(testFile.getBytes()));
+ PDDocument newDocument = spy(new PDDocument());
when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(mockDocument))
.thenReturn(newDocument);
@@ -305,7 +305,7 @@ class CropControllerTest {
assertThatThrownBy(() -> cropController.cropPdf(request))
.isInstanceOf(IllegalArgumentException.class)
- .hasMessageContaining("does not select any page");
+ .hasMessageContaining("pages are numbered 1 to");
}
}
@@ -659,8 +659,8 @@ class CropControllerTest {
.withAutoCrop(false)
.build();
- PDDocument mockDocument = mock(PDDocument.class);
- PDDocument newDocument = mock(PDDocument.class);
+ PDDocument mockDocument = spy(Loader.loadPDF(testFile.getBytes()));
+ PDDocument newDocument = spy(new PDDocument());
when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(mockDocument))
.thenReturn(newDocument);
@@ -672,8 +672,8 @@ class CropControllerTest {
}
@Test
- @DisplayName("Should handle zero width or height")
- void shouldHandleZeroDimensions() throws IOException {
+ @DisplayName("Should reject zero width or height instead of blanking the pages")
+ void shouldRejectZeroDimensions() throws IOException {
MockMultipartFile testFile = pdfFactory.createStandardPdf("test.pdf");
CropPdfForm request =
new CropRequestBuilder()
@@ -683,16 +683,9 @@ class CropControllerTest {
.withAutoCrop(false)
.build();
- PDDocument mockDocument = mock(PDDocument.class);
- PDDocument newDocument = mock(PDDocument.class);
- when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
- when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(mockDocument))
- .thenReturn(newDocument);
-
- assertThatCode(() -> cropController.cropPdf(request)).doesNotThrowAnyException();
-
- verify(mockDocument, times(1)).close();
- verify(newDocument, times(1)).close();
+ assertThatThrownBy(() -> cropController.cropPdf(request))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("greater than 0");
}
}
@@ -725,8 +718,8 @@ class CropControllerTest {
.withAutoCrop(false)
.build();
- PDDocument mockDocument = mock(PDDocument.class);
- PDDocument newDocument = mock(PDDocument.class);
+ PDDocument mockDocument = spy(Loader.loadPDF(testFile.getBytes()));
+ PDDocument newDocument = spy(new PDDocument());
when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(mockDocument))
.thenReturn(newDocument);
@@ -735,6 +728,12 @@ class CropControllerTest {
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ try (PDDocument cropped = Loader.loadPDF(drainBody(response))) {
+ assertThat(cropped.getNumberOfPages()).isEqualTo(1);
+ PDRectangle box = cropped.getPage(0).getMediaBox();
+ assertThat(box.getWidth()).isEqualTo(expectedWidth);
+ assertThat(box.getHeight()).isEqualTo(expectedHeight);
+ }
}
@ParameterizedTest
@@ -753,8 +752,8 @@ class CropControllerTest {
.withAutoCrop(false)
.build();
- PDDocument mockDocument = mock(PDDocument.class);
- PDDocument newDocument = mock(PDDocument.class);
+ PDDocument mockDocument = spy(Loader.loadPDF(testFile.getBytes()));
+ PDDocument newDocument = spy(new PDDocument());
when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
when(pdfDocumentFactory.createNewDocumentBasedOnOldDocument(mockDocument))
.thenReturn(newDocument);
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/RearrangePagesPDFControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/RearrangePagesPDFControllerTest.java
index 2b3145c47a..4d7050ed40 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/RearrangePagesPDFControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/RearrangePagesPDFControllerTest.java
@@ -1,6 +1,7 @@
package stirling.software.SPDF.controller.api;
import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@@ -112,6 +113,55 @@ class RearrangePagesPDFControllerTest {
verify(mockDoc).removePage(0); // page 1 (0-indexed = 0)
}
+ @Test
+ void deletePages_outOfRangePageIsAnError() throws IOException {
+ MockMultipartFile file = createMockPdf();
+ PDFWithPageNums request = new PDFWithPageNums();
+ request.setFileInput(file);
+ request.setPageNumbers("99");
+
+ PDDocument mockDoc = mock(PDDocument.class);
+ when(pdfDocumentFactory.load(file)).thenReturn(mockDoc);
+ when(mockDoc.getNumberOfPages()).thenReturn(3);
+
+ IllegalArgumentException e =
+ assertThrows(IllegalArgumentException.class, () -> controller.deletePages(request));
+ assertTrue(e.getMessage().contains("99"));
+ verify(mockDoc, never()).removePage(anyInt());
+ }
+
+ @Test
+ void pageSelection_acceptsRealPagesAndRejectsTheRest() {
+ assertDoesNotThrow(
+ () ->
+ stirling.software.common.util.GeneralUtils.requireValidPageSelection(
+ "1,2-3,all,2n+1,2-, 1 - 3 ,1,5,0,0-2", 3));
+ // 5 alone matches nothing; "1,5" above is fine because page 1 exists.
+ for (String bad : List.of("0", "-1", "not-a-page", "99", "5-9", ",,", "3-2", "5")) {
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ stirling.software.common.util.GeneralUtils.requireValidPageSelection(
+ bad, 3),
+ bad);
+ }
+ }
+
+ @Test
+ void deletePages_refusesToRemoveEveryPage() throws IOException {
+ MockMultipartFile file = createMockPdf();
+ PDFWithPageNums request = new PDFWithPageNums();
+ request.setFileInput(file);
+ // pageNumbers omitted: the shared default is "all".
+
+ PDDocument mockDoc = mock(PDDocument.class);
+ when(pdfDocumentFactory.load(file)).thenReturn(mockDoc);
+ when(mockDoc.getNumberOfPages()).thenReturn(3);
+
+ assertThrows(IllegalArgumentException.class, () -> controller.deletePages(request));
+ verify(mockDoc, never()).removePage(anyInt());
+ }
+
@Test
void testRearrangePages_ReverseOrder() throws IOException {
MockMultipartFile file = createMockPdf();
@@ -139,6 +189,25 @@ class RearrangePagesPDFControllerTest {
}
}
+ @Test
+ void unknownCustomModeIsAClearErrorNamingTheModes() throws IOException {
+ MockMultipartFile file = createMockPdf();
+ RearrangePagesRequest request = new RearrangePagesRequest();
+ request.setFileInput(file);
+ request.setPageNumbers("");
+ request.setCustomMode("SHUFFLE");
+
+ try (PDDocument realDoc = buildRealPdf(3)) {
+ when(pdfDocumentFactory.load(file)).thenReturn(realDoc);
+
+ IllegalArgumentException error =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> controller.rearrangePages(request));
+ assertTrue(error.getMessage().contains("REVERSE_ORDER"), error.getMessage());
+ }
+ }
+
@Test
void testRearrangePages_RemoveFirst() throws IOException {
MockMultipartFile file = createMockPdf();
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/ScalePagesControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/ScalePagesControllerTest.java
index 9c176bd6f4..09476aa279 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/ScalePagesControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/ScalePagesControllerTest.java
@@ -289,6 +289,86 @@ class ScalePagesControllerTest {
assertThrows(IllegalArgumentException.class, () -> controller.scalePages(request));
}
+ @Test
+ void testScalePages_OmittedPageSizeKeepsPageSize() throws Exception {
+ byte[] pdfBytes = createRealPdf(PDRectangle.LETTER, 2);
+ MockMultipartFile file =
+ new MockMultipartFile(
+ "fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, pdfBytes);
+
+ ScalePagesRequest request = new ScalePagesRequest();
+ request.setFileInput(file);
+ request.setScaleFactor(0.8f);
+
+ setupFactory();
+
+ ResponseEntity<Resource> response = controller.scalePages(request);
+
+ assertEquals(200, response.getStatusCode().value());
+ try (PDDocument out = org.apache.pdfbox.Loader.loadPDF(drainBody(response))) {
+ assertEquals(2, out.getNumberOfPages());
+ PDRectangle box = out.getPage(0).getMediaBox();
+ assertEquals(PDRectangle.LETTER.getWidth(), box.getWidth(), 0.01f);
+ assertEquals(PDRectangle.LETTER.getHeight(), box.getHeight(), 0.01f);
+ }
+ }
+
+ @Test
+ void testScalePages_KeepKeepsEachPagesOwnSize() throws Exception {
+ byte[] pdfBytes;
+ try (PDDocument doc = new PDDocument()) {
+ doc.addPage(new PDPage(PDRectangle.A4));
+ doc.addPage(new PDPage(PDRectangle.LETTER));
+ Path pdfPath = tempDir.resolve("mixed.pdf");
+ doc.save(pdfPath.toFile());
+ pdfBytes = Files.readAllBytes(pdfPath);
+ }
+ MockMultipartFile file =
+ new MockMultipartFile(
+ "fileInput", "mixed.pdf", MediaType.APPLICATION_PDF_VALUE, pdfBytes);
+
+ ScalePagesRequest request = new ScalePagesRequest();
+ request.setFileInput(file);
+ request.setPageSize("KEEP");
+ request.setScaleFactor(0.5f);
+
+ setupFactory();
+
+ ResponseEntity<Resource> response = controller.scalePages(request);
+
+ assertEquals(200, response.getStatusCode().value());
+ try (PDDocument out = org.apache.pdfbox.Loader.loadPDF(drainBody(response))) {
+ assertEquals(2, out.getNumberOfPages());
+ PDRectangle first = out.getPage(0).getMediaBox();
+ assertEquals(PDRectangle.A4.getWidth(), first.getWidth(), 0.01f);
+ assertEquals(PDRectangle.A4.getHeight(), first.getHeight(), 0.01f);
+ PDRectangle second = out.getPage(1).getMediaBox();
+ assertEquals(PDRectangle.LETTER.getWidth(), second.getWidth(), 0.01f);
+ assertEquals(PDRectangle.LETTER.getHeight(), second.getHeight(), 0.01f);
+ }
+ }
+
+ @Test
+ void testScalePages_BlankPageSizeKeepsPageSize() throws Exception {
+ byte[] pdfBytes = createRealPdf(PDRectangle.A5, 1);
+ MockMultipartFile file =
+ new MockMultipartFile(
+ "fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, pdfBytes);
+
+ ScalePagesRequest request = new ScalePagesRequest();
+ request.setFileInput(file);
+ request.setPageSize("");
+
+ setupFactory();
+
+ ResponseEntity<Resource> response = controller.scalePages(request);
+
+ assertEquals(200, response.getStatusCode().value());
+ try (PDDocument out = org.apache.pdfbox.Loader.loadPDF(drainBody(response))) {
+ assertEquals(PDRectangle.A5.getWidth(), out.getPage(0).getMediaBox().getWidth(), 0.01f);
+ }
+ }
+
@Test
void testScalePages_A0Size() throws Exception {
byte[] pdfBytes = createRealPdf(PDRectangle.A4, 1);
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/SplitPdfByChaptersControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/SplitPdfByChaptersControllerMoreTest.java
index bbd3941ef0..134d46a007 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/SplitPdfByChaptersControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/SplitPdfByChaptersControllerMoreTest.java
@@ -1,6 +1,7 @@
package stirling.software.SPDF.controller.api;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -179,6 +180,39 @@ class SplitPdfByChaptersControllerMoreTest {
assertThat(outputs.size()).isGreaterThanOrEqualTo(topLevelCount);
assertThat(totalPages(outputs)).isEqualTo(8);
}
+
+ @Test
+ @DisplayName("omitted options default to level 1, matching the web UI")
+ void omittedOptionsUseUiDefaults() throws Exception {
+ SplitPdfByChaptersRequest req = new SplitPdfByChaptersRequest();
+ req.setFileInput(asFile(nestedDoc()));
+
+ ResponseEntity<Resource> response = controller.splitPdf(req);
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ List<byte[]> outputs = unzip(response.getBody());
+ // Level 1 splits on both chapters and their one child section each.
+ assertThat(outputs).hasSize(4);
+ assertThat(totalPages(outputs)).isEqualTo(8);
+ }
+ }
+
+ @Test
+ @DisplayName("a PDF without bookmarks is rejected with a clear client error")
+ void noBookmarksIsClientError() throws Exception {
+ byte[] bytes;
+ try (PDDocument doc = new PDDocument()) {
+ doc.addPage(new PDPage(PDRectangle.A4));
+ Path p = tempDir.resolve("plain.pdf");
+ doc.save(p.toFile());
+ bytes = Files.readAllBytes(p);
+ }
+ SplitPdfByChaptersRequest req = new SplitPdfByChaptersRequest();
+ req.setFileInput(asFile(bytes));
+
+ assertThatThrownBy(() -> controller.splitPdf(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("No PDF bookmarks");
}
@Nested
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/ToolInputGuardRegressionTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/ToolInputGuardRegressionTest.java
new file mode 100644
index 0000000000..4f8c463219
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/ToolInputGuardRegressionTest.java
@@ -0,0 +1,64 @@
+package stirling.software.SPDF.controller.api;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.mock.web.MockMultipartFile;
+
+import stirling.software.SPDF.controller.api.misc.StampController;
+import stirling.software.SPDF.controller.api.security.WatermarkController;
+import stirling.software.SPDF.model.api.general.SplitPdfBySizeOrCountRequest;
+import stirling.software.SPDF.model.api.misc.AddStampRequest;
+import stirling.software.SPDF.model.api.security.AddWatermarkRequest;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.TempFileManager;
+
+class ToolInputGuardRegressionTest {
+ private final CustomPDFDocumentFactory factory = mock(CustomPDFDocumentFactory.class);
+ private final TempFileManager temps = mock(TempFileManager.class);
+
+ @ParameterizedTest
+ @NullSource
+ @ValueSource(strings = {"", "image"})
+ void emptyStampImageIsAnInputError(String type) {
+ AddStampRequest request = new AddStampRequest();
+ request.setFileInput(
+ new MockMultipartFile("fileInput", "in.pdf", "application/pdf", new byte[] {1}));
+ request.setStampType(type);
+ request.setStampImage(new MockMultipartFile("stampImage", new byte[0]));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> new StampController(factory, temps).addStamp(request));
+ verifyNoInteractions(factory);
+ }
+
+ @ParameterizedTest
+ @NullSource
+ @ValueSource(strings = {"", "image"})
+ void emptyWatermarkImageIsAnInputError(String type) {
+ AddWatermarkRequest request = new AddWatermarkRequest();
+ request.setFileInput(
+ new MockMultipartFile("fileInput", "in.pdf", "application/pdf", new byte[] {1}));
+ request.setWatermarkType(type);
+ request.setWatermarkImage(new MockMultipartFile("watermarkImage", new byte[0]));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> new WatermarkController(factory, temps).addWatermark(request));
+ verifyNoInteractions(factory);
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {1, 2})
+ void countSplittingRequiresAnExplicitNumericValue(int type) {
+ SplitPdfBySizeOrCountRequest request = new SplitPdfBySizeOrCountRequest();
+ request.setSplitType(type);
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> new SplitPdfBySizeController(factory, temps).autoSplitPdf(request));
+ verifyNoInteractions(factory, temps);
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AutoRotateControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AutoRotateControllerTest.java
index 0545a17058..e05bbdf669 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AutoRotateControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/AutoRotateControllerTest.java
@@ -105,6 +105,16 @@ class AutoRotateControllerTest {
return request;
}
+ @Test
+ void rejectsNullExplicitRotationBeforeDereferencingIt() throws Exception {
+ PDDocument document = docWithUprightText(0);
+ AutoRotatePdfRequest request = request(document);
+ request.setPageRotations(java.util.Collections.singletonList(null));
+ assertThatThrownBy(() -> controller.autoRotatePdf(request))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("pageRotations");
+ }
+
private static PDDocument reload(ResponseEntity<?> response) throws IOException {
Resource resource = (Resource) response.getBody();
return Loader.loadPDF(resource.getContentAsByteArray());
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerMoreTest.java
index f1326fea8e..c89868b5ca 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/OCRControllerMoreTest.java
@@ -326,6 +326,100 @@ class OCRControllerMoreTest {
}
}
+ @Test
+ @DisplayName("exit code 6 (prior OCR found) becomes a 400 naming ocrType")
+ void ocrMyPdfPriorOcrFoundIsClientError() throws Exception {
+ availLanguages("eng");
+ when(endpointConfiguration.isGroupEnabled("OCRmyPDF")).thenReturn(true);
+ ProcessPdfWithOcrRequest request = baseRequest("in.pdf");
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ ProcessExecutor executor = mock(ProcessExecutor.class);
+ when(executor.runCommandWithOutputHandling(anyList()))
+ .thenThrow(
+ new IOException(
+ "Command process failed with exit code 6. Error message:"
+ + " PriorOcrFoundError: page already has text!"));
+ pe.when(() -> ProcessExecutor.getInstance(Processes.OCR_MY_PDF))
+ .thenReturn(executor);
+
+ assertThatThrownBy(() -> ocrController.processPdfWithOCR(request))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("ocrType")
+ .hasMessageContaining("skip-text")
+ .hasMessageContaining("force-ocr")
+ .hasMessageNotContaining("PriorOcrFoundError");
+ }
+ }
+
+ @Test
+ @DisplayName("exit code 6 reported as a result is also a 400")
+ void ocrMyPdfPriorOcrFoundResultIsClientError() throws Exception {
+ availLanguages("eng");
+ when(endpointConfiguration.isGroupEnabled("OCRmyPDF")).thenReturn(true);
+ ProcessPdfWithOcrRequest request = baseRequest("in.pdf");
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ ProcessExecutor executor = executorReturning(6, "PriorOcrFoundError");
+ pe.when(() -> ProcessExecutor.getInstance(Processes.OCR_MY_PDF))
+ .thenReturn(executor);
+
+ assertThatThrownBy(() -> ocrController.processPdfWithOCR(request))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("ocrType");
+ }
+ }
+
+ @Test
+ @DisplayName("other ocrmypdf exit codes still propagate as IOException")
+ void ocrMyPdfOtherExitCodePropagates() throws Exception {
+ availLanguages("eng");
+ when(endpointConfiguration.isGroupEnabled("OCRmyPDF")).thenReturn(true);
+ ProcessPdfWithOcrRequest request = baseRequest("in.pdf");
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ ProcessExecutor executor = mock(ProcessExecutor.class);
+ when(executor.runCommandWithOutputHandling(anyList()))
+ .thenThrow(new IOException("Command process failed with exit code 66."));
+ pe.when(() -> ProcessExecutor.getInstance(Processes.OCR_MY_PDF))
+ .thenReturn(executor);
+
+ assertThatThrownBy(() -> ocrController.processPdfWithOCR(request))
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("exit code 66");
+ }
+ }
+
+ @Test
+ @DisplayName("omitted ocrType and languages default to skip-text and eng")
+ void omittedOcrTypeDefaultsToSkipText() throws Exception {
+ availLanguages("eng");
+ when(endpointConfiguration.isGroupEnabled("OCRmyPDF")).thenReturn(true);
+ ProcessPdfWithOcrRequest request = new ProcessPdfWithOcrRequest();
+ request.setFileInput(pdfMultipartFile("in.pdf"));
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class);
+ MockedStatic<WebResponseUtils> wr =
+ Mockito.mockStatic(WebResponseUtils.class)) {
+ ProcessExecutor executor = mock(ProcessExecutor.class);
+ ProcessExecutorResult result = mock(ProcessExecutorResult.class);
+ when(result.getRc()).thenReturn(0);
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<String>> cmd = ArgumentCaptor.forClass(List.class);
+ when(executor.runCommandWithOutputHandling(cmd.capture())).thenReturn(result);
+ pe.when(() -> ProcessExecutor.getInstance(Processes.OCR_MY_PDF))
+ .thenReturn(executor);
+ wr.when(() -> WebResponseUtils.pdfFileToWebResponse(any(), anyString()))
+ .thenReturn(cannedResponse());
+
+ ocrController.processPdfWithOCR(request);
+
+ assertThat(cmd.getValue()).contains("--skip-text");
+ assertThat(cmd.getValue()).contains("--language", "eng");
+ }
+ }
+
@Test
@DisplayName("propagates a process timeout as IOException")
void ocrMyPdfTimeoutPropagates() throws Exception {
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ReplaceAndInvertColorControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ReplaceAndInvertColorControllerTest.java
index 1e5df278b1..b2cc24cf2c 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ReplaceAndInvertColorControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ReplaceAndInvertColorControllerTest.java
@@ -126,7 +126,7 @@ class ReplaceAndInvertColorControllerTest {
when(replaceAndInvertColorService.replaceAndInvertColor(
eq(pdfFile),
eq(ReplaceAndInvert.CUSTOM_COLOR),
- isNull(),
+ eq(HighContrastColorCombination.WHITE_TEXT_ON_BLACK),
eq("0"),
eq("16777215")))
.thenReturn(resource);
@@ -159,7 +159,7 @@ class ReplaceAndInvertColorControllerTest {
when(replaceAndInvertColorService.replaceAndInvertColor(
eq(pdfFile),
eq(ReplaceAndInvert.FULL_INVERSION),
- isNull(),
+ eq(HighContrastColorCombination.WHITE_TEXT_ON_BLACK),
isNull(),
isNull()))
.thenReturn(resource);
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/StampControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/StampControllerMoreTest.java
index c8313830c8..d4a728e3ab 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/StampControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/StampControllerMoreTest.java
@@ -505,11 +505,58 @@ class StampControllerMoreTest {
}
@Test
- @DisplayName("unknown stamp type is a no-op that still returns the PDF")
- void unknownStampTypeIsNoOp() throws Exception {
+ @DisplayName("unknown stamp type is rejected with a message naming the field")
+ void rejectsUnknownStampType() throws Exception {
AddStampRequest req = baseRequest(pdfFile(2));
req.setStampType("neither");
- assertValidPdf(stampController.addStamp(req), 2);
+ assertThatThrownBy(() -> stampController.addStamp(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("stampType");
+ }
+
+ @Test
+ @DisplayName("text stamp type without text is rejected")
+ void rejectsMissingText() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampText(" ");
+ assertThatThrownBy(() -> stampController.addStamp(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Stamp text");
+ }
+ }
+
+ @Nested
+ @DisplayName("Omitted optional fields fall back to the UI defaults")
+ class OmittedOptionalFields {
+
+ @Test
+ @DisplayName("only stampType and stampText stamps the PDF")
+ void textStampWithOnlyRequiredFields() throws Exception {
+ AddStampRequest req = new AddStampRequest();
+ req.setFileInput(pdfFile(1));
+ req.setStampType("text");
+ req.setStampText("QA TEST");
+ assertValidPdf(stampController.addStamp(req), 1);
+ }
+
+ @Test
+ @DisplayName("customMargin given but customColor omitted still stamps")
+ void textStampWithoutColour() throws Exception {
+ AddStampRequest req = new AddStampRequest();
+ req.setFileInput(pdfFile(1));
+ req.setStampType("text");
+ req.setStampText("QA TEST");
+ req.setCustomMargin("10");
+ assertValidPdf(stampController.addStamp(req), 1);
+ }
+
+ @Test
+ @DisplayName("omitted stampType is inferred from the supplied image")
+ void stampTypeInferredFromImage() throws Exception {
+ AddStampRequest req = new AddStampRequest();
+ req.setFileInput(pdfFile(1));
+ req.setStampImage(pngImage("stamp.png"));
+ assertValidPdf(stampController.addStamp(req), 1);
}
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/CertSignControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/CertSignControllerTest.java
index 5a22d48bf3..1a76dcc3a8 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/CertSignControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/CertSignControllerTest.java
@@ -27,6 +27,8 @@ import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -241,6 +243,31 @@ class CertSignControllerTest {
assertTrue(exception.getMessage().contains("PKCS12 keystore"));
}
+ @ParameterizedTest
+ @ValueSource(strings = {"PKCS12", "JKS"})
+ void wrongKeystorePasswordIsAnInputError(String certType) {
+ SignPDFWithCertRequest request = new SignPDFWithCertRequest();
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, pdfBytes));
+ request.setCertType(certType);
+ if ("JKS".equals(certType)) {
+ request.setJksFile(
+ new MockMultipartFile("jksFile", "c.jks", "application/x", jksBytes));
+ } else {
+ request.setP12File(
+ new MockMultipartFile("p12File", "c.p12", "application/x", p12Bytes));
+ }
+ request.setPassword("not-the-password");
+
+ IllegalArgumentException exception =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> certSignController.signPDFWithCert(request, httpRequest));
+
+ assertTrue(exception.getMessage().contains("password is incorrect"));
+ }
+
@Test
void testSignPdfWithJks() throws Exception {
MockMultipartFile pdfFile =
@@ -397,6 +424,85 @@ class CertSignControllerTest {
assertTrue(drainBody(response).length > 0);
}
+ /** An openssl-style unencrypted PKCS#8 key and a self-signed certificate, as PEM text. */
+ private static byte[][] unencryptedPemPair() throws Exception {
+ java.security.KeyPairGenerator generator =
+ java.security.KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ java.security.KeyPair pair = generator.generateKeyPair();
+ org.bouncycastle.asn1.x500.X500Name subject =
+ new org.bouncycastle.asn1.x500.X500Name("CN=Chat Tester");
+ java.util.Date now = new java.util.Date();
+ java.security.cert.X509Certificate cert =
+ new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter()
+ .getCertificate(
+ new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder(
+ subject,
+ java.math.BigInteger.ONE,
+ now,
+ new java.util.Date(now.getTime() + 86_400_000L),
+ subject,
+ pair.getPublic())
+ .build(
+ new org.bouncycastle.operator.jcajce
+ .JcaContentSignerBuilder(
+ "SHA256withRSA")
+ .build(pair.getPrivate())));
+ return new byte[][] {
+ pem("PRIVATE KEY", pair.getPrivate().getEncoded()),
+ pem("CERTIFICATE", cert.getEncoded())
+ };
+ }
+
+ private static byte[] pem(String type, byte[] der) throws Exception {
+ java.io.StringWriter text = new java.io.StringWriter();
+ try (org.bouncycastle.util.io.pem.PemWriter writer =
+ new org.bouncycastle.util.io.pem.PemWriter(text)) {
+ writer.writeObject(new org.bouncycastle.util.io.pem.PemObject(type, der));
+ }
+ return text.toString().getBytes(java.nio.charset.StandardCharsets.US_ASCII);
+ }
+
+ private SignPDFWithCertRequest unencryptedPemRequest() throws Exception {
+ byte[][] pemPair = unencryptedPemPair();
+ SignPDFWithCertRequest request = new SignPDFWithCertRequest();
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, pdfBytes));
+ request.setCertType("PEM");
+ request.setPrivateKeyFile(
+ new MockMultipartFile("privateKeyFile", "key.pem", "text/plain", pemPair[0]));
+ request.setCertFile(
+ new MockMultipartFile("certFile", "cert.pem", "text/plain", pemPair[1]));
+ request.setShowLogo(false);
+ return request;
+ }
+
+ @Test
+ void unencryptedPkcs8KeyWithNoPasswordSignsWithAVisibleBoxAndNoReason() throws Exception {
+ SignPDFWithCertRequest request = unencryptedPemRequest();
+ request.setShowSignature(true);
+ request.setPageNumber(1);
+
+ ResponseEntity<Resource> response =
+ certSignController.signPDFWithCert(request, httpRequest);
+
+ assertTrue(drainBody(response).length > 0);
+ }
+
+ @Test
+ void visibleSignatureOnAPageThatDoesNotExistIsAClearError() throws Exception {
+ SignPDFWithCertRequest request = unencryptedPemRequest();
+ request.setShowSignature(true);
+ request.setPageNumber(5);
+
+ IllegalArgumentException error =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> certSignController.signPDFWithCert(request, httpRequest));
+ assertTrue(error.getMessage().contains("pageNumber 5"), error.getMessage());
+ }
+
@Test
void testSignPdfWithUnencryptedPkcs8PemKey() throws Exception {
ResponseEntity<Resource> response =
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerMoreTest.java
index a5f5c9ef9f..0e363ea5a8 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerMoreTest.java
@@ -633,8 +633,8 @@ class RedactControllerMoreTest {
TempFile resultTemp = mock(TempFile.class);
when(resultTemp.getFile()).thenReturn(outFile);
- when(redactExecuteService.execute(any(RedactExecuteRequest.class)))
- .thenReturn(resultTemp);
+ when(redactExecuteService.executeWithOutcome(any(RedactExecuteRequest.class)))
+ .thenReturn(new RedactExecuteService.Outcome(resultTemp, 0, false));
RedactExecuteRequest request = new RedactExecuteRequest();
request.setFileInput(pdfFile(singlePageTextPdf("in")));
@@ -642,7 +642,8 @@ class RedactControllerMoreTest {
ResponseEntity<Resource> response = controller.executeRedaction(request);
assertThat(response.getStatusCode().value()).isEqualTo(200);
- verify(redactExecuteService, times(1)).execute(any(RedactExecuteRequest.class));
+ verify(redactExecuteService, times(1))
+ .executeWithOutcome(any(RedactExecuteRequest.class));
}
@Test
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerTest.java
index 3062c8f0c2..e6909ba96c 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerTest.java
@@ -1001,15 +1001,12 @@ class RedactControllerTest {
}
@Test
- @DisplayName("Should handle out of bounds page numbers gracefully")
- void handleOutOfBoundsPageNumbers() throws Exception {
+ @DisplayName("Should reject page numbers past the end of the document")
+ void rejectOutOfBoundsPageNumbers() {
ManualRedactPdfRequest request = createManualRedactPdfRequest();
request.setPageNumbers("100-200");
- ResponseEntity<Resource> response = redactController.redactPDF(request);
-
- assertNotNull(response);
- assertEquals(200, response.getStatusCode().value());
+ assertThrows(IllegalArgumentException.class, () -> redactController.redactPDF(request));
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceMoreTest.java
index b74815a3d4..5d9f12b6d9 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceMoreTest.java
@@ -37,7 +37,9 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
+import org.springframework.beans.MutablePropertyValues;
import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.SPDF.model.PDFText;
@@ -245,6 +247,15 @@ class RedactExecuteServiceMoreTest {
.isInstanceOf(IllegalArgumentException.class);
}
+ @Test
+ void blankAndNullRegexEntriesDoNotCountAsRedactionTargets() {
+ RedactExecuteRequest req = requestFor(new byte[] {1});
+ req.setRegexPatterns(java.util.Arrays.asList(null, " "));
+ assertThatThrownBy(() -> service.execute(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("No redaction targets");
+ }
+
@Test
@DisplayName("null file input with targets throws (wrapped as RuntimeException)")
void nullFileInputThrows() {
@@ -362,6 +373,22 @@ class RedactExecuteServiceMoreTest {
}
}
+ @Test
+ void indexedFormBindingSkipsNullRegexEntriesAndStillRedacts() throws IOException {
+ byte[] pdf = singlePageTextPdf("Order 12345 confirmed");
+ factoryReturns(pdf);
+ RedactExecuteRequest req = requestFor(pdf);
+ MutablePropertyValues values = new MutablePropertyValues();
+ values.add("regexPatterns[1]", "\\d+");
+ WebDataBinder binder = new WebDataBinder(req);
+ binder.bind(values);
+ assertThat(req.getRegexPatterns()).containsExactly(null, "\\d+");
+
+ try (TempFile out = service.execute(req)) {
+ assertThat(extractText(out)).doesNotContain("12345");
+ }
+ }
+
@Test
@DisplayName("text + regex together produce a single combined scan pass")
void textAndRegexCombined() throws IOException {
@@ -544,19 +571,32 @@ class RedactExecuteServiceMoreTest {
}
@Test
- @DisplayName("wipePages ignores out-of-range and non-positive page numbers")
- void wipePagesOutOfRangeIgnored() throws IOException {
+ @DisplayName("wipePages rejects pages that don't exist instead of wiping nothing")
+ void wipePagesOutOfRangeRejected() throws IOException {
byte[] pdf = singlePageTextPdf("survives the wipe");
factoryReturns(pdf);
RedactExecuteRequest req = requestFor(pdf);
- // page 0 dropped (non-positive), page 99 dropped (out of range) -> nothing wiped.
req.setWipePages(new ArrayList<>(List.of(0, 99)));
- // keep a real target so we are past the no-targets guard via imageBoxes.
- try (TempFile out = service.execute(req)) {
- assertThat(extractText(out)).contains("survives the wipe");
- }
+ assertThatThrownBy(() -> service.execute(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("[0, 99]");
+ }
+
+ @Test
+ @DisplayName("an invalid regex is rejected instead of matching nothing")
+ void invalidRegexRejected() throws IOException {
+ byte[] pdf = singlePageTextPdf("text");
+ factoryReturns(pdf);
+
+ RedactExecuteRequest req = requestFor(pdf);
+ req.setRegexPatterns(new ArrayList<>(List.of("secret-term(")));
+
+ assertThatThrownBy(() -> service.execute(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("not a valid regular expression")
+ .hasMessageNotContaining("secret-term");
}
@Test
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/SanitizeControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/SanitizeControllerTest.java
index 857e10fdda..02d29baf2c 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/SanitizeControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/SanitizeControllerTest.java
@@ -388,7 +388,12 @@ class SanitizeControllerTest {
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
- // All flags left null
+ request.setRemoveJavaScript(null);
+ request.setRemoveEmbeddedFiles(null);
+ request.setRemoveXMPMetadata(null);
+ request.setRemoveMetadata(null);
+ request.setRemoveLinks(null);
+ request.setRemoveFonts(null);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/WatermarkControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/WatermarkControllerMoreTest.java
index bc30bf8c2b..ef963b97ad 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/WatermarkControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/WatermarkControllerMoreTest.java
@@ -189,15 +189,82 @@ class WatermarkControllerMoreTest {
}
@Test
- @DisplayName("unknown watermark type leaves the document otherwise unmodified")
- void unknownTypeNoOp() throws Exception {
+ @DisplayName("unknown watermark type is rejected with a message naming the field")
+ void unknownTypeRejected() {
AddWatermarkRequest request = baseRequest();
request.setWatermarkType("nonsense");
request.setWatermarkText("ignored");
- ResponseEntity<Resource> response = controller.addWatermark(request);
+ IllegalArgumentException e =
+ assertThrows(
+ IllegalArgumentException.class, () -> controller.addWatermark(request));
+ assertTrue(e.getMessage().contains("watermarkType"));
+ }
- assertEquals(HttpStatus.OK, response.getStatusCode());
+ @Nested
+ @DisplayName("omitted optional fields fall back to the UI defaults")
+ class OmittedOptionalFields {
+
+ private AddWatermarkRequest minimalRequest() {
+ AddWatermarkRequest request = new AddWatermarkRequest();
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput",
+ "in.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ simplePdfBytes));
+ return request;
+ }
+
+ @Test
+ @DisplayName("text, fontSize and opacity alone watermark the PDF")
+ void textWatermarkWithoutAlphabetOrColour() throws Exception {
+ AddWatermarkRequest request = minimalRequest();
+ request.setWatermarkType("text");
+ request.setWatermarkText("TEST");
+ request.setFontSize(24);
+ request.setOpacity(0.5f);
+
+ ResponseEntity<Resource> response = controller.addWatermark(request);
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ assertTrue(response.getBody().contentLength() > 0);
+ }
+
+ @Test
+ @DisplayName("watermarkText alone defaults the type to text")
+ void textOnlyDefaultsTypeToText() throws Exception {
+ AddWatermarkRequest request = minimalRequest();
+ request.setWatermarkText("TEST");
+
+ ResponseEntity<Resource> response = controller.addWatermark(request);
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ }
+
+ @Test
+ @DisplayName("text type without text is rejected with a message naming the field")
+ void textTypeWithoutTextRejected() {
+ AddWatermarkRequest request = minimalRequest();
+ request.setWatermarkType("text");
+
+ IllegalArgumentException e =
+ assertThrows(
+ IllegalArgumentException.class, () -> controller.addWatermark(request));
+ assertTrue(e.getMessage().contains("watermarkText"));
+ }
+
+ @Test
+ @DisplayName("image type without an image is rejected with a message naming the field")
+ void imageTypeWithoutImageRejected() {
+ AddWatermarkRequest request = minimalRequest();
+ request.setWatermarkType("image");
+
+ IllegalArgumentException e =
+ assertThrows(
+ IllegalArgumentException.class, () -> controller.addWatermark(request));
+ assertTrue(e.getMessage().contains("watermarkImage"));
+ }
}
@Test
diff --git a/app/core/src/test/java/stirling/software/SPDF/exception/GlobalExceptionHandlerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/exception/GlobalExceptionHandlerMoreTest.java
index e44b7d0ef8..15248e95f1 100644
--- a/app/core/src/test/java/stirling/software/SPDF/exception/GlobalExceptionHandlerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/exception/GlobalExceptionHandlerMoreTest.java
@@ -30,6 +30,7 @@ import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
+import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.server.ResponseStatusException;
@@ -84,6 +85,20 @@ class GlobalExceptionHandlerMoreTest {
assertThat(resp.getBody().getProperties()).containsKey("errors");
assertThat(resp.getBody().getProperties()).containsKey("actionRequired");
}
+
+ @Test
+ @DisplayName("names each failing field in the detail")
+ void detailNamesFailingFields() throws Exception {
+ BindingResult br = new BeanPropertyBindingResult(new Object(), "target");
+ br.addError(new FieldError("target", "fontSize", "Font size must be at least 1.0"));
+ MethodParameter mp = mock(MethodParameter.class);
+ MethodArgumentNotValidException ex = new MethodArgumentNotValidException(mp, br);
+
+ ResponseEntity<ProblemDetail> resp = handler.handleMethodArgumentNotValid(ex, request);
+
+ assertThat(resp.getBody().getDetail())
+ .isEqualTo("Validation failed: fontSize: Font size must be at least 1.0");
+ }
}
@Nested
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageNumsTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageNumsTest.java
index 6ef1a650f1..d4ea294ab9 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageNumsTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageNumsTest.java
@@ -20,6 +20,25 @@ class PDFWithPageNumsTest {
mockDocument = mock(PDDocument.class);
}
+ @Test
+ void omittedOrBlankPageNumbersMeanAllPages() {
+ when(mockDocument.getNumberOfPages()).thenReturn(3);
+
+ assertEquals("all", new PDFWithPageNums().getPageNumbers());
+ assertEquals(
+ List.of(1, 2, 3), new PDFWithPageNums().getPageNumbersList(mockDocument, true));
+ pdfWithPageNums.setPageNumbers(" ");
+ assertEquals(List.of(1, 2, 3), pdfWithPageNums.getPageNumbersList(mockDocument, true));
+ }
+
+ @Test
+ void manualRedactionDoesNotBlackOutPagesByDefault() {
+ assertEquals(
+ null,
+ new stirling.software.SPDF.model.api.security.ManualRedactPdfRequest()
+ .getPageNumbers());
+ }
+
@Test
void testGetPageNumbersList_AllPages() {
pdfWithPageNums.setPageNumbers("all");
@@ -61,22 +80,22 @@ class PDFWithPageNumsTest {
}
@Test
- void testGetPageNumbersList_EmptyInput() {
+ void testGetPageNumbersList_EmptyInputMeansAllPages() {
pdfWithPageNums.setPageNumbers("");
- when(mockDocument.getNumberOfPages()).thenReturn(10);
+ when(mockDocument.getNumberOfPages()).thenReturn(3);
List<Integer> result = pdfWithPageNums.getPageNumbersList(mockDocument, true);
- assertTrue(result.isEmpty());
+ assertEquals(List.of(1, 2, 3), result);
}
@Test
- void testGetPageNumbersList_InvalidInput() {
+ void testGetPageNumbersList_InvalidInputIsRejected() {
pdfWithPageNums.setPageNumbers("invalid");
when(mockDocument.getNumberOfPages()).thenReturn(10);
- List<Integer> result = pdfWithPageNums.getPageNumbersList(mockDocument, true);
-
- assertTrue(result.isEmpty());
+ org.junit.jupiter.api.Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> pdfWithPageNums.getPageNumbersList(mockDocument, true));
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageSizeTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageSizeTest.java
index 40c6044a89..5acedf3477 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageSizeTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/PDFWithPageSizeTest.java
@@ -9,11 +9,11 @@ import org.junit.jupiter.api.Test;
class PDFWithPageSizeTest {
@Test
- @DisplayName("orientation defaults to PORTRAIT, pageSize null")
+ @DisplayName("orientation defaults to PORTRAIT, pageSize to KEEP")
void defaults() {
PDFWithPageSize req = new PDFWithPageSize();
assertThat(req.getOrientation()).isEqualTo("PORTRAIT");
- assertThat(req.getPageSize()).isNull();
+ assertThat(req.getPageSize()).isEqualTo("KEEP");
}
@Test
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/SchemaDefaultsMatchModelsTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/SchemaDefaultsMatchModelsTest.java
new file mode 100644
index 0000000000..f4f9865b4d
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/SchemaDefaultsMatchModelsTest.java
@@ -0,0 +1,121 @@
+package stirling.software.SPDF.model.api;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.regex.Pattern;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
+import org.springframework.core.type.filter.RegexPatternTypeFilter;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+/**
+ * A documented {@code @Schema} default must be what the API really uses when the field is omitted.
+ * API docs, MCP schemas and the generated client models all advertise it.
+ */
+class SchemaDefaultsMatchModelsTest {
+
+ private static final List<String> PACKAGES =
+ List.of(
+ "stirling.software.SPDF.model",
+ "stirling.software.common.model",
+ "stirling.software.proprietary.model");
+
+ @Test
+ void everyDocumentedDefaultIsTheFieldsInitialValue() throws Exception {
+ ClassPathScanningCandidateComponentProvider scanner =
+ new ClassPathScanningCandidateComponentProvider(false);
+ scanner.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
+ Set<String> mismatches = new TreeSet<>();
+ for (String pkg : PACKAGES) {
+ for (BeanDefinition definition : scanner.findCandidateComponents(pkg)) {
+ Object instance = instantiate(definition.getBeanClassName());
+ if (instance != null) {
+ collect(instance, mismatches);
+ }
+ }
+ }
+ assertTrue(
+ mismatches.isEmpty(),
+ "Set the field to its @Schema defaultValue, or move a placeholder to 'example':\n"
+ + String.join("\n", mismatches));
+ }
+
+ private static void collect(Object instance, Set<String> mismatches) throws Exception {
+ for (Class<?> c = instance.getClass();
+ c != null && c != Object.class;
+ c = c.getSuperclass()) {
+ for (Field field : c.getDeclaredFields()) {
+ Schema schema = field.getAnnotation(Schema.class);
+ if (Modifier.isStatic(field.getModifiers())
+ || schema == null
+ || schema.defaultValue().isEmpty()
+ || "##default".equals(schema.defaultValue())) {
+ continue;
+ }
+ field.setAccessible(true);
+ Object value = field.get(instance);
+ if (!same(schema.defaultValue(), value)) {
+ mismatches.add(
+ c.getSimpleName()
+ + "."
+ + field.getName()
+ + ": documented "
+ + schema.defaultValue()
+ + ", actually "
+ + value);
+ }
+ }
+ }
+ }
+
+ private static boolean same(String documented, Object value) {
+ if (value == null) {
+ return false;
+ }
+ String actual = String.valueOf(value);
+ String expected = documented;
+ if (value instanceof java.util.List<?>) {
+ actual = normalise(actual);
+ expected = normalise(expected);
+ }
+ if (actual.equalsIgnoreCase(expected)) {
+ return true;
+ }
+ try {
+ return Double.parseDouble(actual) == Double.parseDouble(expected);
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+
+ // Lists print as [eng] but are documented as ["eng"].
+ private static String normalise(String s) {
+ return s.replace("\"", "").replace(" ", "");
+ }
+
+ private static Object instantiate(String className) {
+ try {
+ Class<?> c = Class.forName(className);
+ if (c.isInterface()
+ || c.isEnum()
+ || c.isRecord()
+ || Modifier.isAbstract(c.getModifiers())) {
+ return null;
+ }
+ Constructor<?> constructor = c.getDeclaredConstructor();
+ constructor.setAccessible(true);
+ return constructor.newInstance();
+ } catch (ReflectiveOperationException | LinkageError | RuntimeException e) {
+ return null;
+ }
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/SplitPdfByChaptersRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/SplitPdfByChaptersRequestTest.java
index 6d4434bc5c..ecc73cd5cb 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/SplitPdfByChaptersRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/SplitPdfByChaptersRequestTest.java
@@ -8,6 +8,15 @@ import org.junit.jupiter.api.Test;
@DisplayName("SplitPdfByChaptersRequest")
class SplitPdfByChaptersRequestTest {
+ @Test
+ @DisplayName("defaults match what the web UI sends")
+ void defaultsMatchUi() {
+ SplitPdfByChaptersRequest req = new SplitPdfByChaptersRequest();
+ assertThat(req.getBookmarkLevel()).isEqualTo(1);
+ assertThat(req.getIncludeMetadata()).isFalse();
+ assertThat(req.getAllowDuplicates()).isFalse();
+ }
+
@Test
@DisplayName("accessors round-trip")
void roundTrip() {
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequestTest.java
index ae9992b6d2..d234175c2a 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequestTest.java
@@ -21,15 +21,15 @@ class ConvertEbookToPdfRequestTest {
class Defaults {
@Test
- @DisplayName("boolean wrappers and file start null on a fresh instance")
+ @DisplayName("boolean wrappers start false and file null on a fresh instance")
void defaultValues() {
ConvertEbookToPdfRequest req = new ConvertEbookToPdfRequest();
assertThat(req.getFileInput()).isNull();
- assertThat(req.getEmbedAllFonts()).isNull();
- assertThat(req.getIncludeTableOfContents()).isNull();
- assertThat(req.getIncludePageNumbers()).isNull();
- assertThat(req.getOptimizeForEbook()).isNull();
+ assertThat(req.getEmbedAllFonts()).isFalse();
+ assertThat(req.getIncludeTableOfContents()).isFalse();
+ assertThat(req.getIncludePageNumbers()).isFalse();
+ assertThat(req.getOptimizeForEbook()).isFalse();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/converters/PdfVectorExportRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/converters/PdfVectorExportRequestTest.java
index e39b58fa58..0dbdaf99e9 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/converters/PdfVectorExportRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/converters/PdfVectorExportRequestTest.java
@@ -14,12 +14,12 @@ class PdfVectorExportRequestTest {
class Defaults {
@Test
- @DisplayName("outputFormat defaults to eps and prepress to null")
+ @DisplayName("outputFormat defaults to eps and prepress to false")
void defaultValues() {
PdfVectorExportRequest req = new PdfVectorExportRequest();
assertThat(req.getOutputFormat()).isEqualTo("eps");
- assertThat(req.getPrepress()).isNull();
+ assertThat(req.getPrepress()).isFalse();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/filter/ContainsTextRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/filter/ContainsTextRequestTest.java
index bea4c0a670..076337f16c 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/filter/ContainsTextRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/filter/ContainsTextRequestTest.java
@@ -26,7 +26,7 @@ class ContainsTextRequestTest {
ContainsTextRequest req = new ContainsTextRequest();
assertThat(req.getText()).isNull();
- assertThat(req.getPageNumbers()).isNull();
+ assertThat(req.getPageNumbers()).isEqualTo("all");
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/filter/PageSizeRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/filter/PageSizeRequestTest.java
index ca741c230f..9b8215bd3c 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/filter/PageSizeRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/filter/PageSizeRequestTest.java
@@ -21,11 +21,11 @@ class PageSizeRequestTest {
class Defaults {
@Test
- @DisplayName("standardPageSize and inherited comparator null on a fresh instance")
+ @DisplayName("standardPageSize defaults to A4 and inherited comparator is null")
void defaultValues() {
PageSizeRequest req = new PageSizeRequest();
- assertThat(req.getStandardPageSize()).isNull();
+ assertThat(req.getStandardPageSize()).isEqualTo("A4");
assertThat(req.getComparator()).isNull();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/general/CropPdfFormTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/general/CropPdfFormTest.java
index 2cb2ce12bc..ebaa36596f 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/general/CropPdfFormTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/general/CropPdfFormTest.java
@@ -79,11 +79,11 @@ class CropPdfFormTest {
class PageSelection {
@Test
- @DisplayName("null pageNumbers falls back to every page")
+ @DisplayName("omitted pageNumbers defaults to every page")
void nullPageNumbersMeansAllPages() throws IOException {
try (PDDocument doc = threePageDoc()) {
CropPdfForm form = new CropPdfForm();
- assertThat(form.getPageNumbers()).isNull();
+ assertThat(form.getPageNumbers()).isEqualTo("all");
assertThat(form.getPageNumbersList(doc, false)).containsExactly(0, 1, 2);
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/general/MergeMultiplePagesRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/general/MergeMultiplePagesRequestTest.java
index 1571f1a1a6..b4a3880805 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/general/MergeMultiplePagesRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/general/MergeMultiplePagesRequestTest.java
@@ -21,23 +21,23 @@ class MergeMultiplePagesRequestTest {
class Defaults {
@Test
- @DisplayName("pagesPerSheet defaults to 2 and other fields null/zero")
+ @DisplayName("fields default to their documented values")
void defaultValues() {
MergeMultiplePagesRequest req = new MergeMultiplePagesRequest();
assertThat(req.getPagesPerSheet()).isEqualTo(2);
- assertThat(req.getMode()).isNull();
- assertThat(req.getArrangement()).isNull();
- assertThat(req.getReadingDirection()).isNull();
- assertThat(req.getRows()).isZero();
- assertThat(req.getCols()).isZero();
- assertThat(req.getOrientation()).isNull();
+ assertThat(req.getMode()).isEqualTo("DEFAULT");
+ assertThat(req.getArrangement()).isEqualTo("BY_ROWS");
+ assertThat(req.getReadingDirection()).isEqualTo("LTR");
+ assertThat(req.getRows()).isEqualTo(1);
+ assertThat(req.getCols()).isEqualTo(2);
+ assertThat(req.getOrientation()).isEqualTo("PORTRAIT");
assertThat(req.getInnerMargin()).isZero();
assertThat(req.getTopMargin()).isZero();
assertThat(req.getBottomMargin()).isZero();
assertThat(req.getLeftMargin()).isZero();
assertThat(req.getRightMargin()).isZero();
- assertThat(req.getBorderWidth()).isZero();
+ assertThat(req.getBorderWidth()).isEqualTo(1);
assertThat(req.getAddBorder()).isNull();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/general/MergePdfsRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/general/MergePdfsRequestTest.java
index 513f97ac9b..74b0a2d93e 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/general/MergePdfsRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/general/MergePdfsRequestTest.java
@@ -23,13 +23,13 @@ class MergePdfsRequestTest {
class Defaults {
@Test
- @DisplayName("sortType defaults to orderProvided, generateToc false, others null")
+ @DisplayName("sortType defaults to orderProvided, generateToc false, removeCertSign true")
void defaultValues() {
MergePdfsRequest req = new MergePdfsRequest();
assertThat(req.getSortType()).isEqualTo("orderProvided");
assertThat(req.isGenerateToc()).isFalse();
- assertThat(req.getRemoveCertSign()).isNull();
+ assertThat(req.getRemoveCertSign()).isTrue();
assertThat(req.getClientFileIds()).isNull();
assertThat(req.getFileInput()).isNull();
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/general/RearrangePagesRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/general/RearrangePagesRequestTest.java
index 36f8b832de..867c996be7 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/general/RearrangePagesRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/general/RearrangePagesRequestTest.java
@@ -26,7 +26,7 @@ class RearrangePagesRequestTest {
RearrangePagesRequest req = new RearrangePagesRequest();
assertThat(req.getCustomMode()).isNull();
- assertThat(req.getPageNumbers()).isNull();
+ assertThat(req.getPageNumbers()).isEqualTo("all");
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/general/ScalePagesRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/general/ScalePagesRequestTest.java
index 8355d4a5c6..e8acf47f65 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/general/ScalePagesRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/general/ScalePagesRequestTest.java
@@ -21,13 +21,13 @@ class ScalePagesRequestTest {
class Defaults {
@Test
- @DisplayName("scaleFactor zero and inherited orientation PORTRAIT")
+ @DisplayName("scaleFactor 1, page size KEEP and orientation PORTRAIT, matching the UI")
void defaultValues() {
ScalePagesRequest req = new ScalePagesRequest();
- assertThat(req.getScaleFactor()).isEqualTo(0f);
+ assertThat(req.getScaleFactor()).isEqualTo(1f);
assertThat(req.getOrientation()).isEqualTo("PORTRAIT");
- assertThat(req.getPageSize()).isNull();
+ assertThat(req.getPageSize()).isEqualTo("KEEP");
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/general/SplitPdfBySizeOrCountRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/general/SplitPdfBySizeOrCountRequestTest.java
index 0fe7696271..3c2ccbd84f 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/general/SplitPdfBySizeOrCountRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/general/SplitPdfBySizeOrCountRequestTest.java
@@ -21,12 +21,12 @@ class SplitPdfBySizeOrCountRequestTest {
class Defaults {
@Test
- @DisplayName("splitType zero and splitValue null on a fresh instance")
+ @DisplayName("splitType zero and splitValue 10MB on a fresh instance")
void defaultValues() {
SplitPdfBySizeOrCountRequest req = new SplitPdfBySizeOrCountRequest();
assertThat(req.getSplitType()).isZero();
- assertThat(req.getSplitValue()).isNull();
+ assertThat(req.getSplitValue()).isEqualTo("10MB");
assertThat(req.getFileInput()).isNull();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AddPageNumbersRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AddPageNumbersRequestTest.java
index 0469a154d8..4d67799cf9 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AddPageNumbersRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AddPageNumbersRequestTest.java
@@ -19,13 +19,13 @@ class AddPageNumbersRequestTest {
AddPageNumbersRequest req = new AddPageNumbersRequest();
assertThat(req.getZeroPad()).isZero();
assertThat(req.getPosition()).isEqualTo(8);
- assertThat(req.getStartingNumber()).isZero();
- assertThat(req.getFontSize()).isEqualTo(0f);
- assertThat(req.getCustomMargin()).isNull();
+ assertThat(req.getStartingNumber()).isEqualTo(1);
+ assertThat(req.getFontSize()).isEqualTo(12f);
+ assertThat(req.getCustomMargin()).isEqualTo("medium");
assertThat(req.getFontType()).isNull();
- assertThat(req.getFontColor()).isNull();
- assertThat(req.getPagesToNumber()).isNull();
- assertThat(req.getCustomText()).isNull();
+ assertThat(req.getFontColor()).isEqualTo("#000000");
+ assertThat(req.getPagesToNumber()).isEqualTo("all");
+ assertThat(req.getCustomText()).isEqualTo("{n}");
}
}
@@ -94,7 +94,7 @@ class AddPageNumbersRequestTest {
void differByInheritedField() {
AddPageNumbersRequest a = new AddPageNumbersRequest();
AddPageNumbersRequest b = new AddPageNumbersRequest();
- b.setPageNumbers("all");
+ b.setPageNumbers("1-3");
assertThat(a).isNotEqualTo(b);
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AddStampRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AddStampRequestTest.java
index 97c1ece055..27f771e3e3 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AddStampRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AddStampRequestTest.java
@@ -23,14 +23,14 @@ class AddStampRequestTest {
assertThat(req.getStampType()).isNull();
assertThat(req.getStampText()).isNull();
assertThat(req.getStampImage()).isNull();
- assertThat(req.getFontSize()).isEqualTo(0f);
+ assertThat(req.getFontSize()).isEqualTo(40f);
assertThat(req.getRotation()).isEqualTo(0f);
- assertThat(req.getOpacity()).isEqualTo(0f);
- assertThat(req.getPosition()).isZero();
- assertThat(req.getOverrideX()).isEqualTo(0f);
- assertThat(req.getOverrideY()).isEqualTo(0f);
- assertThat(req.getCustomMargin()).isNull();
- assertThat(req.getCustomColor()).isNull();
+ assertThat(req.getOpacity()).isEqualTo(0.5f);
+ assertThat(req.getPosition()).isEqualTo(5);
+ assertThat(req.getOverrideX()).isEqualTo(-1f);
+ assertThat(req.getOverrideY()).isEqualTo(-1f);
+ assertThat(req.getCustomMargin()).isEqualTo("medium");
+ assertThat(req.getCustomColor()).isEqualTo("#d3d3d3");
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AutoSplitPdfRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AutoSplitPdfRequestTest.java
index 484be4dc49..2503c0189a 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AutoSplitPdfRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/AutoSplitPdfRequestTest.java
@@ -14,9 +14,9 @@ class AutoSplitPdfRequestTest {
class Defaults {
@Test
- @DisplayName("duplexMode defaults to null")
- void duplexModeDefaultsNull() {
- assertThat(new AutoSplitPdfRequest().getDuplexMode()).isNull();
+ @DisplayName("duplexMode defaults to false")
+ void duplexModeDefaultsFalse() {
+ assertThat(new AutoSplitPdfRequest().getDuplexMode()).isFalse();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ExtractHeaderRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ExtractHeaderRequestTest.java
index 65459c8cdd..5545bdb4e2 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ExtractHeaderRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ExtractHeaderRequestTest.java
@@ -14,9 +14,9 @@ class ExtractHeaderRequestTest {
class Defaults {
@Test
- @DisplayName("useFirstTextAsFallback defaults to null")
- void useFirstTextAsFallbackDefaultsNull() {
- assertThat(new ExtractHeaderRequest().getUseFirstTextAsFallback()).isNull();
+ @DisplayName("useFirstTextAsFallback defaults to false")
+ void useFirstTextAsFallbackDefaultsFalse() {
+ assertThat(new ExtractHeaderRequest().getUseFirstTextAsFallback()).isFalse();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ExtractImageScansRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ExtractImageScansRequestTest.java
index d457e11d84..856e1c587b 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ExtractImageScansRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ExtractImageScansRequestTest.java
@@ -16,15 +16,15 @@ class ExtractImageScansRequestTest {
class Defaults {
@Test
- @DisplayName("primitive int fields default to 0 and fileInput to null")
+ @DisplayName("int fields default to the documented values and fileInput to null")
void primitiveDefaults() {
ExtractImageScansRequest req = new ExtractImageScansRequest();
assertThat(req.getFileInput()).isNull();
- assertThat(req.getAngleThreshold()).isZero();
- assertThat(req.getTolerance()).isZero();
- assertThat(req.getMinArea()).isZero();
- assertThat(req.getMinContourArea()).isZero();
- assertThat(req.getBorderSize()).isZero();
+ assertThat(req.getAngleThreshold()).isEqualTo(10);
+ assertThat(req.getTolerance()).isEqualTo(30);
+ assertThat(req.getMinArea()).isEqualTo(10000);
+ assertThat(req.getMinContourArea()).isEqualTo(500);
+ assertThat(req.getBorderSize()).isEqualTo(1);
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/FlattenRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/FlattenRequestTest.java
index c155c0422a..58e689682e 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/FlattenRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/FlattenRequestTest.java
@@ -14,10 +14,10 @@ class FlattenRequestTest {
class Defaults {
@Test
- @DisplayName("flattenOnlyForms and renderDpi default to null")
+ @DisplayName("flattenOnlyForms defaults to false and renderDpi to null")
void defaultsNull() {
FlattenRequest req = new FlattenRequest();
- assertThat(req.getFlattenOnlyForms()).isNull();
+ assertThat(req.getFlattenOnlyForms()).isFalse();
assertThat(req.getRenderDpi()).isNull();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/MetadataRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/MetadataRequestTest.java
index d1732e6e7d..403f6968d9 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/MetadataRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/MetadataRequestTest.java
@@ -16,10 +16,10 @@ class MetadataRequestTest {
class Defaults {
@Test
- @DisplayName("all fields default to null on a fresh instance")
+ @DisplayName("deleteAll defaults to false and all other fields to null")
void defaultsNull() {
MetadataRequest req = new MetadataRequest();
- assertThat(req.getDeleteAll()).isNull();
+ assertThat(req.getDeleteAll()).isFalse();
assertThat(req.getAuthor()).isNull();
assertThat(req.getCreationDate()).isNull();
assertThat(req.getCreator()).isNull();
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/OverlayImageRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/OverlayImageRequestTest.java
index f084a7b8b0..6f8b9aed0d 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/OverlayImageRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/OverlayImageRequestTest.java
@@ -22,7 +22,7 @@ class OverlayImageRequestTest {
assertThat(req.getImageFile()).isNull();
assertThat(req.getX()).isEqualTo(0f);
assertThat(req.getY()).isEqualTo(0f);
- assertThat(req.getEveryPage()).isNull();
+ assertThat(req.getEveryPage()).isFalse();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ProcessPdfWithOcrRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ProcessPdfWithOcrRequestTest.java
index 5cdbbbda23..77ce614e9f 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ProcessPdfWithOcrRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ProcessPdfWithOcrRequestTest.java
@@ -20,12 +20,12 @@ class ProcessPdfWithOcrRequestTest {
void documentedDefaults() {
ProcessPdfWithOcrRequest req = new ProcessPdfWithOcrRequest();
assertThat(req.getOcrRenderType()).isEqualTo("hocr");
- assertThat(req.getLanguages()).isNull();
+ assertThat(req.getLanguages()).containsExactly("eng");
assertThat(req.isSidecar()).isFalse();
assertThat(req.isDeskew()).isFalse();
assertThat(req.isClean()).isFalse();
assertThat(req.isCleanFinal()).isFalse();
- assertThat(req.getOcrType()).isNull();
+ assertThat(req.getOcrType()).isEqualTo("skip-text");
assertThat(req.isRemoveImagesAfter()).isFalse();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/RemoveBlankPagesRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/RemoveBlankPagesRequestTest.java
index 77df31eec7..b8eb50ac5c 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/RemoveBlankPagesRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/RemoveBlankPagesRequestTest.java
@@ -14,11 +14,11 @@ class RemoveBlankPagesRequestTest {
class Defaults {
@Test
- @DisplayName("primitive fields default to zero on a fresh instance")
- void defaultsZero() {
+ @DisplayName("fields default to the documented values on a fresh instance")
+ void defaultsMatchSchema() {
RemoveBlankPagesRequest req = new RemoveBlankPagesRequest();
- assertThat(req.getThreshold()).isZero();
- assertThat(req.getWhitePercent()).isEqualTo(0f);
+ assertThat(req.getThreshold()).isEqualTo(10);
+ assertThat(req.getWhitePercent()).isEqualTo(99.9f);
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ReplaceAndInvertColorRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ReplaceAndInvertColorRequestTest.java
index 0c19914117..2e9d0f86b7 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ReplaceAndInvertColorRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/misc/ReplaceAndInvertColorRequestTest.java
@@ -17,11 +17,13 @@ class ReplaceAndInvertColorRequestTest {
class Defaults {
@Test
- @DisplayName("all fields default to null on a fresh instance")
- void defaultsNull() {
+ @DisplayName("options default to the documented values, colors to null")
+ void defaultsMatchSchema() {
ReplaceAndInvertColorRequest req = new ReplaceAndInvertColorRequest();
- assertThat(req.getReplaceAndInvertOption()).isNull();
- assertThat(req.getHighContrastColorCombination()).isNull();
+ assertThat(req.getReplaceAndInvertOption())
+ .isEqualTo(ReplaceAndInvert.HIGH_CONTRAST_COLOR);
+ assertThat(req.getHighContrastColorCombination())
+ .isEqualTo(HighContrastColorCombination.WHITE_TEXT_ON_BLACK);
assertThat(req.getBackGroundColor()).isNull();
assertThat(req.getTextColor()).isNull();
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddPasswordRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddPasswordRequestTest.java
index 55639f3863..f3d0c3bd65 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddPasswordRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddPasswordRequestTest.java
@@ -15,20 +15,20 @@ class AddPasswordRequestTest {
class Defaults {
@Test
- @DisplayName("keyLength defaults to 256 and permission flags are null")
+ @DisplayName("keyLength defaults to 256 and permission flags are false")
void defaults() {
AddPasswordRequest req = new AddPasswordRequest();
assertThat(req.getKeyLength()).isEqualTo(256);
assertThat(req.getOwnerPassword()).isNull();
assertThat(req.getPassword()).isNull();
- assertThat(req.getPreventAssembly()).isNull();
- assertThat(req.getPreventExtractContent()).isNull();
- assertThat(req.getPreventExtractForAccessibility()).isNull();
- assertThat(req.getPreventFillInForm()).isNull();
- assertThat(req.getPreventModify()).isNull();
- assertThat(req.getPreventModifyAnnotations()).isNull();
- assertThat(req.getPreventPrinting()).isNull();
- assertThat(req.getPreventPrintingFaithful()).isNull();
+ assertThat(req.getPreventAssembly()).isFalse();
+ assertThat(req.getPreventExtractContent()).isFalse();
+ assertThat(req.getPreventExtractForAccessibility()).isFalse();
+ assertThat(req.getPreventFillInForm()).isFalse();
+ assertThat(req.getPreventModify()).isFalse();
+ assertThat(req.getPreventModifyAnnotations()).isFalse();
+ assertThat(req.getPreventPrinting()).isFalse();
+ assertThat(req.getPreventPrintingFaithful()).isFalse();
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddWatermarkRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddWatermarkRequestTest.java
new file mode 100644
index 0000000000..f41e436f13
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddWatermarkRequestTest.java
@@ -0,0 +1,45 @@
+package stirling.software.SPDF.model.api.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+
+@DisplayName("AddWatermarkRequest")
+class AddWatermarkRequestTest {
+
+ private static Validator validator;
+
+ @BeforeAll
+ static void setupValidator() {
+ validator = Validation.buildDefaultValidatorFactory().getValidator();
+ }
+
+ @Test
+ @DisplayName("defaults match what the web UI sends")
+ void defaultsMatchUi() {
+ AddWatermarkRequest req = new AddWatermarkRequest();
+ assertThat(req.getWatermarkType()).isNull();
+ assertThat(req.getAlphabet()).isEqualTo("roman");
+ assertThat(req.getFontSize()).isEqualTo(12f);
+ assertThat(req.getRotation()).isEqualTo(0f);
+ assertThat(req.getOpacity()).isEqualTo(0.5f);
+ assertThat(req.getWidthSpacer()).isEqualTo(50);
+ assertThat(req.getHeightSpacer()).isEqualTo(50);
+ assertThat(req.getCustomColor()).isEqualTo("#d3d3d3");
+ assertThat(req.getConvertPDFToImage()).isFalse();
+ }
+
+ @Test
+ @DisplayName("a request with only watermarkText passes bean validation")
+ void textOnlyRequestIsValid() {
+ AddWatermarkRequest req = new AddWatermarkRequest();
+ req.setFileId("file-1");
+ req.setWatermarkText("TEST");
+ assertThat(validator.validate(req)).isEmpty();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ClassifyLabelController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ClassifyLabelController.java
index dc422433f0..0e1fed2972 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ClassifyLabelController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ClassifyLabelController.java
@@ -7,6 +7,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
@@ -38,10 +39,13 @@ import stirling.software.proprietary.classification.model.ClassificationLabel;
import stirling.software.proprietary.model.api.ai.AiPageText;
import stirling.software.proprietary.service.AiEngineClient;
import stirling.software.proprietary.service.AiFeatureGate;
+import stirling.software.proprietary.service.AiToolResponseHeaders;
import stirling.software.proprietary.service.PdfContentExtractor;
+import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ArrayNode;
import tools.jackson.databind.node.ObjectNode;
/**
@@ -106,12 +110,17 @@ public class ClassifyLabelController {
// PDF in, the same PDF out with a verdict on it, so a chain can be checked across this step.
@ToolIO(accepts = ToolFormat.PDF, produces = ToolFormat.PDF)
@Operation(
- summary = "Classify a PDF and label its metadata",
+ summary =
+ "Classify a PDF (invoice, receipt, contract...), store the labels in its"
+ + " metadata and return them",
description =
"Reads the first two and last two pages, classifies the document via the AI"
- + " engine, and stores the result in the StirlingPDFClassification"
- + " metadata field. A document that already carries a verdict is"
- + " passed through untouched unless reclassify=true.")
+ + " engine against the built-in label set, and stores the result in"
+ + " the StirlingPDFClassification metadata field. The label ids are"
+ + " also returned in the X-Stirling-Tool-Report header, e.g."
+ + " {\"labels\":[\"invoice\"]}. A document that already carries a"
+ + " verdict is passed through untouched unless reclassify=true; its"
+ + " stored labels are reported with alreadyClassified=true.")
public ResponseEntity<Resource> classifyAndLabel(
@RequestParam("fileInput") MultipartFile fileInput,
@RequestParam(value = "reclassify", defaultValue = "false") boolean reclassify)
@@ -125,7 +134,10 @@ public class ClassifyLabelController {
// that already carries a verdict has nothing new to learn. A pipeline can run this
// step over a mixed batch without paying for the ones already done.
log.debug("[classify-and-label] {} already classified; passing through", fileName);
- return WebResponseUtils.pdfDocToWebResponse(document, fileName, tempFileManager);
+ String report = storedVerdictReport(document);
+ return withReport(
+ WebResponseUtils.pdfDocToWebResponse(document, fileName, tempFileManager),
+ report);
}
List<EngineLabel> allowed = resolveAllowedLabels();
@@ -144,10 +156,13 @@ public class ClassifyLabelController {
String userId = userService != null ? userService.getCurrentUsername() : null;
String responseJson = aiEngineClient.post(CLASSIFY_ENDPOINT, requestBody, userId);
- pdfMetadataService.setClassificationMetadata(document, toMetadataValue(responseJson));
+ String verdict = toMetadataValue(responseJson);
+ pdfMetadataService.setClassificationMetadata(document, verdict);
log.debug("[classify-and-label] labelled {} ({} window pages)", fileName, pages.size());
- return WebResponseUtils.pdfDocToWebResponse(document, fileName, tempFileManager);
+ return withReport(
+ WebResponseUtils.pdfDocToWebResponse(document, fileName, tempFileManager),
+ verdict);
}
}
@@ -170,6 +185,36 @@ public class ClassifyLabelController {
return existing != null && !existing.isBlank();
}
+ /** Echoes only known label ids: the stored value is whatever metadata the file arrived with. */
+ private String storedVerdictReport(PDDocument document) {
+ Set<String> known =
+ resolveAllowedLabels().stream().map(EngineLabel::id).collect(Collectors.toSet());
+ ObjectNode report = objectMapper.createObjectNode();
+ report.put("alreadyClassified", true);
+ ArrayNode labels = report.putArray("labels");
+ String stored =
+ document.getDocumentInformation()
+ .getCustomMetadataValue(PdfMetadataService.CLASSIFICATION_KEY);
+ try {
+ for (JsonNode label : objectMapper.readTree(stored).path("labels")) {
+ if (label.isTextual() && known.contains(label.asString())) {
+ labels.add(label.asString());
+ }
+ }
+ } catch (JacksonException e) {
+ log.debug("[classify-and-label] stored verdict is not JSON: {}", e.getMessage());
+ }
+ return objectMapper.writeValueAsString(report);
+ }
+
+ private static ResponseEntity<Resource> withReport(
+ ResponseEntity<Resource> response, String report) {
+ return ResponseEntity.status(response.getStatusCode())
+ .headers(response.getHeaders())
+ .header(AiToolResponseHeaders.TOOL_REPORT, report)
+ .body(response.getBody());
+ }
+
private List<AiPageText> extractWindow(PDDocument document) throws IOException {
List<AiPageText> pages = new ArrayList<>();
for (int pageNumber : windowPageNumbers(document.getNumberOfPages(), WINDOW_PAGES)) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/CreatePdfAgentController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/CreatePdfAgentController.java
index 0a41c552aa..4828e98664 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/CreatePdfAgentController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/CreatePdfAgentController.java
@@ -20,6 +20,7 @@ import org.springframework.web.server.ResponseStatusException;
import io.github.pixee.security.Filenames;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
@@ -54,6 +55,11 @@ import tools.jackson.databind.ObjectMapper;
@Tag(name = "AI Tools", description = "Dispatchable AI-backed tools.")
public class CreatePdfAgentController {
+ private static final String BAD_DOCUMENT_REASON =
+ "document must be JSON, not HTML or plain text: {title, sections: [{type:"
+ + " text|key_value|line_items|bullet_list|signature, heading?, body?, pairs?,"
+ + " columns?, rows?, totalRow?, items?, signatories?}]}";
+
private final TempFileManager tempFileManager;
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final RuntimePathConfig runtimePathConfig;
@@ -87,13 +93,31 @@ public class CreatePdfAgentController {
value = "/create-pdf-from-html-agent",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
- summary = "Convert an AI-generated document to a PDF",
+ summary =
+ "Lay out a designed PDF (invoice, letter, report) from a JSON document; no"
+ + " input file",
description =
- "Accepts a structured document as a JSON parameter and returns a PDF. This"
- + " endpoint is dispatched by the AI workflow orchestrator as a plan"
- + " step; it is not intended for direct client use.")
+ "Renders the structured document given as JSON in the document parameter (not"
+ + " HTML or plain text) through a fixed template and returns a PDF."
+ + " Dispatched by the AI workflow orchestrator as a plan step.")
public ResponseEntity<Resource> createPdf(
- @RequestParam("document") String document, @RequestParam("filename") String filename)
+ @Parameter(
+ description =
+ "JSON text, not HTML: {title, subtitle?, referenceNumber?,"
+ + " style?: {primaryColor, backgroundColor,"
+ + " bodyTextColor}, sections: [{type, heading?,"
+ + " ...}]} where type is text (body), key_value"
+ + " (pairs: [[k,v]]), line_items (columns, rows:"
+ + " [[...]], totalRow?), bullet_list (items) or"
+ + " signature (signatories)")
+ @RequestParam("document")
+ String document,
+ @Parameter(
+ description =
+ "Name for the PDF, e.g. invoice-1042.pdf. Must end in .pdf,"
+ + " otherwise generated-document.pdf is used.")
+ @RequestParam("filename")
+ String filename)
throws Exception {
if (!applicationProperties.getAiEngine().isEnabled()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
@@ -104,7 +128,7 @@ public class CreatePdfAgentController {
try {
model = objectMapper.readValue(document, AiDocument.class);
} catch (JacksonException e) {
- throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, BAD_DOCUMENT_REASON);
}
String html = htmlRenderer.render(model);
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/converters/ConvertPdfToPdfUa.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/converters/ConvertPdfToPdfUa.java
index 7f5241388f..c28ce3fd07 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/converters/ConvertPdfToPdfUa.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/converters/ConvertPdfToPdfUa.java
@@ -82,7 +82,7 @@ public class ConvertPdfToPdfUa {
// Only used when the document declares no language of its own.
.language(
request.getLanguage() == null || request.getLanguage().isBlank()
- ? "en-GB"
+ ? "en-US"
: request.getLanguage())
.overrideLanguage(
request.getOverrideLanguage() != null
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/converters/PdfToPdfUaRequest.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/converters/PdfToPdfUaRequest.java
index 8981398001..eeede01d0c 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/converters/PdfToPdfUaRequest.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/converters/PdfToPdfUaRequest.java
@@ -15,7 +15,7 @@ public class PdfToPdfUaRequest extends PDFFile {
description = "PDF/UA conformance level to target",
defaultValue = "ua1",
allowableValues = {"ua1", "ua2"})
- private String profile;
+ private String profile = "ua1";
@Schema(
description =
@@ -25,18 +25,18 @@ public class PdfToPdfUaRequest extends PDFFile {
@Schema(
description =
- "Document language as a BCP-47 tag, for example en-GB. Applied only when the"
+ "Document language as a BCP-47 tag, for example en-US. Applied only when the"
+ " document does not already declare one, unless overrideLanguage is"
+ " set.",
- defaultValue = "en-GB")
- private String language;
+ defaultValue = "en-US")
+ private String language = "en-US";
@Schema(
description =
"Replace the language the document already declares. Off by default, so a"
+ " document is never relabelled into a language it is not written in.",
defaultValue = "false")
- private Boolean overrideLanguage;
+ private Boolean overrideLanguage = false;
@Schema(
description =
@@ -44,7 +44,7 @@ public class PdfToPdfUaRequest extends PDFFile {
+ " automatically",
defaultValue = "auto",
allowableValues = {"auto", "keep", "rebuild"})
- private String existingTags;
+ private String existingTags = "auto";
@Schema(
description =
@@ -53,14 +53,14 @@ public class PdfToPdfUaRequest extends PDFFile {
+ " decoration.",
defaultValue = "require-alt",
allowableValues = {"require-alt", "mark-decorative"})
- private String figurePolicy;
+ private String figurePolicy = "require-alt";
@Schema(
description =
"Embed fonts the document references but does not carry. Required for"
+ " conformance and needs Ghostscript.",
defaultValue = "true")
- private Boolean embedFonts;
+ private Boolean embedFonts = true;
@Schema(
description =
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityReportRequest.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityReportRequest.java
index 178d2637b2..2a14ef9327 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityReportRequest.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityReportRequest.java
@@ -15,5 +15,5 @@ public class AccessibilityReportRequest extends PDFFile {
description = "Profile to check against",
defaultValue = "ua1",
allowableValues = {"ua1", "ua2"})
- private String profile;
+ private String profile = "ua1";
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/TaggingOptions.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/TaggingOptions.java
index bba15ed09f..bc9baa862a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/TaggingOptions.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/TaggingOptions.java
@@ -30,7 +30,7 @@ public class TaggingOptions {
@Builder.Default private PdfUaProfile profile = PdfUaProfile.UA1;
- /** BCP-47 language tag for the document, for example {@code en-GB}. */
+ /** BCP-47 language tag for the document, for example {@code en-US}. */
private String language;
/** Replace a language the document already declares. Off, so a French file stays French. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
index 4bc60f1e0c..d9af06d8fd 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
@@ -764,6 +764,7 @@ public class PolicyController {
// Steps get the same treatment as the output, and for the same reason: an integration
// step dereferences its connection by id on a principal-less worker thread, so this
// request thread is the only place that reference can be checked against the caller.
+ policyValidator.validateRunnableSteps(definition.steps());
policyValidator.validateSteps(definition.steps());
// Every destination is checked; an ad-hoc run with no destinations validates nothing.
for (OutputSpec output : definition.outputs()) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
index f12fe290ad..e2dec05c4c 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
@@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.function.Predicate;
import org.springframework.stereotype.Service;
@@ -67,6 +68,7 @@ public class PolicyValidator {
if (policy.outputIds().size() > 1) {
throw new IllegalArgumentException("a policy supports at most one output");
}
+ validateStepCount(policy.steps());
for (PipelineInput input : policy.inputs()) {
Source source =
sourceStore
@@ -181,20 +183,49 @@ public class PolicyValidator {
*
* <p>Only errors block; warnings depend on configuration or file content.
*
- * @throws IllegalArgumentException if any step cannot accept what the one before it produces
+ * @throws IllegalArgumentException if any step names an unknown operation or cannot accept what
+ * the one before it produces
*/
public void validateChain(List<PipelineStep> steps) {
List<ToolDiagnostic> diagnostics = diagnoseChain(steps, null);
+ requireKnownOperations(diagnostics);
if (!ToolChainValidator.hasErrors(diagnostics)) {
return;
}
- String reasons =
- diagnostics.stream()
- .filter(d -> d.severity() == ToolDiagnostic.Severity.ERROR)
- .map(d -> "step " + (d.stepIndex() + 1) + ": " + d.message())
- .reduce((a, b) -> a + "; " + b)
- .orElse("");
- throw new IllegalArgumentException("pipeline steps cannot run in this order - " + reasons);
+ throw new IllegalArgumentException(
+ "pipeline steps cannot run in this order - "
+ + describeErrors(diagnostics, d -> true));
+ }
+
+ /**
+ * Ad-hoc gate: the step cap and known operations only; format mismatches are left to the run.
+ */
+ public void validateRunnableSteps(List<PipelineStep> steps) {
+ validateStepCount(steps);
+ requireKnownOperations(diagnoseChain(steps, null));
+ }
+
+ /** Rejects more steps than {@code policies.maxSteps}, where 0 or less means no cap. */
+ public void validateStepCount(List<PipelineStep> steps) {
+ PipelineLimits.requireWithinStepLimit(steps.size(), applicationProperties.getPolicies());
+ }
+
+ private static void requireKnownOperations(List<ToolDiagnostic> diagnostics) {
+ String unknown =
+ describeErrors(diagnostics, d -> ToolDiagnostic.UNKNOWN_OPERATION.equals(d.code()));
+ if (!unknown.isEmpty()) {
+ throw new IllegalArgumentException("pipeline cannot run - " + unknown);
+ }
+ }
+
+ private static String describeErrors(
+ List<ToolDiagnostic> diagnostics, Predicate<ToolDiagnostic> filter) {
+ return diagnostics.stream()
+ .filter(d -> d.severity() == ToolDiagnostic.Severity.ERROR)
+ .filter(filter)
+ .map(d -> "step " + (d.stepIndex() + 1) + ": " + d.message())
+ .reduce((a, b) -> a + "; " + b)
+ .orElse("");
}
/**
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
index 887f247bfe..1c51dc71f2 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
@@ -275,6 +275,7 @@ class PolicyControllerTest {
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);
assertThat(response.getBody().getJobId()).isEqualTo("run-1");
+ verify(policyValidator).validateRunnableSteps(definitionWithStep().steps());
}
@Test
@@ -370,6 +371,24 @@ class PolicyControllerTest {
.isEqualTo(HttpStatus.BAD_REQUEST));
}
+ @Test
+ @DisplayName("rejects unknown operations or too many steps before anything runs")
+ void rejectsUnrunnableSteps() {
+ doThrow(new IllegalArgumentException("pipeline cannot run - step 1: Unknown operation"))
+ .when(policyValidator)
+ .validateRunnableSteps(any());
+
+ assertThatThrownBy(() -> controller.run(requestWithStep(), null, new PolicyRunFiles()))
+ .isInstanceOf(ResponseStatusException.class)
+ .satisfies(
+ e -> {
+ ResponseStatusException rse = (ResponseStatusException) e;
+ assertThat(rse.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
+ assertThat(rse.getReason()).contains("Unknown operation");
+ });
+ verify(policyRunner, never()).runAdHoc(any(), any(), any());
+ }
+
@Test
@DisplayName("rejects an ad-hoc output the caller cannot use, on the request thread")
void rejectsUnauthorizedAdHocOutput() {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
index baaa3a4ce0..f93f8b07e5 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
@@ -199,7 +199,7 @@ class ProcessingFolderControllerTest {
sourceStore,
assetStore,
toolChainValidator,
- new ApplicationProperties());
+ properties);
controller =
new ProcessingFolderController(
policyStore,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
index c577c80540..0d38ba759d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
@@ -59,7 +59,7 @@ class PolicyValidatorTest {
private final SourceStore sourceStore = new InProcessSourceStore();
private final PolicyAssetStore assetStore = new InProcessPolicyAssetStore();
- private final ApplicationProperties props = new ApplicationProperties();
+ private final ApplicationProperties properties = new ApplicationProperties();
private PolicyValidator validator;
@BeforeEach
@@ -73,7 +73,7 @@ class PolicyValidatorTest {
sourceStore,
assetStore,
new ToolChainValidator(path -> java.util.Optional.empty()),
- props);
+ properties);
}
@ParameterizedTest
@@ -333,8 +333,144 @@ class PolicyValidatorTest {
verify(outputSink).validate(any());
}
+ @Test
+ void rejectsAStepWhoseOperationIsUnknown() {
+ when(inputSource.supports(any())).thenReturn(true);
+ PolicyValidator strict = validatorWith(KNOWS_REAL_ENDPOINTS);
+
+ IllegalArgumentException ex =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> strict.validate(withSteps(ROTATE, "/api/v1/misc/no-such-tool")));
+
+ assertTrue(ex.getMessage().contains("step 2"), ex.getMessage());
+ assertTrue(ex.getMessage().contains("/api/v1/misc/no-such-tool"), ex.getMessage());
+ }
+
+ @Test
+ void rejectsAStepWithNoOperation() {
+ when(inputSource.supports(any())).thenReturn(true);
+ PolicyValidator strict = validatorWith(KNOWS_REAL_ENDPOINTS);
+
+ IllegalArgumentException ex =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> strict.validate(withSteps(ROTATE, " ")));
+
+ assertTrue(ex.getMessage().contains("step 2"), ex.getMessage());
+ }
+
+ @Test
+ void acceptsAiIntegrationDocparseAndUndeclaredSteps() {
+ // Undeclared steps only warn: they run, their output just cannot be checked.
+ when(inputSource.supports(any())).thenReturn(true);
+ when(outputSink.supports(any())).thenReturn(true);
+ PolicyValidator strict = validatorWith(KNOWS_REAL_ENDPOINTS);
+
+ strict.validate(withSteps(CLASSIFY, ROTATE, EXTERNAL_API, COMPRESS, DOCPARSE));
+
+ verify(outputSink).validate(any());
+ }
+
+ @Test
+ void rejectsMoreStepsThanTheConfiguredCap() {
+ properties.getPolicies().setMaxSteps(3);
+
+ IllegalArgumentException ex =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> validator.validate(withSteps(ROTATE, ROTATE, ROTATE, ROTATE)));
+
+ assertTrue(ex.getMessage().contains("at most 3 steps"), ex.getMessage());
+ }
+
+ @Test
+ void capsStepsAtFiftyByDefault() {
+ String[] fiftyOne = java.util.Collections.nCopies(51, ROTATE).toArray(String[]::new);
+
+ IllegalArgumentException ex =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> validator.validate(withSteps(fiftyOne)));
+
+ assertTrue(ex.getMessage().contains("at most 50 steps"), ex.getMessage());
+ }
+
+ @Test
+ void acceptsExactlyTheCap() {
+ properties.getPolicies().setMaxSteps(2);
+ when(inputSource.supports(any())).thenReturn(true);
+ when(outputSink.supports(any())).thenReturn(true);
+
+ validator.validate(withSteps(ROTATE, ROTATE));
+ }
+
+ @Test
+ void zeroLiftsTheCap() {
+ properties.getPolicies().setMaxSteps(0);
+ String[] many = java.util.Collections.nCopies(60, ROTATE).toArray(String[]::new);
+
+ validator.validateRunnableSteps(withSteps(many).steps());
+ }
+
+ @Test
+ void adHocStepsRejectAnUnknownOperation() {
+ PolicyValidator strict = validatorWith(KNOWS_REAL_ENDPOINTS);
+
+ IllegalArgumentException ex =
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ strict.validateRunnableSteps(
+ withSteps("/api/v1/misc/no-such-tool").steps()));
+
+ assertTrue(ex.getMessage().contains("step 1"), ex.getMessage());
+ assertTrue(ex.getMessage().contains("/api/v1/misc/no-such-tool"), ex.getMessage());
+ }
+
+ @Test
+ void adHocStepsRejectMoreThanTheCap() {
+ properties.getPolicies().setMaxSteps(1);
+
+ IllegalArgumentException ex =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> validator.validateRunnableSteps(withSteps(ROTATE, ROTATE).steps()));
+
+ assertTrue(ex.getMessage().contains("at most 1 steps"), ex.getMessage());
+ }
+
+ @Test
+ void adHocStepsAcceptKnownOperationsAndLeaveFormatsToTheRun() {
+ PolicyValidator strict = validatorWith(KNOWS_REAL_ENDPOINTS);
+
+ strict.validateRunnableSteps(
+ withSteps(CLASSIFY, EXTERNAL_API, DOCPARSE, EXTRACT_IMAGES, ROTATE).steps());
+ }
+
private static final String EXTRACT_IMAGES = "/api/v1/misc/extract-images";
private static final String ROTATE = "/api/v1/general/rotate-pdf";
+ private static final String CLASSIFY = "/api/v1/ai/tools/classify-and-label";
+ private static final String EXTERNAL_API = "/api/v1/integration/external-api-call";
+ private static final String COMPRESS = "/api/v1/misc/compress-pdf";
+ private static final String DOCPARSE = "/api/v1/docparse/ingest";
+
+ // Declares only rotate and extract-images, but knows every endpoint these tests name.
+ private static final ToolIOSource KNOWS_REAL_ENDPOINTS =
+ new ToolIOSource() {
+ private final Set<String> known =
+ Set.of(EXTRACT_IMAGES, ROTATE, CLASSIFY, EXTERNAL_API, COMPRESS, DOCPARSE);
+
+ @Override
+ public java.util.Optional<ToolIOSpec> find(String operationPath) {
+ return IMAGE_THEN_PDF.find(operationPath);
+ }
+
+ @Override
+ public boolean isKnown(String operationPath) {
+ return known.contains(operationPath);
+ }
+ };
private static final ToolIOSource IMAGE_THEN_PDF =
ToolIOSource.of(
@@ -354,7 +490,7 @@ class PolicyValidatorTest {
@Test
void diagnoseChainFlagsTheFirstStepPastTheLimit() {
- props.getPolicies().setMaxSteps(2);
+ properties.getPolicies().setMaxSteps(2);
PipelineStep step = new PipelineStep("/api/v1/general/rotate-pdf", Map.of());
List<ToolDiagnostic> diagnostics = validator.diagnoseChain(List.of(step, step, step), null);
@@ -370,7 +506,7 @@ class PolicyValidatorTest {
@Test
void refusesMoreStepsThanTheLimit() {
- props.getPolicies().setMaxSteps(2);
+ properties.getPolicies().setMaxSteps(2);
PipelineStep step = new PipelineStep("/api/v1/general/rotate-pdf", Map.of());
assertThrows(
@@ -388,7 +524,7 @@ class PolicyValidatorTest {
sourceStore,
assetStore,
new ToolChainValidator(toolIO),
- props);
+ properties);
}
private Policy withSteps(String... operations) {
diff --git a/build.gradle b/build.gradle
index c05b433fa8..832418a199 100644
--- a/build.gradle
+++ b/build.gradle
@@ -776,24 +776,20 @@ tasks.withType(Test).configureEach {
// ----------------------------------------------------------------------------
configurations {
- jacocoRuntimeAgent
jacocoCli
}
dependencies {
- // The :runtime classifier on org.jacoco.agent IS the agent jar - no
- // unzipping required. Kept on the version the plugin already picks so
- // agent + reporter line up exactly.
- jacocoRuntimeAgent "org.jacoco:org.jacoco.agent:${jacoco.toolVersion}:runtime"
jacocoCli "org.jacoco:org.jacoco.cli:${jacoco.toolVersion}"
}
tasks.register('copyJacocoAgent', Copy) {
group = 'verification'
description = 'Copies the JaCoCo runtime agent jar to build/jacoco/jacocoagent.jar.'
- from configurations.jacocoRuntimeAgent
+ // Reuse the test agent artifact so mirrors and shared caches need only one agent dependency.
+ from { configurations.jacocoAgent.collect { zipTree(it) } }
+ include 'jacocoagent.jar'
into layout.buildDirectory.dir('jacoco')
- rename { 'jacocoagent.jar' }
}
// Aggregates an externally-produced .exec (e.g. from e2e:live or the cucumber
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index a630c2cc2c..7ad7dc30ca 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -193,7 +193,7 @@ class Position1(IntEnum):
class StampType(StrEnum):
"""
- The stamp type (text, image or qr)
+ The stamp type (text, image or qr). When omitted, image is used if stampImage is supplied, otherwise text.
"""
text = "text"
@@ -224,14 +224,18 @@ class AddStampParams(ApiModel):
description="The pages to select, Supports ranges (e.g., '1,3,5-9'), or 'all' or functions in the format 'an+b' where 'a' is the multiplier of the page number 'n', and 'b' is a constant (e.g., '2n+1', '3n', '6n-5')",
)
position: Position1 = Field(
- Position1.integer_8,
+ Position1.integer_5,
description="Position for stamp placement based on a 1-9 grid (1: bottom-left, 2: bottom-center, 3: bottom-right, 4: middle-left, 5: middle-center, 6: middle-right, 7: top-left, 8: top-center, 9: top-right)",
)
rotation: float = Field(0, description="The rotation of the stamp in degrees")
- stamp_text: str = Field(
- "Stirling Software", description="The stamp text, or the QR code content when the stamp type is qr"
+ stamp_text: str | None = Field(
+ None,
+ description="The stamp text, or the QR code content when stampType is qr; required when stampType is text or qr",
+ )
+ stamp_type: StampType | None = Field(
+ None,
+ description="The stamp type (text, image or qr). When omitted, image is used if stampImage is supplied, otherwise text.",
)
- stamp_type: StampType = Field(..., description="The stamp type (text, image or qr)")
class Alphabet1(StrEnum):
@@ -249,7 +253,7 @@ class Alphabet1(StrEnum):
class WatermarkType(StrEnum):
"""
- The watermark type (text or image)
+ The watermark type (text or image). When omitted, image is used if watermarkImage is supplied, otherwise text.
"""
text = "text"
@@ -264,12 +268,15 @@ class AddWatermarkParams(ApiModel):
alphabet: Alphabet1 = Field(Alphabet1.roman, description="The selected alphabet")
convert_pdf_to_image: bool = Field(False, description="Convert the redacted PDF to an image")
custom_color: str = Field("#d3d3d3", description="The color for watermark")
- font_size: float = Field(30, description="The font size of the watermark text", ge=1.0)
+ font_size: float = Field(12, description="The font size of the watermark text", ge=1.0)
height_spacer: int = Field(50, description="The height spacer between watermark elements", ge=0)
opacity: float = Field(0.5, description="The opacity of the watermark (0.0 - 1.0)")
rotation: float = Field(0, description="The rotation of the watermark in degrees")
- watermark_text: str = Field("Stirling Software", description="The watermark text")
- watermark_type: WatermarkType = Field(..., description="The watermark type (text or image)")
+ watermark_text: str | None = Field(None, description="The watermark text, required when watermarkType is text")
+ watermark_type: WatermarkType | None = Field(
+ None,
+ description="The watermark type (text or image). When omitted, image is used if watermarkImage is supplied, otherwise text.",
+ )
width_spacer: int = Field(50, description="The width spacer between watermark elements", ge=0)
@@ -283,7 +290,9 @@ class AutoRedactParams(ApiModel):
)
convert_pdf_to_image: bool = Field(False, description="Convert the redacted PDF to an image")
custom_padding: float = Field(..., description="Custom padding for redaction")
- list_of_text: str = Field("text,text2", description="List of text to redact from the PDF")
+ list_of_text: str = Field(
+ ..., description="Newline-separated list of text to redact from the PDF", examples=["text\ntext2"]
+ )
redact_color: str = Field("#000000", description="The color for redaction")
use_regex: bool = Field(False, description="Whether to use regex for the listOfText")
whole_word_search: bool = Field(False, description="Whether to use whole word search")
@@ -425,7 +434,11 @@ class CompressPdfParams(ApiModel):
This endpoint accepts a PDF file and optimizes it based on the provided parameters. Input:PDF Output:PDF Type:SISO
"""
- expected_output_size: str = Field("25KB", description="The expected output size, e.g. '100MB', '25KB', etc.")
+ expected_output_size: str | None = Field(
+ None,
+ description="Target output size, e.g. '100MB' or '25KB'. When set, the optimization level is chosen automatically to reach it; omit to compress at optimizeLevel.",
+ examples=["25KB"],
+ )
grayscale: bool = Field(False, description="Whether to convert the PDF to grayscale. Default is false.")
line_art: bool = Field(
False, description="Whether to convert images to high-contrast line art using ImageMagick. Default is false."
@@ -587,11 +600,11 @@ class ExtractImageScansParams(ApiModel):
This endpoint extracts image scans from a given file based on certain parameters. Users can specify angle threshold, tolerance, minimum area, minimum contour area, and border size. Input:PDF/IMAGE Output:IMAGE Type:SIMO
"""
- angle_threshold: int = Field(5, description="The angle threshold for the image scan extraction")
+ angle_threshold: int = Field(10, description="The angle threshold for the image scan extraction")
border_size: int = Field(1, description="The border size for the image scan extraction")
- min_area: int = Field(8000, description="The minimum area for the image scan extraction")
+ min_area: int = Field(10000, description="The minimum area for the image scan extraction")
min_contour_area: int = Field(500, description="The minimum contour area for the image scan extraction")
- tolerance: int = Field(20, description="The tolerance for the image scan extraction")
+ tolerance: int = Field(30, description="The tolerance for the image scan extraction")
class Format(StrEnum):
@@ -843,7 +856,7 @@ class OcrRenderType(StrEnum):
class OcrType(StrEnum):
"""
- Specify the OCR type, e.g., 'skip-text', 'force-ocr', or 'Normal'
+ How to treat pages that already contain text: 'skip-text' OCRs only pages without text, 'force-ocr' rasterises and OCRs every page.
"""
skip_text = "skip-text"
@@ -856,19 +869,22 @@ class OcrPdfParams(ApiModel):
This endpoint processes a PDF file using OCR (Optical Character Recognition). Users can specify languages, sidecar, deskew, clean, cleanFinal, ocrType, ocrRenderType, and removeImagesAfter options. Uses OCRmyPDF if available, falls back to Tesseract. Input:PDF Output:PDF Type:SISO
"""
- clean: bool | None = Field(None, description="Clean the input file if set to true")
- clean_final: bool | None = Field(None, description="Clean the final output if set to true")
- deskew: bool | None = Field(None, description="Deskew the input file if set to true")
+ clean: bool = Field(False, description="Clean the input file if set to true")
+ clean_final: bool = Field(False, description="Clean the final output if set to true")
+ deskew: bool = Field(False, description="Deskew the input file if set to true")
languages: list[str] = Field(["eng"], description="List of languages to use in OCR processing, e.g., 'eng', 'deu'")
ocr_render_type: OcrRenderType = Field(
OcrRenderType.hocr, description="Specify the OCR render type, either 'hocr' or 'sandwich'"
)
- ocr_type: OcrType = Field(..., description="Specify the OCR type, e.g., 'skip-text', 'force-ocr', or 'Normal'")
- remove_images_after: bool | None = Field(None, description="Remove images from the output PDF if set to true")
- rotate_pages: bool | None = Field(
- None, description="Auto-correct page orientation (90/180/270) using Tesseract OSD if set to true"
+ ocr_type: OcrType = Field(
+ OcrType.skip_text,
+ description="How to treat pages that already contain text: 'skip-text' OCRs only pages without text, 'force-ocr' rasterises and OCRs every page.",
+ )
+ remove_images_after: bool = Field(False, description="Remove images from the output PDF if set to true")
+ rotate_pages: bool = Field(
+ False, description="Auto-correct page orientation (90/180/270) using Tesseract OSD if set to true"
)
- sidecar: bool | None = Field(None, description="Include OCR text in a sidecar text file if set to true")
+ sidecar: bool = Field(False, description="Include OCR text in a sidecar text file if set to true")
class PageRotation(ApiModel):
@@ -1133,8 +1149,8 @@ class PdfToUaParams(ApiModel):
description="How to treat images with no description. require-alt leaves them undescribed so the report asks for input; mark-decorative treats every image as decoration.",
)
language: str = Field(
- "en-GB",
- description="Document language as a BCP-47 tag, for example en-GB. Applied only when the document does not already declare one, unless overrideLanguage is set.",
+ "en-US",
+ description="Document language as a BCP-47 tag, for example en-US. Applied only when the document does not already declare one, unless overrideLanguage is set.",
)
override_language: bool = Field(
False,
@@ -1238,7 +1254,7 @@ class CustomMode(StrEnum):
class RearrangePagesParams(ApiModel):
"""
- This endpoint rearranges pages in a given PDF file based on the specified page order or custom mode. Users can provide a page order as a comma-separated list of page numbers or page ranges, or a custom mode. Input:PDF Output:PDF Type:SISO
+ Builds the output from pageNumbers, in the order given: '3-7' keeps only pages 3 to 7, '3,1,2' keeps pages 3, 1 and 2 in that order, and pages not listed are dropped (a page listed twice is kept once). Or set customMode to a preset such as REVERSE_ORDER, DUPLEX_SORT or REMOVE_FIRST; with DUPLICATE, pageNumbers is how many copies of each page to make. Input:PDF Output:PDF Type:SISO
"""
custom_mode: CustomMode | None = Field(
@@ -1455,7 +1471,7 @@ class Orientation1(StrEnum):
class PageSize(StrEnum):
"""
- The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP.
+ The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP. KEEP keeps each page's own size.
"""
a0 = "A0"
@@ -1480,7 +1496,8 @@ class ScalePagesParams(ApiModel):
description="Orientation to apply to the target page size. Ignored when pageSize is KEEP.",
)
page_size: PageSize = Field(
- ..., description="The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP."
+ PageSize.keep,
+ description="The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP. KEEP keeps each page's own size.",
)
scale_factor: float = Field(
1, description="The scale of the content on the pages of the output PDF. Acceptable values are floats.", ge=0.0
@@ -1592,7 +1609,11 @@ class SplitPdfByChaptersParams(ApiModel):
"""
allow_duplicates: bool = Field(False, description="Whether to allow duplicates or not")
- bookmark_level: int = Field(0, description="Maximum bookmark level required", ge=0)
+ bookmark_level: int = Field(
+ 1,
+ description="Maximum bookmark nesting level to split on: 0 splits on top-level bookmarks only, 1 also on their children, and so on",
+ ge=0,
+ )
include_metadata: bool = Field(False, description="Whether to include Metadata or not")
@@ -1621,7 +1642,11 @@ class SplitPdfBySectionsParams(ApiModel):
horizontal_divisions: int = Field(0, description="Number of horizontal divisions for each PDF page", ge=0, le=50)
merge: bool = Field(False, description="Merge the split documents into a single PDF")
- page_numbers: str = Field("SPLIT_ALL", description="Pages to be split by section")
+ page_numbers: str | None = Field(
+ None,
+ description="Pages to split when splitMode is CUSTOM (required in that mode, ignored otherwise). Supports ranges (e.g. '1,3,5-9'), 'all', or functions like '2n+1'.",
+ examples=["1,3,5-9"],
+ )
split_mode: SplitMode | None = Field(
None,
description="Modes for page split. Valid values are:\nSPLIT_ALL_EXCEPT_FIRST_AND_LAST: Splits all except the first and the last pages.\nSPLIT_ALL_EXCEPT_FIRST: Splits all except the first page.\nSPLIT_ALL_EXCEPT_LAST: Splits all except the last page.\nSPLIT_ALL: Splits all pages.\nCUSTOM: Custom split.\n",
@@ -1659,12 +1684,13 @@ class TextRange(ApiModel):
class TimestampPdfParams(ApiModel):
"""
- Contacts a trusted Time Stamp Authority (TSA) server and embeds an RFC 3161 document timestamp into the PDF. Only a SHA-256 hash of the document is sent to the TSA - the PDF itself never leaves the server. Input:PDF Output:PDF Type:SISO
+ Contacts a trusted Time Stamp Authority (TSA) server and embeds an RFC 3161 document timestamp into the PDF. Only a SHA-256 hash of the document is sent to the TSA - the PDF itself never leaves the server. Make the timestamp the last change to the file: any later edit invalidates it. Input:PDF Output:PDF Type:SISO
"""
- tsa_url: str = Field(
- "http://timestamp.digicert.com",
- description="URL of the RFC 3161 Time Stamp Authority (TSA) server. Must be one of the built-in presets (DigiCert, Sectigo, SSL.com, FreeTSA, MeSign) or an admin-configured URL in settings.yml (security.timestamp.customTsaUrls). If omitted, the server default is used.",
+ tsa_url: str | None = Field(
+ None,
+ description="URL of the RFC 3161 Time Stamp Authority (TSA) server. Must be one of the built-in presets (DigiCert, Sectigo, SSL.com, FreeTSA, MeSign) or an admin-configured URL in settings.yml (security.timestamp.customTsaUrls). If omitted, the server default is used (security.timestamp.defaultTsaUrl, DigiCert unless changed).",
+ examples=["http://timestamp.digicert.com"],
)
@@ -1676,7 +1702,7 @@ class UnlockPdfFormsParams(ApiModel):
class Trapped(StrEnum):
"""
- The trapped status of the document
+ The trapped status of the document. Omit to remove it, which readers treat as Unknown.
"""
true = "True"
@@ -1693,24 +1719,36 @@ class UpdateMetadataParams(ApiModel):
None,
description="Map list of key and value of custom parameters. Note these must start with customKey and customValue if they are non-standard",
)
- author: str = Field("author", description="The author of the document")
- creation_date: str = Field(
- "2023/10/01 12:00:00",
- description="The creation date of the document (format: yyyy/MM/dd HH:mm:ss)",
+ author: str | None = Field(None, description="The author of the document. Omit to remove it.", examples=["author"])
+ creation_date: str | None = Field(
+ None,
+ description="The creation date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it.",
+ examples=["2023/10/01 12:00:00"],
pattern="yyyy/MM/dd HH:mm:ss",
)
- creator: str = Field("creator", description="The creator of the document")
+ creator: str | None = Field(
+ None, description="The creator of the document. Omit to remove it.", examples=["creator"]
+ )
delete_all: bool = Field(False, description="Delete all metadata if set to true")
- keywords: str = Field("keywords", description="The keywords for the document")
- modification_date: str = Field(
- "2023/10/01 12:00:00",
- description="The modification date of the document (format: yyyy/MM/dd HH:mm:ss)",
+ keywords: str | None = Field(
+ None, description="The keywords for the document. Omit to remove it.", examples=["keywords"]
+ )
+ modification_date: str | None = Field(
+ None,
+ description="The modification date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it.",
+ examples=["2023/10/01 12:00:00"],
pattern="yyyy/MM/dd HH:mm:ss",
)
- producer: str = Field("producer", description="The producer of the document")
- subject: str = Field("subject", description="The subject of the document")
- title: str = Field("title", description="The title of the document")
- trapped: Trapped = Field(Trapped.false, description="The trapped status of the document")
+ producer: str | None = Field(
+ None, description="The producer of the document. Omit to remove it.", examples=["producer"]
+ )
+ subject: str | None = Field(
+ None, description="The subject of the document. Omit to remove it.", examples=["subject"]
+ )
+ title: str | None = Field(None, description="The title of the document. Omit to remove it.", examples=["title"])
+ trapped: Trapped | None = Field(
+ None, description="The trapped status of the document. Omit to remove it, which readers treat as Unknown."
+ )
class UrlToPdfParams(ApiModel):
@@ -1743,7 +1781,7 @@ class VectorToPdfParams(ApiModel):
class AutoRotatePdfParams(ApiModel):
"""
- Detects each page's orientation (embedded-text direction first, Tesseract OSD for scanned pages) and sets the page rotation so the content displays upright. With dryRun=true, returns a JSON per-page report instead of the PDF. With pageRotations set, applies the given corrections without running detection. Input:PDF Output:PDF Type:SISO
+ Detects each page's orientation (embedded-text direction first, Tesseract OSD for scanned pages) and sets the page rotation so the content displays upright. With dryRun=true, returns a JSON per-page report instead of the PDF. With pageRotations set (a JSON list such as [{"pageNumber":3,"rotation":90}]), applies only those clockwise turns without running detection. Input:PDF Output:PDF Type:SISO
"""
confidence_threshold: float = Field(
@@ -1805,9 +1843,8 @@ class RedactParams(ApiModel):
"""
convert_pdf_to_image: bool = Field(False, description="Convert the redacted PDF to an image")
- page_numbers: str = Field(
- "all",
- description="The pages to select, Supports ranges (e.g., '1,3,5-9'), or 'all' or functions in the format 'an+b' where 'a' is the multiplier of the page number 'n', and 'b' is a constant (e.g., '2n+1', '3n', '6n-5')",
+ page_numbers: str | None = Field(
+ None, description="Pages to black out completely, e.g. '1,3-5'. Omit to redact only the listed areas."
)
page_redaction_color: str = Field("#000000", description="The color used to fully redact certain pages")
redactions: list[RedactionArea] = Field(..., description="A list of areas that should be redacted")
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index f6f9ce0398..f1f418f552 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -4107,7 +4107,7 @@ pdfUaFigureLabel = "Page {{page}} {{kind}}"
pdfUaFigurePlaceholder = "What this image tells the reader"
pdfUaFindImages = "Find images needing a description"
pdfUaLanguage = "Document language"
-pdfUaLanguageHelp = "A BCP-47 tag such as en-GB. Used only when the document does not already declare its own language."
+pdfUaLanguageHelp = "A BCP-47 tag such as en-US. Used only when the document does not already declare its own language."
pdfUaNoImagesNeedingText = "No image is missing a description."
pdfUaOptions = "PDF/UA Options"
pdfUaOverrideLanguage = "Replace the document's own language"
diff --git a/frontend/src/editor/core/components/tools/convert/ConvertToPdfUaSettings.tsx b/frontend/src/editor/core/components/tools/convert/ConvertToPdfUaSettings.tsx
index 6f20e84877..d9564a92c2 100644
--- a/frontend/src/editor/core/components/tools/convert/ConvertToPdfUaSettings.tsx
+++ b/frontend/src/editor/core/components/tools/convert/ConvertToPdfUaSettings.tsx
@@ -149,7 +149,7 @@ const ConvertToPdfUaSettings = ({
label={t("convert.pdfUaLanguage", "Document language")}
description={t(
"convert.pdfUaLanguageHelp",
- "A BCP-47 tag such as en-GB. Used only when the document does not already declare its own language.",
+ "A BCP-47 tag such as en-US. Used only when the document does not already declare its own language.",
)}
value={parameters.pdfUaOptions.language}
onChange={(event) => update({ language: event.currentTarget.value })}
diff --git a/frontend/src/editor/core/components/tools/ocr/LanguagePicker.tsx b/frontend/src/editor/core/components/tools/ocr/LanguagePicker.tsx
index fce0c90882..b5de1febb1 100644
--- a/frontend/src/editor/core/components/tools/ocr/LanguagePicker.tsx
+++ b/frontend/src/editor/core/components/tools/ocr/LanguagePicker.tsx
@@ -44,12 +44,16 @@ const LanguagePicker: React.FC<LanguagePickerProps> = ({
const [hasAutoFilled, setHasAutoFilled] = useState(false);
useEffect(() => {
+ let cancelled = false;
// Fetch available languages from backend
const fetchLanguages = async () => {
try {
const { data } = await apiClient.get<{ languages: string[] }>(
languagesEndpoint,
);
+ if (cancelled) {
+ return;
+ }
const displayNames =
typeof Intl.DisplayNames !== "undefined"
@@ -86,6 +90,9 @@ const LanguagePicker: React.FC<LanguagePickerProps> = ({
setAvailableLanguages(languageOptions);
} catch (error) {
+ if (cancelled) {
+ return;
+ }
console.error("[LanguagePicker] Fetch failed with error:", error);
console.error("[LanguagePicker] Error details:", {
name: error instanceof Error ? error.name : "Unknown",
@@ -93,11 +100,16 @@ const LanguagePicker: React.FC<LanguagePickerProps> = ({
stack: error instanceof Error ? error.stack : undefined,
});
} finally {
- setIsLoadingLanguages(false);
+ if (!cancelled) {
+ setIsLoadingLanguages(false);
+ }
}
};
fetchLanguages();
+ return () => {
+ cancelled = true;
+ };
}, [languagesEndpoint, i18n.language, t]);
// Auto-fill OCR language based on browser language when languages are loaded
diff --git a/frontend/src/editor/core/hooks/tools/convert/useConvertParameters.ts b/frontend/src/editor/core/hooks/tools/convert/useConvertParameters.ts
index a6209079fc..5510ae15dd 100644
--- a/frontend/src/editor/core/hooks/tools/convert/useConvertParameters.ts
+++ b/frontend/src/editor/core/hooks/tools/convert/useConvertParameters.ts
@@ -121,7 +121,7 @@ export const defaultParameters: ConvertParameters = {
},
pdfUaOptions: {
profile: "ua1",
- language: "en-GB",
+ language: "en-US",
overrideLanguage: false,
title: "",
embedFonts: true,
diff --git a/frontend/src/editor/core/hooks/tools/shared/useToolApiCalls.ts b/frontend/src/editor/core/hooks/tools/shared/useToolApiCalls.ts
index 15033ede89..7927331011 100644
--- a/frontend/src/editor/core/hooks/tools/shared/useToolApiCalls.ts
+++ b/frontend/src/editor/core/hooks/tools/shared/useToolApiCalls.ts
@@ -5,7 +5,7 @@ import {
processResponse,
ResponseHandler,
} from "@editor/utils/toolResponseProcessor";
-import { isEmptyOutput } from "@editor/services/errorUtils";
+import { isEmptyOutput, serverErrorReason } from "@editor/services/errorUtils";
import type { ProcessingProgress } from "@editor/hooks/tools/shared/useToolState";
import type { StirlingFile, FileId } from "@editor/types/fileContext";
import { isSignupRequiredError } from "@editor/utils/toolErrorHandler";
@@ -62,6 +62,7 @@ export const useToolApiCalls = <TParams = void>() => {
const failedInputs: FailedInput[] = [];
const unprocessedSourceIds: FileId[] = [];
const failedFiles: string[] = [];
+ let firstFailureReason: string | undefined;
const total = validFiles.length;
const cancellation = axios.CancelToken.source();
@@ -230,6 +231,7 @@ export const useToolApiCalls = <TParams = void>() => {
}
console.error("[processFiles] Failed", { name: file.name, error });
failedFiles.push(file.name);
+ firstFailureReason ??= await serverErrorReason(error);
failedInputs.push({ fileId: file.fileId, name: file.name, error });
// mark errored file so UI can highlight
try {
@@ -253,16 +255,17 @@ export const useToolApiCalls = <TParams = void>() => {
unprocessedSourceIds.push(id);
}
+ const reasonSuffix = firstFailureReason ? ` (${firstFailureReason})` : "";
if (failedFiles.length > 0 && processedFiles.length === 0) {
if (failedInputs.length === 1) throw failedInputs[0].error;
throw new Error(
- `Failed to process all files: ${failedFiles.join(", ")}`,
+ `Failed to process all files: ${failedFiles.join(", ")}${reasonSuffix}`,
);
}
if (failedFiles.length > 0) {
onStatus(
- `Processed ${processedFiles.length}/${total} files. Failed: ${failedFiles.join(", ")}`,
+ `Processed ${processedFiles.length}/${total} files. Failed: ${failedFiles.join(", ")}${reasonSuffix}`,
);
} else {
onStatus(
diff --git a/frontend/src/editor/core/services/errorUtils.serverReason.test.ts b/frontend/src/editor/core/services/errorUtils.serverReason.test.ts
new file mode 100644
index 0000000000..8478b894e6
--- /dev/null
+++ b/frontend/src/editor/core/services/errorUtils.serverReason.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { serverErrorReason } from "@editor/services/errorUtils";
+
+const blobError = (body: object) => ({
+ response: {
+ data: new Blob([JSON.stringify(body)], { type: "application/json" }),
+ },
+});
+
+describe("serverErrorReason", () => {
+ it("reads a problem detail from a blob body", async () => {
+ await expect(
+ serverErrorReason(
+ blobError({
+ detail: "Invalid page selection '0': pages are numbered 1 to 3.",
+ }),
+ ),
+ ).resolves.toBe("Invalid page selection '0': pages are numbered 1 to 3.");
+ });
+
+ it("falls back to message and ignores unreadable bodies", async () => {
+ await expect(
+ serverErrorReason(blobError({ message: "No pages" })),
+ ).resolves.toBe("No pages");
+ await expect(
+ serverErrorReason(new Error("network")),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/frontend/src/editor/core/services/errorUtils.ts b/frontend/src/editor/core/services/errorUtils.ts
index 747cd90b5a..dd51d0b2ae 100644
--- a/frontend/src/editor/core/services/errorUtils.ts
+++ b/frontend/src/editor/core/services/errorUtils.ts
@@ -24,6 +24,40 @@ export async function normalizeAxiosErrorData(data: unknown): Promise<unknown> {
return data;
}
+/** The server's own reason for a failed request (ProblemDetail `detail` or `message`), if any. */
+export async function serverErrorReason(
+ error: unknown,
+): Promise<string | undefined> {
+ const data = (error as { response?: { data?: unknown } })?.response?.data;
+ try {
+ let payload = await normalizeAxiosErrorData(data);
+ if (typeof Blob !== "undefined" && payload instanceof Blob) {
+ // Older Blob implementations lack text(); read it the long way.
+ payload = tryParseJson(await readBlobText(payload));
+ }
+ if (payload && typeof payload === "object") {
+ const { detail, message } = payload as {
+ detail?: unknown;
+ message?: unknown;
+ };
+ const reason = typeof detail === "string" && detail ? detail : message;
+ return typeof reason === "string" && reason ? reason : undefined;
+ }
+ } catch {
+ // Unreadable body: the caller keeps its generic message.
+ }
+ return undefined;
+}
+
+function readBlobText(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result ?? ""));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(blob);
+ });
+}
+
export function extractErrorFileIds(payload: unknown): string[] | undefined {
if (!payload) return undefined;
const errorFileIds = (payload as { errorFileIds?: unknown }).errorFileIds;
diff --git a/frontend/src/editor/core/services/httpErrorHandler.ts b/frontend/src/editor/core/services/httpErrorHandler.ts
index 71199fb6d9..18cb80003b 100644
--- a/frontend/src/editor/core/services/httpErrorHandler.ts
+++ b/frontend/src/editor/core/services/httpErrorHandler.ts
@@ -153,10 +153,7 @@ export async function handleHttpError(error: unknown): Promise<boolean> {
if (handleSaaSError(error)) return true;
- // Compute title/body (friendly) from the error object
- const { title, body } = extractAxiosErrorMessage(error);
-
- // Normalize response data ONCE, reuse for both ID extraction and special-toast matching
+ // Normalize response data ONCE, reuse for the message, ID extraction and special toasts
const raw = axiosError?.response?.data;
let normalized: unknown = raw;
try {
@@ -165,6 +162,16 @@ export async function handleHttpError(error: unknown): Promise<boolean> {
console.debug("normalizeAxiosErrorData", e);
}
+ // Tool calls ask for blobs, so read the message from the normalized body, not the raw blob.
+ const { title, body } = extractAxiosErrorMessage(
+ axiosError?.response
+ ? {
+ ...axiosError,
+ response: { ...axiosError.response, data: normalized },
+ }
+ : error,
+ );
+
// 1) If server sends structured file IDs for failures, also mark them errored in UI
try {
const ids = extractErrorFileIds(normalized);
diff --git a/frontend/src/editor/core/services/httpErrorUtils.test.ts b/frontend/src/editor/core/services/httpErrorUtils.test.ts
new file mode 100644
index 0000000000..1cde73b67a
--- /dev/null
+++ b/frontend/src/editor/core/services/httpErrorUtils.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import { extractAxiosErrorMessage } from "@editor/services/httpErrorUtils";
+
+describe("problem detail selection", () => {
+ it.each([
+ "",
+ "Request failed",
+ "500 Server Error",
+ undefined,
+ { unexpected: true },
+ ])("uses a specific detail when message is %j", (message) => {
+ const result = extractAxiosErrorMessage({
+ isAxiosError: true,
+ response: {
+ status: 400,
+ data: { message, detail: "pageNumbers selects no pages" },
+ },
+ });
+ expect(result.body).toBe("pageNumbers selects no pages");
+ });
+
+ it("preserves a specific message", () => {
+ expect(
+ extractAxiosErrorMessage({
+ isAxiosError: true,
+ response: {
+ status: 400,
+ data: { message: "Unsupported image", detail: "Generic detail" },
+ },
+ }).body,
+ ).toBe("Unsupported image");
+ });
+});
diff --git a/frontend/src/editor/core/services/httpErrorUtils.ts b/frontend/src/editor/core/services/httpErrorUtils.ts
index 2ce7b17f04..5270d4d627 100644
--- a/frontend/src/editor/core/services/httpErrorUtils.ts
+++ b/frontend/src/editor/core/services/httpErrorUtils.ts
@@ -74,8 +74,14 @@ export function extractAxiosErrorMessage(error: unknown): {
ids: ids.join(", "),
});
}
- const message = (data as { message?: unknown })?.message;
- if (message) return message as string;
+ const { message, detail } = data as {
+ message?: unknown;
+ detail?: unknown;
+ };
+ if (typeof message === "string" && !isUnhelpfulMessage(message))
+ return message;
+ if (typeof detail === "string" && detail.trim()) return detail;
+ if (typeof message === "string" && message.trim()) return message;
if (typeof raw === "string") return raw;
try {
return JSON.stringify(data);
diff --git a/frontend/src/editor/core/tests/stubbed/form-field-editing.spec.ts b/frontend/src/editor/core/tests/stubbed/form-field-editing.spec.ts
index f2fb301d5a..ecf740af37 100644
--- a/frontend/src/editor/core/tests/stubbed/form-field-editing.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/form-field-editing.spec.ts
@@ -520,7 +520,9 @@ test.describe("Form field editor", () => {
await selectMode(page, "Fill");
await page.getByTestId("unsaved-save").click();
await expect(
- page.getByText("Field could not be saved", { exact: true }),
+ page
+ .getByText("Field could not be saved", { exact: true })
+ .and(page.locator(":not(.toast-body)")),
).toBeVisible();
await expect(page.getByLabel("Label", { exact: true })).toHaveValue(
"Keep this draft",
diff --git a/frontend/src/editor/core/types/toolApiTypes.ts b/frontend/src/editor/core/types/toolApiTypes.ts
index 633b9e1afb..5cae40053a 100644
--- a/frontend/src/editor/core/types/toolApiTypes.ts
+++ b/frontend/src/editor/core/types/toolApiTypes.ts
@@ -164,13 +164,13 @@ export interface AddStampRequest {
rotation?: number;
stampImage?: File;
/**
- * The stamp text, or the QR code content when the stamp type is qr
+ * The stamp text, or the QR code content when stampType is qr; required when stampType is text or qr
*/
stampText?: string;
/**
- * The stamp type (text, image or qr)
+ * The stamp type (text, image or qr). When omitted, image is used if stampImage is supplied, otherwise text.
*/
- stampType: "text" | "image" | "qr";
+ stampType?: "text" | "image" | "qr";
}
export interface AddWatermarkRequest {
/**
@@ -203,13 +203,13 @@ export interface AddWatermarkRequest {
rotation?: number;
watermarkImage?: File;
/**
- * The watermark text
+ * The watermark text, required when watermarkType is text
*/
watermarkText?: string;
/**
- * The watermark type (text or image)
+ * The watermark type (text or image). When omitted, image is used if watermarkImage is supplied, otherwise text.
*/
- watermarkType: "text" | "image";
+ watermarkType?: "text" | "image";
/**
* The width spacer between watermark elements
*/
@@ -306,7 +306,7 @@ export interface ContainsTextRequest {
/**
* The text to check for
*/
- text?: string;
+ text: string;
}
export interface ConvertCbrToPdfRequest {
/**
@@ -621,7 +621,7 @@ export interface ManualRedactPdfRequest {
*/
convertPDFToImage?: boolean;
/**
- * The pages to select, Supports ranges (e.g., '1,3,5-9'), or 'all' or functions in the format 'an+b' where 'a' is the multiplier of the page number 'n', and 'b' is a constant (e.g., '2n+1', '3n', '6n-5')
+ * Pages to black out completely, e.g. '1,3-5'. Omit to redact only the listed areas.
*/
pageNumbers?: string;
/**
@@ -755,15 +755,15 @@ export interface MetadataRequest {
[k: string]: string | undefined;
};
/**
- * The author of the document
+ * The author of the document. Omit to remove it.
*/
author?: string;
/**
- * The creation date of the document (format: yyyy/MM/dd HH:mm:ss)
+ * The creation date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it.
*/
creationDate?: string;
/**
- * The creator of the document
+ * The creator of the document. Omit to remove it.
*/
creator?: string;
/**
@@ -771,27 +771,27 @@ export interface MetadataRequest {
*/
deleteAll?: boolean;
/**
- * The keywords for the document
+ * The keywords for the document. Omit to remove it.
*/
keywords?: string;
/**
- * The modification date of the document (format: yyyy/MM/dd HH:mm:ss)
+ * The modification date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it.
*/
modificationDate?: string;
/**
- * The producer of the document
+ * The producer of the document. Omit to remove it.
*/
producer?: string;
/**
- * The subject of the document
+ * The subject of the document. Omit to remove it.
*/
subject?: string;
/**
- * The title of the document
+ * The title of the document. Omit to remove it.
*/
title?: string;
/**
- * The trapped status of the document
+ * The trapped status of the document. Omit to remove it, which readers treat as Unknown.
*/
trapped?: "True" | "False" | "Unknown";
}
@@ -801,7 +801,7 @@ export type MiscShowJavascriptRequest = Record<string, never>;
export type MiscUnlockPdfFormsRequest = Record<string, never>;
export interface OptimizePdfRequest {
/**
- * The expected output size, e.g. '100MB', '25KB', etc.
+ * Target output size, e.g. '100MB' or '25KB'. When set, the optimization level is chosen automatically to reach it; omit to compress at optimizeLevel.
*/
expectedOutputSize?: string;
/**
@@ -963,7 +963,7 @@ export interface PdfToPdfUaRequest {
*/
figurePolicy?: "require-alt" | "mark-decorative";
/**
- * Document language as a BCP-47 tag, for example en-GB. Applied only when the document does not already declare one, unless overrideLanguage is set.
+ * Document language as a BCP-47 tag, for example en-US. Applied only when the document does not already declare one, unless overrideLanguage is set.
*/
language?: string;
/**
@@ -1055,9 +1055,9 @@ export interface ProcessPdfWithOcrRequest {
*/
ocrRenderType?: "hocr" | "sandwich";
/**
- * Specify the OCR type, e.g., 'skip-text', 'force-ocr', or 'Normal'
+ * How to treat pages that already contain text: 'skip-text' OCRs only pages without text, 'force-ocr' rasterises and OCRs every page.
*/
- ocrType: "skip-text" | "force-ocr" | "Normal";
+ ocrType?: "skip-text" | "force-ocr" | "Normal";
/**
* Remove images from the output PDF if set to true
*/
@@ -1198,9 +1198,9 @@ export interface RedactPdfRequest {
*/
customPadding: number;
/**
- * List of text to redact from the PDF
+ * Newline-separated list of text to redact from the PDF
*/
- listOfText?: string;
+ listOfText: string;
/**
* The color for redaction
*/
@@ -1320,9 +1320,9 @@ export interface ScalePagesRequest {
*/
orientation?: "PORTRAIT" | "LANDSCAPE";
/**
- * The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP.
+ * The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL, KEEP. KEEP keeps each page's own size.
*/
- pageSize:
+ pageSize?:
| "A0"
| "A1"
| "A2"
@@ -1424,32 +1424,32 @@ export interface SignPDFWithCertRequest {
alias?: string;
certFile?: File;
/**
- * The type of the digital certificate. WINDOWS_STORE and PKCS11 are hardware-backed and only available in the desktop app.
+ * SERVER: this server's own certificate, no file or password. Signer shown is the server's organisation, not the user; self-signed by default, so other PDF readers may show it unverified. PEM needs certFile+privateKeyFile, PKCS12/PFX p12File, JKS jksFile. WINDOWS_STORE/PKCS11: desktop app only.
*/
certType:
+ | "SERVER"
| "PEM"
| "PKCS12"
| "PFX"
| "JKS"
- | "SERVER"
| "WINDOWS_STORE"
| "PKCS11";
jksFile?: File;
/**
- * The location where the PDF is signed
+ * The location where the PDF is signed. Omitted from the signature when not set
*/
location?: string;
/**
- * The name of the signer
+ * Signer name stored in the signature properties; the visible box shows the certificate's name instead. Omitted when not set.
*/
name?: string;
p12File?: File;
/**
- * The page number where the signature should be visible. This is required if showSignature is set to true
+ * Page (1-based) for the visible signature. Only used when showSignature is true.
*/
pageNumber?: number;
/**
- * The password for the keystore / private key, or the token PIN for PKCS11
+ * Password for the PKCS12/PFX or JKS keystore or an encrypted PEM key, or the PKCS11 token PIN. Leave empty if the key has none. Not needed for SERVER or WINDOWS_STORE.
*/
password?: string;
/**
@@ -1462,7 +1462,7 @@ export interface SignPDFWithCertRequest {
pkcs11Slot?: number;
privateKeyFile?: File;
/**
- * The reason for signing the PDF
+ * The reason for signing the PDF. Omitted from the signature when not set
*/
reason?: string;
/**
@@ -1470,7 +1470,7 @@ export interface SignPDFWithCertRequest {
*/
showLogo?: boolean;
/**
- * Whether to visually show the signature in the PDF file
+ * Add a visible signature box on pageNumber showing the certificate's name, the date and the reason (if set).
*/
showSignature?: boolean;
}
@@ -1489,7 +1489,7 @@ export interface SplitPdfByChaptersRequest {
*/
allowDuplicates?: boolean;
/**
- * Maximum bookmark level required
+ * Maximum bookmark nesting level to split on: 0 splits on top-level bookmarks only, 1 also on their children, and so on
*/
bookmarkLevel?: number;
/**
@@ -1507,7 +1507,7 @@ export interface SplitPdfBySectionsRequest {
*/
merge?: boolean;
/**
- * Pages to be split by section
+ * Pages to split when splitMode is CUSTOM (required in that mode, ignored otherwise). Supports ranges (e.g. '1,3,5-9'), 'all', or functions like '2n+1'.
*/
pageNumbers?: string;
/**
@@ -1548,7 +1548,7 @@ export interface SvgToPdfRequest {
}
export interface TimestampPdfRequest {
/**
- * URL of the RFC 3161 Time Stamp Authority (TSA) server. Must be one of the built-in presets (DigiCert, Sectigo, SSL.com, FreeTSA, MeSign) or an admin-configured URL in settings.yml (security.timestamp.customTsaUrls). If omitted, the server default is used.
+ * URL of the RFC 3161 Time Stamp Authority (TSA) server. Must be one of the built-in presets (DigiCert, Sectigo, SSL.com, FreeTSA, MeSign) or an admin-configured URL in settings.yml (security.timestamp.customTsaUrls). If omitted, the server default is used (security.timestamp.defaultTsaUrl, DigiCert unless changed).
*/
tsaUrl?: string;
}