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;
public String getAppName() {
return appName != null && appName.trim().length() > 0 ? appName : null;
return appName != null && !appName.trim().isEmpty() ? appName : null;
}
public String getHomeDescription() {
return homeDescription != null && homeDescription.trim().length() > 0
return homeDescription != null && !homeDescription.trim().isEmpty()
? homeDescription
: null;
}
public String getAppNameNavbar() {
return appNameNavbar != null && appNameNavbar.trim().length() > 0
? appNameNavbar
: null;
return appNameNavbar != null && !appNameNavbar.trim().isEmpty() ? appNameNavbar : null;
}
}

View File

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

View File

@ -74,7 +74,7 @@ public class PDFToFile {
Path tempInputFile = null;
Path tempOutputDir = null;
byte[] fileBytes;
String fileName = "temp.file";
String fileName;
try {
tempInputFile = Files.createTempFile("input_", ".pdf");
@ -167,7 +167,7 @@ public class PDFToFile {
Path tempInputFile = null;
Path tempOutputDir = null;
byte[] fileBytes;
String fileName = "temp.file";
String fileName;
try {
// Save the uploaded file to a temporary location
@ -230,7 +230,7 @@ public class PDFToFile {
// Get the original PDF file name without the extension
String originalPdfFileName = Filenames.toSimpleFileName(inputFile.getOriginalFilename());
if (originalPdfFileName == null || "".equals(originalPdfFileName.trim())) {
if (originalPdfFileName == null || originalPdfFileName.trim().isEmpty()) {
originalPdfFileName = "output.pdf";
}
// Assume file is pdf if no extension
@ -248,7 +248,7 @@ public class PDFToFile {
Path tempInputFile = null;
Path tempOutputDir = null;
byte[] fileBytes;
String fileName = "temp.file";
String fileName;
try {
// 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 {
return getAllImages(page.getResources()).size() > 0;
return !getAllImages(page.getResources()).isEmpty();
}
public static boolean hasTextOnPage(PDPage page, String phrase) throws IOException {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -69,7 +69,7 @@ public class ExtractImageScansController {
List<String> images = new ArrayList<>();
List<Path> tempImageFiles = new ArrayList<>();
Path tempInputFile = null;
Path tempInputFile;
Path tempZipFile = null;
List<Path> tempDirs = new ArrayList<>();
@ -181,7 +181,7 @@ public class ExtractImageScansController {
return WebResponseUtils.bytesToWebResponse(
zipBytes, outputZipFilename, MediaType.APPLICATION_OCTET_STREAM);
}
if (processedImageBytes.size() == 0) {
if (processedImageBytes.isEmpty()) {
throw new IllegalArgumentException("No images detected");
} 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();
try {
creationDateCal.setTime(
@ -155,7 +155,7 @@ public class MetadataController {
} else {
info.setCreationDate(null);
}
if (modificationDate != null && modificationDate.length() > 0) {
if (modificationDate != null && !modificationDate.isEmpty()) {
Calendar modificationDateCal = Calendar.getInstance();
try {
modificationDateCal.setTime(

View File

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

View File

@ -183,7 +183,7 @@ public class StampController {
float margin,
String colorString) // Y override
throws IOException {
String resourceDir = "";
String resourceDir;
PDFont font = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
switch (alphabet) {
case "arabic":
@ -207,7 +207,6 @@ public class StampController {
break;
}
if (!"".equals(resourceDir)) {
ClassPathResource classPathResource = new ClassPathResource(resourceDir);
String fileExtension = resourceDir.substring(resourceDir.lastIndexOf("."));
@ -220,7 +219,6 @@ public class StampController {
font = PDType0Font.load(document, tempFile);
}
}
}
contentStream.setFont(font, fontSize);

View File

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

View File

@ -115,7 +115,7 @@ public class PipelineDirectoryProcessor {
log.info("Handling directory: {}", dir);
Path processingDir = createProcessingDirectory(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);
return;
}
@ -150,7 +150,7 @@ public class PipelineDirectoryProcessor {
for (PipelineOperation operation : config.getOperations()) {
validateOperation(operation);
File[] files = collectFilesForProcessing(dir, jsonFile, operation);
if (files == null || files.length == 0) {
if (files.length == 0) {
log.debug("No files detected for {} ", dir);
return;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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