refactor: replace size checks with isEmpty(), safely collapse redundant "if X == null" or "if X != null" checks

This commit is contained in:
Balázs Szücs 2025-08-07 12:29:34 +02:00
parent 63b64b5dc5
commit be82079ba2
28 changed files with 74 additions and 87 deletions

View File

@ -433,19 +433,17 @@ public class ApplicationProperties {
private List<String> languages; private List<String> languages;
public String getAppName() { public String getAppName() {
return appName != null && appName.trim().length() > 0 ? appName : null; return appName != null && !appName.trim().isEmpty() ? appName : null;
} }
public String getHomeDescription() { public String getHomeDescription() {
return homeDescription != null && homeDescription.trim().length() > 0 return homeDescription != null && !homeDescription.trim().isEmpty()
? homeDescription ? homeDescription
: null; : null;
} }
public String getAppNameNavbar() { public String getAppNameNavbar() {
return appNameNavbar != null && appNameNavbar.trim().length() > 0 return appNameNavbar != null && !appNameNavbar.trim().isEmpty() ? appNameNavbar : null;
? appNameNavbar
: null;
} }
} }

View File

@ -28,7 +28,7 @@ public class CustomHtmlSanitizer {
new AttributePolicy() { new AttributePolicy() {
@Override @Override
public String apply(String elementName, String attributeName, String value) { public String apply(String elementName, String attributeName, String value) {
if (value == null || value.trim().isEmpty()) { if (value.trim().isEmpty()) {
return null; return null;
} }

View File

@ -74,7 +74,7 @@ public class PDFToFile {
Path tempInputFile = null; Path tempInputFile = null;
Path tempOutputDir = null; Path tempOutputDir = null;
byte[] fileBytes; byte[] fileBytes;
String fileName = "temp.file"; String fileName;
try { try {
tempInputFile = Files.createTempFile("input_", ".pdf"); tempInputFile = Files.createTempFile("input_", ".pdf");
@ -167,7 +167,7 @@ public class PDFToFile {
Path tempInputFile = null; Path tempInputFile = null;
Path tempOutputDir = null; Path tempOutputDir = null;
byte[] fileBytes; byte[] fileBytes;
String fileName = "temp.file"; String fileName;
try { try {
// Save the uploaded file to a temporary location // Save the uploaded file to a temporary location
@ -230,7 +230,7 @@ public class PDFToFile {
// Get the original PDF file name without the extension // Get the original PDF file name without the extension
String originalPdfFileName = Filenames.toSimpleFileName(inputFile.getOriginalFilename()); String originalPdfFileName = Filenames.toSimpleFileName(inputFile.getOriginalFilename());
if (originalPdfFileName == null || "".equals(originalPdfFileName.trim())) { if (originalPdfFileName == null || originalPdfFileName.trim().isEmpty()) {
originalPdfFileName = "output.pdf"; originalPdfFileName = "output.pdf";
} }
// Assume file is pdf if no extension // Assume file is pdf if no extension
@ -248,7 +248,7 @@ public class PDFToFile {
Path tempInputFile = null; Path tempInputFile = null;
Path tempOutputDir = null; Path tempOutputDir = null;
byte[] fileBytes; byte[] fileBytes;
String fileName = "temp.file"; String fileName;
try { try {
// Save the uploaded file to a temporary location // Save the uploaded file to a temporary location

View File

@ -122,7 +122,7 @@ public class PdfUtils {
} }
public static boolean hasImagesOnPage(PDPage page) throws IOException { public static boolean hasImagesOnPage(PDPage page) throws IOException {
return getAllImages(page.getResources()).size() > 0; return !getAllImages(page.getResources()).isEmpty();
} }
public static boolean hasTextOnPage(PDPage page, String phrase) throws IOException { public static boolean hasTextOnPage(PDPage page, String phrase) throws IOException {

View File

@ -26,7 +26,7 @@ class AppUpdateService {
@Scope("request") @Scope("request")
public boolean shouldShow() { public boolean shouldShow() {
boolean showUpdate = applicationProperties.getSystem().isShowUpdate(); boolean showUpdate = applicationProperties.getSystem().isShowUpdate();
boolean showAdminResult = (showAdmin != null) ? showAdmin.getShowUpdateOnlyAdmins() : true; boolean showAdminResult = showAdmin == null || showAdmin.getShowUpdateOnlyAdmins();
return showUpdate && showAdminResult; return showUpdate && showAdminResult;
} }
} }

View File

@ -64,7 +64,7 @@ public class CleanUrlInterceptor implements HandlerInterceptor {
// Construct new query string // Construct new query string
StringBuilder newQueryString = new StringBuilder(); StringBuilder newQueryString = new StringBuilder();
for (Map.Entry<String, String> entry : allowedParameters.entrySet()) { for (Map.Entry<String, String> entry : allowedParameters.entrySet()) {
if (newQueryString.length() > 0) { if (!newQueryString.isEmpty()) {
newQueryString.append("&"); newQueryString.append("&");
} }
newQueryString.append(entry.getKey()).append("=").append(entry.getValue()); newQueryString.append(entry.getKey()).append("=").append(entry.getValue());

View File

@ -100,7 +100,7 @@ public class ExternalAppDepConfig {
"Missing dependency: {} - Disabling group: {} (Affected features: {})", "Missing dependency: {} - Disabling group: {} (Affected features: {})",
command, command,
group, group,
affectedFeatures != null && !affectedFeatures.isEmpty() !affectedFeatures.isEmpty()
? String.join(", ", affectedFeatures) ? String.join(", ", affectedFeatures)
: "unknown"); : "unknown");
} }

View File

@ -259,7 +259,7 @@ public class RearrangePagesPDFController {
int totalPages = document.getNumberOfPages(); int totalPages = document.getNumberOfPages();
List<Integer> newPageOrder; List<Integer> newPageOrder;
if (sortType != null if (sortType != null
&& sortType.length() > 0 && !sortType.isEmpty()
&& !"custom".equals(sortType.toLowerCase())) { && !"custom".equals(sortType.toLowerCase())) {
newPageOrder = processSortTypes(sortType, totalPages, pageOrder); newPageOrder = processSortTypes(sortType, totalPages, pageOrder);
} else { } else {

View File

@ -273,7 +273,7 @@ public class SplitPdfBySizeController {
log.debug("Starting handleSplitByPageCount with pageCount={}", pageCount); log.debug("Starting handleSplitByPageCount with pageCount={}", pageCount);
int currentPageCount = 0; int currentPageCount = 0;
log.debug("Creating initial output document"); log.debug("Creating initial output document");
PDDocument currentDoc = null; PDDocument currentDoc;
try { try {
currentDoc = pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument); currentDoc = pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument);
log.debug("Successfully created initial output document"); log.debug("Successfully created initial output document");
@ -387,7 +387,7 @@ public class SplitPdfBySizeController {
for (int i = 0; i < documentCount; i++) { for (int i = 0; i < documentCount; i++) {
log.debug("Creating document {} of {}", i + 1, documentCount); log.debug("Creating document {} of {}", i + 1, documentCount);
PDDocument currentDoc = null; PDDocument currentDoc;
try { try {
currentDoc = pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument); currentDoc = pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument);
log.debug("Successfully created document {} of {}", i + 1, documentCount); log.debug("Successfully created document {} of {}", i + 1, documentCount);

View File

@ -69,12 +69,11 @@ public class ConvertImgPDFController {
Path tempFile = null; Path tempFile = null;
Path tempOutputDir = null; Path tempOutputDir = null;
Path tempPdfPath = null; Path tempPdfPath = null;
byte[] result = null; byte[] result;
String[] pageOrderArr = String[] pageOrderArr =
(pageNumbers != null && !pageNumbers.trim().isEmpty()) (pageNumbers != null && !pageNumbers.trim().isEmpty())
? pageNumbers.split(",") ? pageNumbers.split(",")
: new String[] {"all"}; : new String[] {"all"};
;
try { try {
// Load the input PDF // Load the input PDF
byte[] newPdfBytes = rearrangePdfPages(file, pageOrderArr); byte[] newPdfBytes = rearrangePdfPages(file, pageOrderArr);
@ -102,7 +101,7 @@ public class ConvertImgPDFController {
singleImage, singleImage,
dpi, dpi,
filename); filename);
if (result == null || result.length == 0) { if (result.length == 0) {
log.error("resultant bytes for {} is null, error converting ", filename); log.error("resultant bytes for {} is null, error converting ", filename);
} }
if ("webp".equalsIgnoreCase(imageFormat) && !CheckProgramInstall.isPythonAvailable()) { if ("webp".equalsIgnoreCase(imageFormat) && !CheckProgramInstall.isPythonAvailable()) {
@ -159,7 +158,7 @@ public class ConvertImgPDFController {
"No WebP files were created. " + resultProcess.getMessages()); "No WebP files were created. " + resultProcess.getMessages());
} }
byte[] bodyBytes = new byte[0]; byte[] bodyBytes;
if (webpFiles.size() == 1) { if (webpFiles.size() == 1) {
// Return the single WebP file directly // Return the single WebP file directly
@ -179,7 +178,7 @@ public class ConvertImgPDFController {
} }
// Clean up the temporary files // Clean up the temporary files
Files.deleteIfExists(tempFile); Files.deleteIfExists(tempFile);
if (tempOutputDir != null) FileUtils.deleteDirectory(tempOutputDir.toFile()); FileUtils.deleteDirectory(tempOutputDir.toFile());
result = bodyBytes; result = bodyBytes;
} }

View File

@ -88,7 +88,7 @@ public class ConvertOfficeController {
return tempOutputFile.toFile(); return tempOutputFile.toFile();
} finally { } finally {
// Clean up the temporary files // Clean up the temporary files
if (tempInputFile != null) Files.deleteIfExists(tempInputFile); Files.deleteIfExists(tempInputFile);
} }
} }

View File

@ -123,7 +123,7 @@ public class ConvertPDFToPDFA {
preProcessedFile = preProcessHighlights(tempInputFile.toFile()); preProcessedFile = preProcessHighlights(tempInputFile.toFile());
} }
Set<String> missingFonts = new HashSet<>(); Set<String> missingFonts = new HashSet<>();
boolean needImgs = false; boolean needImgs;
try (PDDocument doc = Loader.loadPDF(preProcessedFile)) { try (PDDocument doc = Loader.loadPDF(preProcessedFile)) {
missingFonts = findUnembeddedFontNames(doc); missingFonts = findUnembeddedFontNames(doc);
needImgs = (pdfaPart == 1) && hasTransparentImages(doc); needImgs = (pdfaPart == 1) && hasTransparentImages(doc);
@ -285,7 +285,7 @@ public class ConvertPDFToPDFA {
if (fontStream == null) continue; if (fontStream == null) continue;
try (InputStream in = fontStream.createInputStream()) { try (InputStream in = fontStream.createInputStream()) {
PDFont newFont = null; PDFont newFont;
try { try {
newFont = PDType0Font.load(baseDoc, in, false); newFont = PDType0Font.load(baseDoc, in, false);
} catch (IOException e1) { } catch (IOException e1) {

View File

@ -84,7 +84,7 @@ public class FilterController {
PDDocument document = pdfDocumentFactory.load(inputFile); PDDocument document = pdfDocumentFactory.load(inputFile);
int actualPageCount = document.getNumberOfPages(); int actualPageCount = document.getNumberOfPages();
boolean valid = false; boolean valid;
// Perform the comparison // Perform the comparison
switch (comparator) { switch (comparator) {
case "Greater": case "Greater":
@ -127,7 +127,7 @@ public class FilterController {
PDRectangle standardSize = PdfUtils.textToPageSize(standardPageSize); PDRectangle standardSize = PdfUtils.textToPageSize(standardPageSize);
float standardArea = standardSize.getWidth() * standardSize.getHeight(); float standardArea = standardSize.getWidth() * standardSize.getHeight();
boolean valid = false; boolean valid;
// Perform the comparison // Perform the comparison
switch (comparator) { switch (comparator) {
case "Greater": case "Greater":
@ -160,7 +160,7 @@ public class FilterController {
// Get the file size // Get the file size
long actualFileSize = inputFile.getSize(); long actualFileSize = inputFile.getSize();
boolean valid = false; boolean valid;
// Perform the comparison // Perform the comparison
switch (comparator) { switch (comparator) {
case "Greater": case "Greater":
@ -196,7 +196,7 @@ public class FilterController {
// Get the rotation of the first page // Get the rotation of the first page
PDPage firstPage = document.getPage(0); PDPage firstPage = document.getPage(0);
int actualRotation = firstPage.getRotation(); int actualRotation = firstPage.getRotation();
boolean valid = false; boolean valid;
// Perform the comparison // Perform the comparison
switch (comparator) { switch (comparator) {
case "Greater": case "Greater":

View File

@ -75,7 +75,7 @@ public class AutoRenameController {
} }
private void processLine() { private void processLine() {
if (lineBuilder.length() > 0 && lineCount < LINE_LIMIT) { if (!lineBuilder.isEmpty() && lineCount < LINE_LIMIT) {
lineInfos.add(new LineInfo(lineBuilder.toString(), maxFontSizeInLine)); lineInfos.add(new LineInfo(lineBuilder.toString(), maxFontSizeInLine));
} }
} }

View File

@ -118,7 +118,7 @@ public class AutoSplitPdfController {
PDDocument document = null; PDDocument document = null;
List<PDDocument> splitDocuments = new ArrayList<>(); List<PDDocument> splitDocuments = new ArrayList<>();
Path zipFile = null; Path zipFile = null;
byte[] data = null; byte[] data;
try { try {
document = pdfDocumentFactory.load(file.getInputStream()); document = pdfDocumentFactory.load(file.getInputStream());

View File

@ -782,11 +782,8 @@ public class CompressController {
// Check if we can't increase the level further // Check if we can't increase the level further
if (newOptimizeLevel == optimizeLevel) { if (newOptimizeLevel == optimizeLevel) {
if (autoMode) { log.info("Maximum optimization level reached without meeting target size.");
log.info( sizeMet = true;
"Maximum optimization level reached without meeting target size.");
sizeMet = true;
}
} else { } else {
// Reset flags for next iteration with higher optimization level // Reset flags for next iteration with higher optimization level
imageCompressionApplied = false; imageCompressionApplied = false;
@ -888,7 +885,7 @@ public class CompressController {
command.add("-sOutputFile=" + gsOutputFile.toString()); command.add("-sOutputFile=" + gsOutputFile.toString());
command.add(currentFile.toString()); command.add(currentFile.toString());
ProcessExecutorResult returnCode = null; ProcessExecutorResult returnCode;
try { try {
returnCode = returnCode =
ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT) ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT)

View File

@ -69,7 +69,7 @@ public class ExtractImageScansController {
List<String> images = new ArrayList<>(); List<String> images = new ArrayList<>();
List<Path> tempImageFiles = new ArrayList<>(); List<Path> tempImageFiles = new ArrayList<>();
Path tempInputFile = null; Path tempInputFile;
Path tempZipFile = null; Path tempZipFile = null;
List<Path> tempDirs = new ArrayList<>(); List<Path> tempDirs = new ArrayList<>();
@ -181,7 +181,7 @@ public class ExtractImageScansController {
return WebResponseUtils.bytesToWebResponse( return WebResponseUtils.bytesToWebResponse(
zipBytes, outputZipFilename, MediaType.APPLICATION_OCTET_STREAM); zipBytes, outputZipFilename, MediaType.APPLICATION_OCTET_STREAM);
} }
if (processedImageBytes.size() == 0) { if (processedImageBytes.isEmpty()) {
throw new IllegalArgumentException("No images detected"); throw new IllegalArgumentException("No images detected");
} else { } else {

View File

@ -143,7 +143,7 @@ public class MetadataController {
} }
} }
} }
if (creationDate != null && creationDate.length() > 0) { if (creationDate != null && !creationDate.isEmpty()) {
Calendar creationDateCal = Calendar.getInstance(); Calendar creationDateCal = Calendar.getInstance();
try { try {
creationDateCal.setTime( creationDateCal.setTime(
@ -155,7 +155,7 @@ public class MetadataController {
} else { } else {
info.setCreationDate(null); info.setCreationDate(null);
} }
if (modificationDate != null && modificationDate.length() > 0) { if (modificationDate != null && !modificationDate.isEmpty()) {
Calendar modificationDateCal = Calendar.getInstance(); Calendar modificationDateCal = Calendar.getInstance();
try { try {
modificationDateCal.setTime( modificationDateCal.setTime(

View File

@ -126,7 +126,7 @@ public class OCRController {
try { try {
// Use OCRmyPDF if available (no fallback - error if it fails) // Use OCRmyPDF if available (no fallback - error if it fails)
if (isOcrMyPdfEnabled()) { if (isOcrMyPdfEnabled()) {
if (sidecar != null && sidecar) { if (sidecar) {
sidecarTextFile = new TempFile(tempFileManager, ".txt"); sidecarTextFile = new TempFile(tempFileManager, ".txt");
} }
@ -165,7 +165,7 @@ public class OCRController {
.replaceFirst("[.][^.]+$", "") .replaceFirst("[.][^.]+$", "")
+ "_OCR.pdf"; + "_OCR.pdf";
if (sidecar != null && sidecar && sidecarTextFile != null) { if (sidecar && sidecarTextFile != null) {
// Create a zip file containing both the PDF and the text file // Create a zip file containing both the PDF and the text file
String outputZipFilename = String outputZipFilename =
Filenames.toSimpleFileName(inputFile.getOriginalFilename()) Filenames.toSimpleFileName(inputFile.getOriginalFilename())
@ -257,7 +257,7 @@ public class OCRController {
if (cleanFinal != null && cleanFinal) { if (cleanFinal != null && cleanFinal) {
command.add("--clean-final"); command.add("--clean-final");
} }
if (ocrType != null && !"".equals(ocrType)) { if (ocrType != null && !ocrType.isEmpty()) {
if ("skip-text".equals(ocrType)) { if ("skip-text".equals(ocrType)) {
command.add("--skip-text"); command.add("--skip-text");
} else if ("force-ocr".equals(ocrType)) { } else if ("force-ocr".equals(ocrType)) {
@ -338,7 +338,7 @@ public class OCRController {
for (int pageNum = 0; pageNum < pageCount; pageNum++) { for (int pageNum = 0; pageNum < pageCount; pageNum++) {
PDPage page = document.getPage(pageNum); PDPage page = document.getPage(pageNum);
boolean hasText = false; boolean hasText;
// Check for existing text // Check for existing text
try (PDDocument tempDoc = new PDDocument()) { try (PDDocument tempDoc = new PDDocument()) {

View File

@ -183,7 +183,7 @@ public class StampController {
float margin, float margin,
String colorString) // Y override String colorString) // Y override
throws IOException { throws IOException {
String resourceDir = ""; String resourceDir;
PDFont font = new PDType1Font(Standard14Fonts.FontName.HELVETICA); PDFont font = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
switch (alphabet) { switch (alphabet) {
case "arabic": case "arabic":
@ -207,18 +207,16 @@ public class StampController {
break; break;
} }
if (!"".equals(resourceDir)) { ClassPathResource classPathResource = new ClassPathResource(resourceDir);
ClassPathResource classPathResource = new ClassPathResource(resourceDir); String fileExtension = resourceDir.substring(resourceDir.lastIndexOf("."));
String fileExtension = resourceDir.substring(resourceDir.lastIndexOf("."));
// Use TempFile with try-with-resources for automatic cleanup // Use TempFile with try-with-resources for automatic cleanup
try (TempFile tempFileWrapper = new TempFile(tempFileManager, fileExtension)) { try (TempFile tempFileWrapper = new TempFile(tempFileManager, fileExtension)) {
File tempFile = tempFileWrapper.getFile(); File tempFile = tempFileWrapper.getFile();
try (InputStream is = classPathResource.getInputStream(); try (InputStream is = classPathResource.getInputStream();
FileOutputStream os = new FileOutputStream(tempFile)) { FileOutputStream os = new FileOutputStream(tempFile)) {
IOUtils.copy(is, os); IOUtils.copy(is, os);
font = PDType0Font.load(document, tempFile); font = PDType0Font.load(document, tempFile);
}
} }
} }

View File

@ -68,7 +68,7 @@ public class PipelineController {
try { try {
List<Resource> inputFiles = processor.generateInputFiles(files); List<Resource> inputFiles = processor.generateInputFiles(files);
if (inputFiles == null || inputFiles.size() == 0) { if (inputFiles == null || inputFiles.isEmpty()) {
return null; return null;
} }
PipelineResult result = processor.runPipelineAgainstFiles(inputFiles, config); PipelineResult result = processor.runPipelineAgainstFiles(inputFiles, config);

View File

@ -115,7 +115,7 @@ public class PipelineDirectoryProcessor {
log.info("Handling directory: {}", dir); log.info("Handling directory: {}", dir);
Path processingDir = createProcessingDirectory(dir); Path processingDir = createProcessingDirectory(dir);
Optional<Path> jsonFileOptional = findJsonFile(dir); Optional<Path> jsonFileOptional = findJsonFile(dir);
if (!jsonFileOptional.isPresent()) { if (jsonFileOptional.isEmpty()) {
log.warn("No .JSON settings file found. No processing will happen for dir {}.", dir); log.warn("No .JSON settings file found. No processing will happen for dir {}.", dir);
return; return;
} }
@ -150,7 +150,7 @@ public class PipelineDirectoryProcessor {
for (PipelineOperation operation : config.getOperations()) { for (PipelineOperation operation : config.getOperations()) {
validateOperation(operation); validateOperation(operation);
File[] files = collectFilesForProcessing(dir, jsonFile, operation); File[] files = collectFilesForProcessing(dir, jsonFile, operation);
if (files == null || files.length == 0) { if (files.length == 0) {
log.debug("No files detected for {} ", dir); log.debug("No files detected for {} ", dir);
return; return;
} }

View File

@ -119,7 +119,7 @@ public class GetInfoOnPDF {
if (!ap.canModifyAnnotations()) restrictedPermissions.add("annotation modification"); if (!ap.canModifyAnnotations()) restrictedPermissions.add("annotation modification");
if (!ap.canPrint()) restrictedPermissions.add("printing"); if (!ap.canPrint()) restrictedPermissions.add("printing");
if (restrictedPermissions.size() > 0) { if (!restrictedPermissions.isEmpty()) {
summaryData.set("restrictedPermissions", restrictedPermissions); summaryData.set("restrictedPermissions", restrictedPermissions);
summaryData.put("restrictedPermissionsCount", restrictedPermissions.size()); summaryData.put("restrictedPermissionsCount", restrictedPermissions.size());
} }
@ -193,7 +193,7 @@ public class GetInfoOnPDF {
public ResponseEntity<byte[]> getPdfInfo(@ModelAttribute PDFFile request) throws IOException { public ResponseEntity<byte[]> getPdfInfo(@ModelAttribute PDFFile request) throws IOException {
MultipartFile inputFile = request.getFileInput(); MultipartFile inputFile = request.getFileInput();
boolean readonly = true; boolean readonly = true;
try (PDDocument pdfBoxDoc = pdfDocumentFactory.load(inputFile, readonly); ) { try (PDDocument pdfBoxDoc = pdfDocumentFactory.load(inputFile, readonly)) {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ObjectNode jsonOutput = objectMapper.createObjectNode(); ObjectNode jsonOutput = objectMapper.createObjectNode();
@ -249,7 +249,6 @@ public class GetInfoOnPDF {
docInfoNode.put("PDF version", pdfBoxDoc.getVersion()); docInfoNode.put("PDF version", pdfBoxDoc.getVersion());
docInfoNode.put("Trapped", info.getTrapped()); docInfoNode.put("Trapped", info.getTrapped());
docInfoNode.put("Page Mode", getPageModeDescription(pageMode)); docInfoNode.put("Page Mode", getPageModeDescription(pageMode));
;
PDAcroForm acroForm = pdfBoxDoc.getDocumentCatalog().getAcroForm(); PDAcroForm acroForm = pdfBoxDoc.getDocumentCatalog().getAcroForm();
@ -263,7 +262,7 @@ public class GetInfoOnPDF {
// Generate structured summary data about PDF characteristics // Generate structured summary data about PDF characteristics
ObjectNode summaryData = generatePDFSummaryData(pdfBoxDoc); ObjectNode summaryData = generatePDFSummaryData(pdfBoxDoc);
if (summaryData != null && summaryData.size() > 0) { if (summaryData != null && !summaryData.isEmpty()) {
jsonOutput.set("SummaryData", summaryData); jsonOutput.set("SummaryData", summaryData);
} }
@ -788,7 +787,7 @@ public class GetInfoOnPDF {
// Recursively explore child elements // Recursively explore child elements
ArrayNode childElements = exploreStructureTree(structureElement.getKids()); ArrayNode childElements = exploreStructureTree(structureElement.getKids());
if (childElements.size() > 0) { if (!childElements.isEmpty()) {
elementNode.set("Children", childElements); elementNode.set("Children", childElements);
} }
} }

View File

@ -176,11 +176,9 @@ public class SanitizeController {
private void sanitizeLinks(PDDocument document) throws IOException { private void sanitizeLinks(PDDocument document) throws IOException {
for (PDPage page : document.getPages()) { for (PDPage page : document.getPages()) {
for (PDAnnotation annotation : page.getAnnotations()) { for (PDAnnotation annotation : page.getAnnotations()) {
if (annotation != null && annotation instanceof PDAnnotationLink linkAnnotation) { if (annotation instanceof PDAnnotationLink linkAnnotation) {
PDAction action = linkAnnotation.getAction(); PDAction action = linkAnnotation.getAction();
if (action != null if ((action instanceof PDActionLaunch || action instanceof PDActionURI)) {
&& (action instanceof PDActionLaunch
|| action instanceof PDActionURI)) {
linkAnnotation.setAction(null); linkAnnotation.setAction(null);
} }
} }

View File

@ -191,17 +191,15 @@ public class WatermarkController {
break; break;
} }
if (!"".equals(resourceDir)) { ClassPathResource classPathResource = new ClassPathResource(resourceDir);
ClassPathResource classPathResource = new ClassPathResource(resourceDir); String fileExtension = resourceDir.substring(resourceDir.lastIndexOf("."));
String fileExtension = resourceDir.substring(resourceDir.lastIndexOf(".")); File tempFile = Files.createTempFile("NotoSansFont", fileExtension).toFile();
File tempFile = Files.createTempFile("NotoSansFont", fileExtension).toFile(); try (InputStream is = classPathResource.getInputStream();
try (InputStream is = classPathResource.getInputStream(); FileOutputStream os = new FileOutputStream(tempFile)) {
FileOutputStream os = new FileOutputStream(tempFile)) { IOUtils.copy(is, os);
IOUtils.copy(is, os); font = PDType0Font.load(document, tempFile);
font = PDType0Font.load(document, tempFile); } finally {
} finally { Files.deleteIfExists(tempFile.toPath());
if (tempFile != null) Files.deleteIfExists(tempFile.toPath());
}
} }
contentStream.setFont(font, fontSize); contentStream.setFont(font, fontSize);

View File

@ -75,7 +75,7 @@ public class GeneralWebController {
new ObjectMapper() new ObjectMapper()
.readValue(config, new TypeReference<Map<String, Object>>() {}); .readValue(config, new TypeReference<Map<String, Object>>() {});
String name = (String) jsonContent.get("name"); String name = (String) jsonContent.get("name");
if (name == null || name.length() < 1) { if (name == null || name.isEmpty()) {
String filename = String filename =
jsonFiles jsonFiles
.get(pipelineConfigs.indexOf(config)) .get(pipelineConfigs.indexOf(config))
@ -92,7 +92,7 @@ public class GeneralWebController {
log.error("exception", e); log.error("exception", e);
} }
} }
if (pipelineConfigsWithNames.size() == 0) { if (pipelineConfigsWithNames.isEmpty()) {
Map<String, String> configWithName = new HashMap<>(); Map<String, String> configWithName = new HashMap<>();
configWithName.put("json", ""); configWithName.put("json", "");
configWithName.put("name", "No preloaded configs found"); configWithName.put("name", "No preloaded configs found");

View File

@ -52,7 +52,7 @@ public class ApiDocService {
} }
public List<String> getExtensionTypes(boolean output, String operationName) { public List<String> getExtensionTypes(boolean output, String operationName) {
if (outputToFileTypes.size() == 0) { if (outputToFileTypes.isEmpty()) {
outputToFileTypes.put("PDF", Arrays.asList("pdf")); outputToFileTypes.put("PDF", Arrays.asList("pdf"));
outputToFileTypes.put( outputToFileTypes.put(
"IMAGE", "IMAGE",
@ -74,7 +74,7 @@ public class ApiDocService {
"BOOK", Arrays.asList("epub", "mobi", "azw3", "fb2", "txt", "docx")); "BOOK", Arrays.asList("epub", "mobi", "azw3", "fb2", "txt", "docx"));
// type. // type.
} }
if (apiDocsJsonRootNode == null || apiDocumentation.size() == 0) { if (apiDocsJsonRootNode == null || apiDocumentation.isEmpty()) {
loadApiDocumentation(); loadApiDocumentation();
} }
if (!apiDocumentation.containsKey(operationName)) { if (!apiDocumentation.containsKey(operationName)) {
@ -138,7 +138,7 @@ public class ApiDocService {
} }
public boolean isValidOperation(String operationName, Map<String, Object> parameters) { public boolean isValidOperation(String operationName, Map<String, Object> parameters) {
if (apiDocumentation.size() == 0) { if (apiDocumentation.isEmpty()) {
loadApiDocumentation(); loadApiDocumentation();
} }
if (!apiDocumentation.containsKey(operationName)) { if (!apiDocumentation.containsKey(operationName)) {
@ -149,7 +149,7 @@ public class ApiDocService {
} }
public boolean isMultiInput(String operationName) { public boolean isMultiInput(String operationName) {
if (apiDocsJsonRootNode == null || apiDocumentation.size() == 0) { if (apiDocsJsonRootNode == null || apiDocumentation.isEmpty()) {
loadApiDocumentation(); loadApiDocumentation();
} }
if (!apiDocumentation.containsKey(operationName)) { if (!apiDocumentation.containsKey(operationName)) {

View File

@ -31,7 +31,7 @@ public class MetricsAggregatorService {
public void aggregateAndSendMetrics() { public void aggregateAndSendMetrics() {
Map<String, Object> metrics = new HashMap<>(); Map<String, Object> metrics = new HashMap<>();
final boolean validateGetEndpoints = endpointInspector.getValidGetEndpoints().size() != 0; final boolean validateGetEndpoints = !endpointInspector.getValidGetEndpoints().isEmpty();
Search.in(meterRegistry) Search.in(meterRegistry)
.name("http.requests") .name("http.requests")
.counters() .counters()