diff --git a/src/main/java/stirling/software/SPDF/LibreOfficeListener.java b/src/main/java/stirling/software/SPDF/LibreOfficeListener.java index 96c4d270..06e19512 100644 --- a/src/main/java/stirling/software/SPDF/LibreOfficeListener.java +++ b/src/main/java/stirling/software/SPDF/LibreOfficeListener.java @@ -6,11 +6,15 @@ import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.github.pixee.security.SystemCommand; public class LibreOfficeListener { - private static final long ACTIVITY_TIMEOUT = 20 * 60 * 1000; // 20 minutes + private static final Logger logger = LoggerFactory.getLogger(LibreOfficeListener.class); + private static final long ACTIVITY_TIMEOUT = 20L * 60 * 1000; // 20 minutes private static final LibreOfficeListener INSTANCE = new LibreOfficeListener(); private static final int LISTENER_PORT = 2002; @@ -27,14 +31,12 @@ public class LibreOfficeListener { private LibreOfficeListener() {} private boolean isListenerRunning() { - try { - System.out.println("waiting for listener to start"); - Socket socket = new Socket(); + System.out.println("waiting for listener to start"); + try (Socket socket = new Socket()) { socket.connect( new InetSocketAddress("localhost", 2002), 1000); // Timeout after 1 second - socket.close(); return true; - } catch (IOException e) { + } catch (Exception e) { return false; } } @@ -63,6 +65,7 @@ public class LibreOfficeListener { try { Thread.sleep(5000); // Check for inactivity every 5 seconds } catch (InterruptedException e) { + Thread.currentThread().interrupt(); break; } } @@ -80,8 +83,8 @@ public class LibreOfficeListener { try { Thread.sleep(1000); } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + Thread.currentThread().interrupt(); + logger.error("exception", e); } // Check every 1 second } } diff --git a/src/main/java/stirling/software/SPDF/config/AppConfig.java b/src/main/java/stirling/software/SPDF/config/AppConfig.java index e71b01cd..bad35880 100644 --- a/src/main/java/stirling/software/SPDF/config/AppConfig.java +++ b/src/main/java/stirling/software/SPDF/config/AppConfig.java @@ -7,6 +7,8 @@ import java.nio.file.Paths; import java.util.Properties; import java.util.function.Predicate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -24,6 +26,8 @@ import stirling.software.SPDF.model.ApplicationProperties; @Lazy public class AppConfig { + private static final Logger logger = LoggerFactory.getLogger(AppConfig.class); + @Autowired ApplicationProperties applicationProperties; @Bean @@ -56,7 +60,7 @@ public class AppConfig { props.load(resource.getInputStream()); return props.getProperty("version"); } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); } return "0.0.0"; } diff --git a/src/main/java/stirling/software/SPDF/config/MetricsFilter.java b/src/main/java/stirling/software/SPDF/config/MetricsFilter.java index 6f2751a9..876613f4 100644 --- a/src/main/java/stirling/software/SPDF/config/MetricsFilter.java +++ b/src/main/java/stirling/software/SPDF/config/MetricsFilter.java @@ -36,7 +36,6 @@ public class MetricsFilter extends OncePerRequestFilter { || uri.startsWith("/v1/api-docs") || uri.endsWith("robots.txt") || uri.startsWith("/images") - || uri.startsWith("/images") || uri.endsWith(".png") || uri.endsWith(".ico") || uri.endsWith(".css") diff --git a/src/main/java/stirling/software/SPDF/config/security/CustomAuthenticationFailureHandler.java b/src/main/java/stirling/software/SPDF/config/security/CustomAuthenticationFailureHandler.java index 85447376..02911622 100644 --- a/src/main/java/stirling/software/SPDF/config/security/CustomAuthenticationFailureHandler.java +++ b/src/main/java/stirling/software/SPDF/config/security/CustomAuthenticationFailureHandler.java @@ -49,10 +49,12 @@ public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationF } String username = request.getParameter("username"); - if (username != null && !isDemoUser(username)) { + Optional optUser = userService.findByUsernameIgnoreCase(username); + + if (username != null && optUser.isPresent() && !isDemoUser(optUser)) { logger.info( "Remaining attempts for user {}: {}", - username, + optUser.get().getUsername(), loginAttemptService.getRemainingAttempts(username)); loginAttemptService.loginFailed(username); if (loginAttemptService.isBlocked(username) @@ -70,8 +72,7 @@ public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationF super.onAuthenticationFailure(request, response, exception); } - private boolean isDemoUser(String username) { - Optional user = userService.findByUsernameIgnoreCase(username); + private boolean isDemoUser(Optional user) { return user.isPresent() && user.get().getAuthorities().stream() .anyMatch(authority -> "ROLE_DEMO_USER".equals(authority.getAuthority())); diff --git a/src/main/java/stirling/software/SPDF/config/security/LoginAttemptService.java b/src/main/java/stirling/software/SPDF/config/security/LoginAttemptService.java index f398f13c..da3e216e 100644 --- a/src/main/java/stirling/software/SPDF/config/security/LoginAttemptService.java +++ b/src/main/java/stirling/software/SPDF/config/security/LoginAttemptService.java @@ -33,7 +33,6 @@ public class LoginAttemptService { } public void loginSucceeded(String key) { - logger.info(key + " " + attemptsCache.mappingCount()); if (key == null || key.trim().isEmpty()) { return; } diff --git a/src/main/java/stirling/software/SPDF/config/security/oauth2/CustomOAuth2LogoutSuccessHandler.java b/src/main/java/stirling/software/SPDF/config/security/oauth2/CustomOAuth2LogoutSuccessHandler.java index f8b76ab9..e209d0cd 100644 --- a/src/main/java/stirling/software/SPDF/config/security/oauth2/CustomOAuth2LogoutSuccessHandler.java +++ b/src/main/java/stirling/software/SPDF/config/security/oauth2/CustomOAuth2LogoutSuccessHandler.java @@ -52,7 +52,7 @@ public class CustomOAuth2LogoutSuccessHandler extends SimpleUrlLogoutSuccessHand issuer = provider.getIssuer(); clientId = provider.getClientId(); } catch (Exception e) { - e.printStackTrace(); + logger.error("exception", e); } } else { @@ -60,13 +60,13 @@ public class CustomOAuth2LogoutSuccessHandler extends SimpleUrlLogoutSuccessHand issuer = oauth.getIssuer(); clientId = oauth.getClientId(); } - + String errorMessage = ""; if (request.getParameter("oauth2AuthenticationErrorWeb") != null) { param = "erroroauth=oauth2AuthenticationErrorWeb"; - } else if (request.getParameter("error") != null) { - param = "error=" + request.getParameter("error"); - } else if (request.getParameter("erroroauth") != null) { - param = "erroroauth=" + request.getParameter("erroroauth"); + } else if ((errorMessage = request.getParameter("error")) != null) { + param = "error=" + sanitizeInput(errorMessage); + } else if ((errorMessage = request.getParameter("erroroauth")) != null) { + param = "erroroauth=" + sanitizeInput(errorMessage); } else if (request.getParameter("oauth2AutoCreateDisabled") != null) { param = "error=oauth2AutoCreateDisabled"; } @@ -115,4 +115,8 @@ public class CustomOAuth2LogoutSuccessHandler extends SimpleUrlLogoutSuccessHand break; } } + + private String sanitizeInput(String input) { + return input.replaceAll("[^a-zA-Z0-9 ]", ""); + } } diff --git a/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySectionsController.java b/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySectionsController.java index d9077d9e..ce4a61d4 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySectionsController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySectionsController.java @@ -18,6 +18,8 @@ import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.util.Matrix; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ModelAttribute; @@ -38,6 +40,9 @@ import stirling.software.SPDF.utils.WebResponseUtils; @Tag(name = "General", description = "General APIs") public class SplitPdfBySectionsController { + private static final Logger logger = + LoggerFactory.getLogger(SplitPdfBySectionsController.class); + @PostMapping(value = "/split-pdf-by-sections", consumes = "multipart/form-data") @Operation( summary = "Split PDF pages into smaller sections", @@ -92,7 +97,7 @@ public class SplitPdfBySectionsController { if (sectionNum == horiz * verti) pageNum++; } } catch (Exception e) { - e.printStackTrace(); + logger.error("exception", e); } finally { data = Files.readAllBytes(zipFile); Files.deleteIfExists(zipFile); diff --git a/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java b/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java index 40ac2d16..b3772b3b 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java @@ -10,6 +10,8 @@ import java.util.zip.ZipOutputStream; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ModelAttribute; @@ -31,6 +33,8 @@ import stirling.software.SPDF.utils.WebResponseUtils; @Tag(name = "General", description = "General APIs") public class SplitPdfBySizeController { + private static final Logger logger = LoggerFactory.getLogger(SplitPdfBySizeController.class); + @PostMapping(value = "/split-by-size-or-count", consumes = "multipart/form-data") @Operation( summary = "Auto split PDF pages into separate documents based on size or count", @@ -66,7 +70,7 @@ public class SplitPdfBySizeController { } } catch (Exception e) { - e.printStackTrace(); + logger.error("exception", e); } finally { data = Files.readAllBytes(zipFile); Files.deleteIfExists(zipFile); diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java index 23c08f26..d57a8bda 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java @@ -15,6 +15,8 @@ import java.util.zip.ZipOutputStream; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ModelAttribute; @@ -43,6 +45,7 @@ import stirling.software.SPDF.utils.WebResponseUtils; @Tag(name = "Misc", description = "Miscellaneous APIs") public class AutoSplitPdfController { + private static final Logger logger = LoggerFactory.getLogger(AutoSplitPdfController.class); private static final String QR_CONTENT = "https://github.com/Stirling-Tools/Stirling-PDF"; private static final String QR_CONTENT_OLD = "https://github.com/Frooodle/Stirling-PDF"; @@ -115,7 +118,7 @@ public class AutoSplitPdfController { zipOut.closeEntry(); } } catch (Exception e) { - e.printStackTrace(); + logger.error("exception", e); } finally { data = Files.readAllBytes(zipFile); Files.deleteIfExists(zipFile); diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java index 73dab071..59fc0be7 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java @@ -106,7 +106,7 @@ public class BlankPageController { .replaceFirst("[.][^.]+$", "") + "_blanksRemoved.pdf"); } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } finally { if (document != null) document.close(); diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/FakeScanControllerWIP.java b/src/main/java/stirling/software/SPDF/controller/api/misc/FakeScanControllerWIP.java index 2400c0d3..d4c4ce05 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/misc/FakeScanControllerWIP.java +++ b/src/main/java/stirling/software/SPDF/controller/api/misc/FakeScanControllerWIP.java @@ -110,8 +110,8 @@ public class FakeScanControllerWIP { private BufferedImage rotate(BufferedImage image, double rotation) { double rotationRequired = Math.toRadians(rotation); - double locationX = image.getWidth() / 2; - double locationY = image.getHeight() / 2; + double locationX = (double) image.getWidth() / 2; + double locationY = (double) image.getHeight() / 2; AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC); @@ -127,8 +127,8 @@ public class FakeScanControllerWIP { for (int i = -radius; i <= radius; i++) { for (int j = -radius; j <= radius; j++) { - double xDistance = i * i; - double yDistance = j * j; + double xDistance = (double) i * i; + double yDistance = (double) j * j; double g = Math.exp(-(xDistance + yDistance) / (2 * sigma * sigma)); data[(i + radius) * size + j + radius] = (float) g; sum += g; @@ -137,7 +137,7 @@ public class FakeScanControllerWIP { // Normalize the kernel for (int i = 0; i < data.length; i++) { - data[i] /= sum; + if (sum != 0) data[i] /= sum; } Kernel kernel = new Kernel(size, size, data); @@ -166,7 +166,7 @@ public class FakeScanControllerWIP { 0, new Color(0, 0, 0, 1f), 0, - featherRadius * 2, + featherRadius * 2f, new Color(0, 0, 0, 0f))); g2.fillRect(0, 0, width, featherRadius); @@ -174,7 +174,7 @@ public class FakeScanControllerWIP { g2.setPaint( new GradientPaint( 0, - height - featherRadius * 2, + height - featherRadius * 2f, new Color(0, 0, 0, 0f), 0, height, @@ -187,7 +187,7 @@ public class FakeScanControllerWIP { 0, 0, new Color(0, 0, 0, 1f), - featherRadius * 2, + featherRadius * 2f, 0, new Color(0, 0, 0, 0f))); g2.fillRect(0, 0, featherRadius, height); @@ -195,7 +195,7 @@ public class FakeScanControllerWIP { // Right edge g2.setPaint( new GradientPaint( - width - featherRadius * 2, + width - featherRadius * 2f, 0, new Color(0, 0, 0, 0f), width, @@ -244,7 +244,7 @@ public class FakeScanControllerWIP { int y2 = y1 + random.nextInt(20) - 10; Path2D.Double hair = new Path2D.Double(); hair.moveTo(x1, y1); - hair.curveTo(x1, y1, (x1 + x2) / 2, (y1 + y2) / 2, x2, y2); + hair.curveTo(x1, y1, (double) (x1 + x2) / 2, (double) (y1 + y2) / 2, x2, y2); g2d.draw(hair); } diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/FlattenController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/FlattenController.java index bdc0a478..888d7670 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/misc/FlattenController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/misc/FlattenController.java @@ -12,6 +12,8 @@ import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; @@ -33,6 +35,8 @@ import stirling.software.SPDF.utils.WebResponseUtils; @Tag(name = "Misc", description = "Miscellaneous APIs") public class FlattenController { + private static final Logger logger = LoggerFactory.getLogger(FlattenController.class); + @PostMapping(consumes = "multipart/form-data", value = "/flatten") @Operation( summary = "Flatten PDF form fields or full page", @@ -73,7 +77,7 @@ public class FlattenController { contentStream.drawImage(pdImage, 0, 0, pageWidth, pageHeight); } } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); } } PdfUtils.setMetadataToPdf(newDocument, metadata); diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java index fec07380..4d51e0f8 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java @@ -11,6 +11,8 @@ import org.apache.pdfbox.Loader; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; @@ -30,6 +32,8 @@ import stirling.software.SPDF.utils.WebResponseUtils; @Tag(name = "Misc", description = "Miscellaneous APIs") public class MetadataController { + private static final Logger logger = LoggerFactory.getLogger(MetadataController.class); + private String checkUndefined(String entry) { // Check if the string is "undefined" if ("undefined".equals(entry)) { @@ -136,7 +140,7 @@ public class MetadataController { creationDateCal.setTime( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(creationDate)); } catch (ParseException e) { - e.printStackTrace(); + logger.error("exception", e); } info.setCreationDate(creationDateCal); } else { @@ -148,7 +152,7 @@ public class MetadataController { modificationDateCal.setTime( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(modificationDate)); } catch (ParseException e) { - e.printStackTrace(); + logger.error("exception", e); } info.setModificationDate(modificationDateCal); } else { diff --git a/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java b/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java index d066bd9a..6ff75ebd 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java @@ -148,7 +148,7 @@ public class CertSignController { doc.addSignature(signature, instance); doc.saveIncremental(output); } catch (Exception e) { - e.printStackTrace(); + logger.error("exception", e); } } diff --git a/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java b/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java index 9926da55..77f02524 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java +++ b/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java @@ -56,6 +56,8 @@ import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.xml.DomXmpParser; import org.apache.xmpbox.xml.XmpParsingException; import org.apache.xmpbox.xml.XmpSerializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ModelAttribute; @@ -79,6 +81,8 @@ import stirling.software.SPDF.utils.WebResponseUtils; @Tag(name = "Security", description = "Security APIs") public class GetInfoOnPDF { + private static final Logger logger = LoggerFactory.getLogger(GetInfoOnPDF.class); + static ObjectMapper objectMapper = new ObjectMapper(); @PostMapping(consumes = "multipart/form-data", value = "/get-info-on-pdf") @@ -220,7 +224,7 @@ public class GetInfoOnPDF { javascriptArray.add(jsNode); } } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); } } } @@ -253,7 +257,7 @@ public class GetInfoOnPDF { } } catch (Exception e) { // TODO Auto-generated catch block - e.printStackTrace(); + logger.error("exception", e); } boolean isPdfACompliant = checkForStandard(pdfBoxDoc, "PDF/A"); @@ -305,7 +309,7 @@ public class GetInfoOnPDF { new XmpSerializer().serialize(xmpMeta, os, true); xmpString = new String(os.toByteArray(), StandardCharsets.UTF_8); } catch (XmpParsingException | IOException e) { - e.printStackTrace(); + logger.error("exception", e); } } @@ -593,7 +597,7 @@ public class GetInfoOnPDF { MediaType.APPLICATION_JSON); } catch (Exception e) { - e.printStackTrace(); + logger.error("exception", e); } return null; } @@ -691,7 +695,7 @@ public class GetInfoOnPDF { Exception e) { // Catching general exception for brevity, ideally you'd catch specific // exceptions. - e.printStackTrace(); + logger.error("exception", e); } return false; diff --git a/src/main/java/stirling/software/SPDF/controller/web/AccountWebController.java b/src/main/java/stirling/software/SPDF/controller/web/AccountWebController.java index 904a8ba0..79a84ecb 100644 --- a/src/main/java/stirling/software/SPDF/controller/web/AccountWebController.java +++ b/src/main/java/stirling/software/SPDF/controller/web/AccountWebController.java @@ -262,8 +262,7 @@ public class AccountWebController { userRepository.findByUsernameIgnoreCase( username); // Assuming findByUsername method exists if (!user.isPresent()) { - // Handle error appropriately - return "redirect:/error"; // Example redirection in case of error + return "redirect:/error"; } // Convert settings map to JSON string @@ -273,8 +272,8 @@ public class AccountWebController { settingsJson = objectMapper.writeValueAsString(user.get().getSettings()); } catch (JsonProcessingException e) { // Handle JSON conversion error - e.printStackTrace(); - return "redirect:/error"; // Example redirection in case of error + logger.error("exception", e); + return "redirect:/error"; } String messageType = request.getParameter("messageType"); diff --git a/src/main/java/stirling/software/SPDF/controller/web/GeneralWebController.java b/src/main/java/stirling/software/SPDF/controller/web/GeneralWebController.java index 5615a3a6..bb730dc9 100644 --- a/src/main/java/stirling/software/SPDF/controller/web/GeneralWebController.java +++ b/src/main/java/stirling/software/SPDF/controller/web/GeneralWebController.java @@ -15,6 +15,8 @@ import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; @@ -33,6 +35,8 @@ import io.swagger.v3.oas.annotations.tags.Tag; @Tag(name = "General", description = "General APIs") public class GeneralWebController { + private static final Logger logger = LoggerFactory.getLogger(GeneralWebController.class); + @GetMapping("/pipeline") @Hidden public String pipelineForm(Model model) { @@ -74,7 +78,7 @@ public class GeneralWebController { } } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); } } if (pipelineConfigsWithNames.size() == 0) { diff --git a/src/main/java/stirling/software/SPDF/controller/web/HomeWebController.java b/src/main/java/stirling/software/SPDF/controller/web/HomeWebController.java index 94e83342..5ade5668 100644 --- a/src/main/java/stirling/software/SPDF/controller/web/HomeWebController.java +++ b/src/main/java/stirling/software/SPDF/controller/web/HomeWebController.java @@ -6,6 +6,8 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @@ -26,6 +28,8 @@ import stirling.software.SPDF.model.Dependency; @Controller public class HomeWebController { + private static final Logger logger = LoggerFactory.getLogger(HomeWebController.class); + @GetMapping("/about") @Hidden public String gameForm(Model model) { @@ -46,7 +50,7 @@ public class HomeWebController { mapper.readValue(json, new TypeReference>>() {}); model.addAttribute("dependencies", data.get("dependencies")); } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); } return "licenses"; } diff --git a/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java b/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java index 7f94791e..173bde0b 100644 --- a/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java +++ b/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java @@ -5,6 +5,8 @@ import java.util.List; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.media.Schema; @@ -19,6 +21,8 @@ import stirling.software.SPDF.utils.GeneralUtils; @EqualsAndHashCode(callSuper = true) public class PDFWithPageNums extends PDFFile { + private static final Logger logger = LoggerFactory.getLogger(PDFWithPageNums.class); + @Schema( 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')\"") @@ -31,7 +35,7 @@ public class PDFWithPageNums extends PDFFile { pageCount = Loader.loadPDF(getFileInput().getBytes()).getNumberOfPages(); } catch (IOException e) { // TODO Auto-generated catch block - e.printStackTrace(); + logger.error("exception", e); } return GeneralUtils.parsePageList(pageNumbers, pageCount, zeroCount); } diff --git a/src/main/java/stirling/software/SPDF/utils/GeneralUtils.java b/src/main/java/stirling/software/SPDF/utils/GeneralUtils.java index 03ae55ce..ae86d8c1 100644 --- a/src/main/java/stirling/software/SPDF/utils/GeneralUtils.java +++ b/src/main/java/stirling/software/SPDF/utils/GeneralUtils.java @@ -14,6 +14,8 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import com.fathzer.soft.javaluator.DoubleEvaluator; @@ -23,6 +25,8 @@ import io.github.pixee.security.Urls; public class GeneralUtils { + private static final Logger logger = LoggerFactory.getLogger(GeneralUtils.class); + public static File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException { File tempFile = Files.createTempFile("temp", null).toFile(); try (FileOutputStream os = new FileOutputStream(tempFile)) { @@ -234,7 +238,7 @@ public class GeneralUtils { try { Files.createDirectories(folder); } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); return false; } } diff --git a/src/main/java/stirling/software/SPDF/utils/PDFToFile.java b/src/main/java/stirling/software/SPDF/utils/PDFToFile.java index f5297a10..7c419220 100644 --- a/src/main/java/stirling/software/SPDF/utils/PDFToFile.java +++ b/src/main/java/stirling/software/SPDF/utils/PDFToFile.java @@ -14,6 +14,8 @@ import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -24,6 +26,7 @@ import io.github.pixee.security.Filenames; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; public class PDFToFile { + private static final Logger logger = LoggerFactory.getLogger(PDFToFile.class); public ResponseEntity processPdfToHtml(MultipartFile inputFile) throws IOException, InterruptedException { @@ -67,18 +70,20 @@ public class PDFToFile { // Return output files in a ZIP archive fileName = pdfBaseName + "ToHtml.zip"; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream); - - for (File outputFile : outputFiles) { - ZipEntry entry = new ZipEntry(outputFile.getName()); - zipOutputStream.putNextEntry(entry); - FileInputStream fis = new FileInputStream(outputFile); - IOUtils.copy(fis, zipOutputStream); - fis.close(); - zipOutputStream.closeEntry(); + try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) { + for (File outputFile : outputFiles) { + ZipEntry entry = new ZipEntry(outputFile.getName()); + zipOutputStream.putNextEntry(entry); + try (FileInputStream fis = new FileInputStream(outputFile)) { + IOUtils.copy(fis, zipOutputStream); + } catch (IOException e) { + logger.error("Exception writing zip entry", e); + } + zipOutputStream.closeEntry(); + } + } catch (IOException e) { + logger.error("Exception writing zip", e); } - - zipOutputStream.close(); fileBytes = byteArrayOutputStream.toByteArray(); } finally { @@ -160,18 +165,22 @@ public class PDFToFile { // Return output files in a ZIP archive fileName = pdfBaseName + "To" + outputFormat + ".zip"; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream); + try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) { + for (File outputFile : outputFiles) { + ZipEntry entry = new ZipEntry(outputFile.getName()); + zipOutputStream.putNextEntry(entry); + try (FileInputStream fis = new FileInputStream(outputFile)) { + IOUtils.copy(fis, zipOutputStream); + } catch (IOException e) { + logger.error("Exception writing zip entry", e); + } - for (File outputFile : outputFiles) { - ZipEntry entry = new ZipEntry(outputFile.getName()); - zipOutputStream.putNextEntry(entry); - FileInputStream fis = new FileInputStream(outputFile); - IOUtils.copy(fis, zipOutputStream); - fis.close(); - zipOutputStream.closeEntry(); + zipOutputStream.closeEntry(); + } + } catch (IOException e) { + logger.error("Exception writing zip", e); } - zipOutputStream.close(); fileBytes = byteArrayOutputStream.toByteArray(); } diff --git a/src/main/java/stirling/software/SPDF/utils/ProcessExecutor.java b/src/main/java/stirling/software/SPDF/utils/ProcessExecutor.java index 93fdbd54..5055c14c 100644 --- a/src/main/java/stirling/software/SPDF/utils/ProcessExecutor.java +++ b/src/main/java/stirling/software/SPDF/utils/ProcessExecutor.java @@ -125,7 +125,7 @@ public class ProcessExecutor { logger.warn( "Error reader thread was interrupted due to timeout."); } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); } }); @@ -149,7 +149,7 @@ public class ProcessExecutor { logger.warn( "Error reader thread was interrupted due to timeout."); } catch (IOException e) { - e.printStackTrace(); + logger.error("exception", e); } });