From 5277cf2b59263f309b3e5de7283fe19d53a842d8 Mon Sep 17 00:00:00 2001 From: jimdouk Date: Thu, 6 Jun 2024 12:54:12 +0300 Subject: [PATCH 01/74] Add junit tests for utils classes --- .../software/SPDF/utils/ErrorUtilsTest.java | 45 +++++++ .../software/SPDF/utils/FileToPdfTest.java | 36 ++++++ .../SPDF/utils/ImageProcessingUtilsTest.java | 76 ++++++++++++ .../software/SPDF/utils/PdfUtilsTest.java | 60 ++++++++++ .../SPDF/utils/ProcessExecutorTest.java | 51 ++++++++ .../SPDF/utils/PropertyConfigsTest.java | 69 +++++++++++ .../SPDF/utils/RequestUriUtilsTest.java | 26 ++++ .../SPDF/utils/SPdfApplicationTest.java | 76 ++++++++++++ .../software/SPDF/utils/UrlUtilsTest.java | 26 ++++ .../SPDF/utils/WebResponseUtilsTest.java | 111 ++++++++++++++++++ 10 files changed, 576 insertions(+) create mode 100644 src/test/java/stirling/software/SPDF/utils/ErrorUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/FileToPdfTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/ImageProcessingUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/PdfUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/ProcessExecutorTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/PropertyConfigsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/RequestUriUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/SPdfApplicationTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java create mode 100644 src/test/java/stirling/software/SPDF/utils/WebResponseUtilsTest.java diff --git a/src/test/java/stirling/software/SPDF/utils/ErrorUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/ErrorUtilsTest.java new file mode 100644 index 00000000..414540dd --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/ErrorUtilsTest.java @@ -0,0 +1,45 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.ui.Model; +import org.springframework.web.servlet.ModelAndView; + +public class ErrorUtilsTest { + + @Test + public void testExceptionToModel() { + // Create a mock Model + Model model = new org.springframework.ui.ExtendedModelMap(); + + // Create a test exception + Exception ex = new Exception("Test Exception"); + + // Call the method under test + Model resultModel = ErrorUtils.exceptionToModel(model, ex); + + // Verify the result + assertNotNull(resultModel); + assertEquals("Test Exception", resultModel.getAttribute("errorMessage")); + assertNotNull(resultModel.getAttribute("stackTrace")); + } + + @Test + public void testExceptionToModelView() { + // Create a mock Model + Model model = new org.springframework.ui.ExtendedModelMap(); + + // Create a test exception + Exception ex = new Exception("Test Exception"); + + // Call the method under test + ModelAndView modelAndView = ErrorUtils.exceptionToModelView(model, ex); + + // Verify the result + assertNotNull(modelAndView); + assertEquals("Test Exception", modelAndView.getModel().get("errorMessage")); + assertNotNull(modelAndView.getModel().get("stackTrace")); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/FileToPdfTest.java b/src/test/java/stirling/software/SPDF/utils/FileToPdfTest.java new file mode 100644 index 00000000..66c19539 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/FileToPdfTest.java @@ -0,0 +1,36 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; + +import org.junit.jupiter.api.Test; + +import stirling.software.SPDF.model.api.converters.HTMLToPdfRequest; + +public class FileToPdfTest { + + @Test + public void testConvertHtmlToPdf() { + HTMLToPdfRequest request = new HTMLToPdfRequest(); + byte[] fileBytes = new byte[10]; // Sample file bytes + String fileName = "test.html"; // Sample file name + boolean htmlFormatsInstalled = true; // Sample boolean value + + // Check if the method throws IOException + assertThrows(IOException.class, () -> { + FileToPdf.convertHtmlToPdf(request, fileBytes, fileName, htmlFormatsInstalled); + }); + } + + @Test + public void testConvertBookTypeToPdf() { + byte[] bytes = new byte[10]; // Sample bytes + String originalFilename = "test.epub"; // Sample original filename + + // Check if the method throws IOException + assertThrows(IOException.class, () -> { + FileToPdf.convertBookTypeToPdf(bytes, originalFilename); + }); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/ImageProcessingUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/ImageProcessingUtilsTest.java new file mode 100644 index 00000000..da990c1c --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/ImageProcessingUtilsTest.java @@ -0,0 +1,76 @@ +package stirling.software.SPDF.utils; + +import org.junit.jupiter.api.Test; + +import java.awt.image.BufferedImage; +import java.awt.Color; + +import static org.junit.jupiter.api.Assertions.*; + +public class ImageProcessingUtilsTest { + + @Test + void testConvertColorTypeToGreyscale() { + BufferedImage sourceImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + fillImageWithColor(sourceImage, Color.RED); + + BufferedImage convertedImage = ImageProcessingUtils.convertColorType(sourceImage, "greyscale"); + + assertNotNull(convertedImage); + assertEquals(BufferedImage.TYPE_BYTE_GRAY, convertedImage.getType()); + assertEquals(sourceImage.getWidth(), convertedImage.getWidth()); + assertEquals(sourceImage.getHeight(), convertedImage.getHeight()); + + // Check if a pixel is correctly converted to greyscale + Color grey = new Color(convertedImage.getRGB(0, 0)); + assertEquals(grey.getRed(), grey.getGreen()); + assertEquals(grey.getGreen(), grey.getBlue()); + } + + @Test + void testConvertColorTypeToBlackWhite() { + BufferedImage sourceImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + fillImageWithColor(sourceImage, Color.RED); + + BufferedImage convertedImage = ImageProcessingUtils.convertColorType(sourceImage, "blackwhite"); + + assertNotNull(convertedImage); + assertEquals(BufferedImage.TYPE_BYTE_BINARY, convertedImage.getType()); + assertEquals(sourceImage.getWidth(), convertedImage.getWidth()); + assertEquals(sourceImage.getHeight(), convertedImage.getHeight()); + + // Check if a pixel is converted correctly (binary image will be either black or white) + int rgb = convertedImage.getRGB(0, 0); + assertTrue(rgb == Color.BLACK.getRGB() || rgb == Color.WHITE.getRGB()); + } + + @Test + void testConvertColorTypeToFullColor() { + BufferedImage sourceImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + fillImageWithColor(sourceImage, Color.RED); + + BufferedImage convertedImage = ImageProcessingUtils.convertColorType(sourceImage, "fullcolor"); + + assertNotNull(convertedImage); + assertEquals(sourceImage, convertedImage); + } + + @Test + void testConvertColorTypeInvalid() { + BufferedImage sourceImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); + fillImageWithColor(sourceImage, Color.RED); + + BufferedImage convertedImage = ImageProcessingUtils.convertColorType(sourceImage, "invalidtype"); + + assertNotNull(convertedImage); + assertEquals(sourceImage, convertedImage); + } + + private void fillImageWithColor(BufferedImage image, Color color) { + for (int y = 0; y < image.getHeight(); y++) { + for (int x = 0; x < image.getWidth(); x++) { + image.setRGB(x, y, color.getRGB()); + } + } + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/PdfUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/PdfUtilsTest.java new file mode 100644 index 00000000..03a52663 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/PdfUtilsTest.java @@ -0,0 +1,60 @@ +package stirling.software.SPDF.utils; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.PDResources; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import stirling.software.SPDF.model.PdfMetadata; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; +import org.apache.pdfbox.cos.COSName; + +public class PdfUtilsTest { + + @Test + void testTextToPageSize() { + assertEquals(PDRectangle.A4, PdfUtils.textToPageSize("A4")); + assertEquals(PDRectangle.LETTER, PdfUtils.textToPageSize("LETTER")); + assertThrows(IllegalArgumentException.class, () -> PdfUtils.textToPageSize("INVALID")); + } + + @Test + void testHasImagesOnPage() throws IOException { + // Mock a PDPage and its resources + PDPage page = Mockito.mock(PDPage.class); + PDResources resources = Mockito.mock(PDResources.class); + Mockito.when(page.getResources()).thenReturn(resources); + + // Case 1: No images in resources + Mockito.when(resources.getXObjectNames()).thenReturn(Collections.emptySet()); + assertFalse(PdfUtils.hasImagesOnPage(page)); + + // Case 2: Resources with an image + Set xObjectNames = new HashSet<>(); + COSName cosName = Mockito.mock(COSName.class); + xObjectNames.add(cosName); + + PDImageXObject imageXObject = Mockito.mock(PDImageXObject.class); + Mockito.when(resources.getXObjectNames()).thenReturn(xObjectNames); + Mockito.when(resources.getXObject(cosName)).thenReturn(imageXObject); + + assertTrue(PdfUtils.hasImagesOnPage(page)); + } + + @Test + void testExtractMetadataFromPdf() throws IOException { + PDDocument document = Mockito.mock(PDDocument.class); + Mockito.when(document.getDocumentInformation()).thenReturn(Mockito.mock(org.apache.pdfbox.pdmodel.PDDocumentInformation.class)); + PdfMetadata metadata = PdfUtils.extractMetadataFromPdf(document); + + assertNotNull(metadata); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/ProcessExecutorTest.java b/src/test/java/stirling/software/SPDF/utils/ProcessExecutorTest.java new file mode 100644 index 00000000..02f846c7 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/ProcessExecutorTest.java @@ -0,0 +1,51 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ProcessExecutorTest { + + private ProcessExecutor processExecutor; + + @BeforeEach + public void setUp() { + // Initialize the ProcessExecutor instance + processExecutor = ProcessExecutor.getInstance(ProcessExecutor.Processes.LIBRE_OFFICE); + } + + @Test + public void testRunCommandWithOutputHandling() throws IOException, InterruptedException { + // Mock the command to execute + List command = new ArrayList<>(); + command.add("java"); + command.add("-version"); + + // Execute the command + ProcessExecutor.ProcessExecutorResult result = processExecutor.runCommandWithOutputHandling(command); + + // Check the exit code and output messages + assertEquals(0, result.getRc()); + assertNotNull(result.getMessages()); // Check if messages are not null + } + + @Test + public void testRunCommandWithOutputHandling_Error() { + // Mock the command to execute + List command = new ArrayList<>(); + command.add("nonexistent-command"); + + // Execute the command and expect an IOException + IOException thrown = assertThrows(IOException.class, () -> { + processExecutor.runCommandWithOutputHandling(command); + }); + + // Check the exception message to ensure it is about the nonexistent command + assertTrue(thrown.getMessage().contains("CreateProcess error=2, The system cannot find the file specified")); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/PropertyConfigsTest.java b/src/test/java/stirling/software/SPDF/utils/PropertyConfigsTest.java new file mode 100644 index 00000000..7909f1d9 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/PropertyConfigsTest.java @@ -0,0 +1,69 @@ +package stirling.software.SPDF.utils; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PropertyConfigsTest { + + @Test + public void testGetBooleanValue_WithKeys() { + // Define keys and default value + List keys = Arrays.asList("test.key1", "test.key2", "test.key3"); + boolean defaultValue = false; + + // Set property for one of the keys + System.setProperty("test.key2", "true"); + + // Call the method under test + boolean result = PropertyConfigs.getBooleanValue(keys, defaultValue); + + // Verify the result + assertEquals(true, result); + } + + @Test + public void testGetStringValue_WithKeys() { + // Define keys and default value + List keys = Arrays.asList("test.key1", "test.key2", "test.key3"); + String defaultValue = "default"; + + // Set property for one of the keys + System.setProperty("test.key2", "value"); + + // Call the method under test + String result = PropertyConfigs.getStringValue(keys, defaultValue); + + // Verify the result + assertEquals("value", result); + } + + @Test + public void testGetBooleanValue_WithKey() { + // Define key and default value + String key = "test.key"; + boolean defaultValue = true; + + // Call the method under test + boolean result = PropertyConfigs.getBooleanValue(key, defaultValue); + + // Verify the result + assertEquals(true, result); + } + + @Test + public void testGetStringValue_WithKey() { + // Define key and default value + String key = "test.key"; + String defaultValue = "default"; + + // Call the method under test + String result = PropertyConfigs.getStringValue(key, defaultValue); + + // Verify the result + assertEquals("default", result); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/RequestUriUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/RequestUriUtilsTest.java new file mode 100644 index 00000000..5fdf5856 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/RequestUriUtilsTest.java @@ -0,0 +1,26 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +public class RequestUriUtilsTest { + + @Test + public void testIsStaticResource() { + assertTrue(RequestUriUtils.isStaticResource("/css/styles.css")); + assertTrue(RequestUriUtils.isStaticResource("/js/script.js")); + assertTrue(RequestUriUtils.isStaticResource("/images/logo.png")); + assertTrue(RequestUriUtils.isStaticResource("/public/index.html")); + assertTrue(RequestUriUtils.isStaticResource("/pdfjs/pdf.worker.js")); + assertTrue(RequestUriUtils.isStaticResource("/api/v1/info/status")); + assertTrue(RequestUriUtils.isStaticResource("/some-path/icon.svg")); + assertFalse(RequestUriUtils.isStaticResource("/api/v1/users")); + assertFalse(RequestUriUtils.isStaticResource("/api/v1/orders")); + assertFalse(RequestUriUtils.isStaticResource("/")); + assertFalse(RequestUriUtils.isStaticResource("/login")); + assertFalse(RequestUriUtils.isStaticResource("/register")); + assertFalse(RequestUriUtils.isStaticResource("/api/v1/products")); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/SPdfApplicationTest.java b/src/test/java/stirling/software/SPDF/utils/SPdfApplicationTest.java new file mode 100644 index 00000000..e37e74b6 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/SPdfApplicationTest.java @@ -0,0 +1,76 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.core.env.Environment; + +import stirling.software.SPDF.SPdfApplication; +import stirling.software.SPDF.model.ApplicationProperties; + +@ExtendWith(MockitoExtension.class) +public class SPdfApplicationTest { + + @Mock + private Environment env; + + @Mock + private ApplicationProperties applicationProperties; + + @InjectMocks + private SPdfApplication sPdfApplication; + + @BeforeEach + public void setUp() { + sPdfApplication = new SPdfApplication(); + sPdfApplication.setServerPortStatic("8080"); + } + + @Test + public void testSetServerPortStatic() { + sPdfApplication.setServerPortStatic("9090"); + assertEquals("9090", SPdfApplication.getStaticPort()); + } + + @Test + public void testMainApplicationStartup() throws IOException, InterruptedException { + // Setup mock environment for the main method + Path settingsPath = Paths.get("configs/settings.yml"); + Path customSettingsPath = Paths.get("configs/custom_settings.yml"); + + // Ensure the files do not exist for the test + if (Files.exists(settingsPath)) { + Files.delete(settingsPath); + } + if (Files.exists(customSettingsPath)) { + Files.delete(customSettingsPath); + } + + // Run the main method + SPdfApplication.main(new String[]{}); + + // Verify that the directories were created + assertTrue(Files.exists(Path.of("customFiles/static/"))); + assertTrue(Files.exists(Path.of("customFiles/templates/"))); + } + + @Test + public void testGetStaticPort() { + assertEquals("8080", SPdfApplication.getStaticPort()); + } + + @Test + public void testGetNonStaticPort() { + assertEquals("8080", sPdfApplication.getNonStaticPort()); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java new file mode 100644 index 00000000..c17c0e74 --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java @@ -0,0 +1,26 @@ +package stirling.software.SPDF.utils; + +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UrlUtilsTest { + + @Test + void testGetOrigin() { + // Mock HttpServletRequest + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getScheme()).thenReturn("http"); + Mockito.when(request.getServerName()).thenReturn("localhost"); + Mockito.when(request.getServerPort()).thenReturn(8080); + Mockito.when(request.getContextPath()).thenReturn("/myapp"); + + // Call the method under test + String origin = UrlUtils.getOrigin(request); + + // Assert the result + assertEquals("http://localhost:8080/myapp", origin); + } +} diff --git a/src/test/java/stirling/software/SPDF/utils/WebResponseUtilsTest.java b/src/test/java/stirling/software/SPDF/utils/WebResponseUtilsTest.java new file mode 100644 index 00000000..68ff619d --- /dev/null +++ b/src/test/java/stirling/software/SPDF/utils/WebResponseUtilsTest.java @@ -0,0 +1,111 @@ +package stirling.software.SPDF.utils; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; + +public class WebResponseUtilsTest { + + @Test + public void testBoasToWebResponse() { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + baos.write("Sample PDF content".getBytes()); + String docName = "sample.pdf"; + + ResponseEntity responseEntity = WebResponseUtils.boasToWebResponse(baos, docName); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + + HttpHeaders headers = responseEntity.getHeaders(); + assertNotNull(headers); + assertEquals(MediaType.APPLICATION_PDF, headers.getContentType()); + assertNotNull(headers.getContentDisposition()); + //assertEquals("attachment; filename=\"sample.pdf\"", headers.getContentDisposition().toString()); + + } catch (IOException e) { + fail("Exception thrown: " + e.getMessage()); + } + } + + @Test + public void testMultiPartFileToWebResponse() { + try { + byte[] fileContent = "Sample file content".getBytes(); + MockMultipartFile file = new MockMultipartFile("file", "sample.txt", "text/plain", fileContent); + + ResponseEntity responseEntity = WebResponseUtils.multiPartFileToWebResponse(file); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + + HttpHeaders headers = responseEntity.getHeaders(); + assertNotNull(headers); + assertEquals(MediaType.TEXT_PLAIN, headers.getContentType()); + assertNotNull(headers.getContentDisposition()); + + } catch (IOException e) { + fail("Exception thrown: " + e.getMessage()); + } + } + + @Test + public void testBytesToWebResponse() { + try { + byte[] bytes = "Sample bytes".getBytes(); + String docName = "sample.txt"; + MediaType mediaType = MediaType.TEXT_PLAIN; + + ResponseEntity responseEntity = WebResponseUtils.bytesToWebResponse(bytes, docName, mediaType); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + + HttpHeaders headers = responseEntity.getHeaders(); + assertNotNull(headers); + assertEquals(MediaType.TEXT_PLAIN, headers.getContentType()); + assertNotNull(headers.getContentDisposition()); + + + } catch (IOException e) { + fail("Exception thrown: " + e.getMessage()); + } + } + + @Test + public void testPdfDocToWebResponse() { + try { + PDDocument document = new PDDocument(); + document.addPage(new org.apache.pdfbox.pdmodel.PDPage()); + String docName = "sample.pdf"; + + ResponseEntity responseEntity = WebResponseUtils.pdfDocToWebResponse(document, docName); + + assertNotNull(responseEntity); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + + HttpHeaders headers = responseEntity.getHeaders(); + assertNotNull(headers); + assertEquals(MediaType.APPLICATION_PDF, headers.getContentType()); + assertNotNull(headers.getContentDisposition()); + + + } catch (IOException e) { + fail("Exception thrown: " + e.getMessage()); + } + } +} From 515b5b1492226a2a953b5dbaf3b0225937d0fbe6 Mon Sep 17 00:00:00 2001 From: Ludy87 Date: Thu, 6 Jun 2024 20:42:50 +0200 Subject: [PATCH 02/74] Minor corrections in the languages --- README.md | 22 ++++++++++---------- scripts/translation_status.toml | 18 ++++++++++++++++ src/main/resources/messages_cs_CZ.properties | 2 +- src/main/resources/messages_de_DE.properties | 10 ++++----- src/main/resources/messages_hr_HR.properties | 20 +++++++++++------- src/main/resources/messages_no_NB.properties | 6 +++--- 6 files changed, 50 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 493c2f2f..a2002414 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,7 @@ Please view https://github.com/Stirling-Tools/Stirling-PDF/blob/main/HowToUseOCR ## Supported Languages -Stirling PDF currently supports 28! +Stirling PDF currently supports 32! | Language | Progress | | ------------------------------------------- | -------------------------------------- | @@ -167,15 +167,15 @@ Stirling PDF currently supports 28! | English (US) (en_US) | ![100%](https://geps.dev/progress/100) | | Arabic (العربية) (ar_AR) | ![40%](https://geps.dev/progress/40) | | German (Deutsch) (de_DE) | ![99%](https://geps.dev/progress/99) | -| French (Français) (fr_FR) | ![94%](https://geps.dev/progress/94) | +| French (Français) (fr_FR) | ![93%](https://geps.dev/progress/93) | | Spanish (Español) (es_ES) | ![95%](https://geps.dev/progress/95) | | Simplified Chinese (简体中文) (zh_CN) | ![95%](https://geps.dev/progress/95) | | Traditional Chinese (繁體中文) (zh_TW) | ![94%](https://geps.dev/progress/94) | | Catalan (Català) (ca_CA) | ![49%](https://geps.dev/progress/49) | | Italian (Italiano) (it_IT) | ![98%](https://geps.dev/progress/98) | | Swedish (Svenska) (sv_SE) | ![40%](https://geps.dev/progress/40) | -| Polish (Polski) (pl_PL) | ![43%](https://geps.dev/progress/43) | -| Romanian (Română) (ro_RO) | ![40%](https://geps.dev/progress/40) | +| Polish (Polski) (pl_PL) | ![42%](https://geps.dev/progress/42) | +| Romanian (Română) (ro_RO) | ![39%](https://geps.dev/progress/39) | | Korean (한국어) (ko_KR) | ![87%](https://geps.dev/progress/87) | | Portuguese Brazilian (Português) (pt_BR) | ![61%](https://geps.dev/progress/61) | | Russian (Русский) (ru_RU) | ![87%](https://geps.dev/progress/87) | @@ -183,17 +183,17 @@ Stirling PDF currently supports 28! | Japanese (日本語) (ja_JP) | ![87%](https://geps.dev/progress/87) | | Dutch (Nederlands) (nl_NL) | ![85%](https://geps.dev/progress/85) | | Greek (Ελληνικά) (el_GR) | ![85%](https://geps.dev/progress/85) | -| Turkish (Türkçe) (tr_TR) | ![98%](https://geps.dev/progress/98) | -| Indonesia (Bahasa Indonesia) (id_ID) | ![79%](https://geps.dev/progress/79) | +| Turkish (Türkçe) (tr_TR) | ![97%](https://geps.dev/progress/97) | +| Indonesia (Bahasa Indonesia) (id_ID) | ![78%](https://geps.dev/progress/78) | | Hindi (हिंदी) (hi_IN) | ![79%](https://geps.dev/progress/79) | | Hungarian (Magyar) (hu_HU) | ![78%](https://geps.dev/progress/78) | | Bulgarian (Български) (bg_BG) | ![98%](https://geps.dev/progress/98) | -| Sebian Latin alphabet (Srpski) (sr_LATN_RS) | ![81%](https://geps.dev/progress/81) | -| Ukrainian (Українська) (uk_UA) | ![87%](https://geps.dev/progress/87) | -| Slovakian (Slovensky) (sk_SK) | ![96%](https://geps.dev/progress/96) | +| Sebian Latin alphabet (Srpski) (sr_LATN_RS) | ![80%](https://geps.dev/progress/80) | +| Ukrainian (Українська) (uk_UA) | ![86%](https://geps.dev/progress/86) | +| Slovakian (Slovensky) (sk_SK) | ![95%](https://geps.dev/progress/95) | | Czech (Česky) (cs_CZ) | ![94%](https://geps.dev/progress/94) | -| Croatian (Hrvatski) (hr_HR) | ![94%](https://geps.dev/progress/94) | -| Norwegian (Norsk) (no_NB) | ![94%](https://geps.dev/progress/94) | +| Croatian (Hrvatski) (hr_HR) | ![98%](https://geps.dev/progress/98) | +| Norwegian (Norsk) (no_NB) | ![98%](https://geps.dev/progress/98) | ## Contributing (creating issues, translations, fixing bugs, etc.) diff --git a/scripts/translation_status.toml b/scripts/translation_status.toml index 633847c9..4a57aaf4 100644 --- a/scripts/translation_status.toml +++ b/scripts/translation_status.toml @@ -15,7 +15,10 @@ ignore = [ [cs_CZ] ignore = [ + 'info', 'language.direction', + 'pipeline.header', + 'text', ] [de_DE] @@ -65,6 +68,16 @@ ignore = [ 'language.direction', ] +[hr_HR] +ignore = [ + 'font', + 'home.pipeline.title', + 'info', + 'language.direction', + 'pdfOrganiser.tags', + 'showJS.tags', +] + [hu_HU] ignore = [ 'language.direction', @@ -103,6 +116,11 @@ ignore = [ 'language.direction', ] +[no_NB] +ignore = [ + 'language.direction', +] + [pl_PL] ignore = [ 'language.direction', diff --git a/src/main/resources/messages_cs_CZ.properties b/src/main/resources/messages_cs_CZ.properties index c382e92d..42539603 100644 --- a/src/main/resources/messages_cs_CZ.properties +++ b/src/main/resources/messages_cs_CZ.properties @@ -26,7 +26,7 @@ bored=Nudíte se při čekání? alphabet=Abeceda downloadPdf=Stáhnout PDF text=Text -font=Font +font=Písmo selectFillter=-- Vyberte -- pageNum=Číslo stránky sizes.small=Malé diff --git a/src/main/resources/messages_de_DE.properties b/src/main/resources/messages_de_DE.properties index 8677a886..bd306345 100644 --- a/src/main/resources/messages_de_DE.properties +++ b/src/main/resources/messages_de_DE.properties @@ -71,7 +71,7 @@ visitGithub=GitHub-Repository besuchen donate=Spenden color=Farbe sponsor=Sponsor -info=Die Info +info=Informationen @@ -660,10 +660,10 @@ certSign.submit=PDF signieren #removeCertSign -removeCertSign.title=Remove Certificate Signature -removeCertSign.header=Remove the digital certificate from the PDF -removeCertSign.selectPDF=Select a PDF file: -removeCertSign.submit=Remove Signature +removeCertSign.title=Zertifikatsignatur entfernen +removeCertSign.header=Digitales Zertifikat aus dem PDF entfernen +removeCertSign.selectPDF=PDF-Datei auswählen: +removeCertSign.submit=Signatur entfernen #removeBlanks diff --git a/src/main/resources/messages_hr_HR.properties b/src/main/resources/messages_hr_HR.properties index c55b9868..e5e4d92f 100644 --- a/src/main/resources/messages_hr_HR.properties +++ b/src/main/resources/messages_hr_HR.properties @@ -1,7 +1,7 @@ ########### # Generic # ########### -# the direction that the language is written (ltr=left to right, rtl = right to left) +# the direction that the language is written (ltr = left to right, rtl = right to left) language.direction=ltr pdfPrompt=Odaberi PDF(ove) @@ -331,9 +331,10 @@ compare.tags=razlikovati,kontrast,izmjene,analiza home.certSign.title=Potpišite s certifikatom home.certSign.desc=Potpisuje PDF s certifikatom/ključem (PEM/P12) certSign.tags=autentifikacija,PEM,P12,zvanično,šifriranje -# home.removeCertSign.title=Remove Certificate Sign -# home.removeCertSign.desc=Remove certificate signature from PDF -# removeCertSign.tags=authenticate,PEM,P12,official,decrypt + +home.removeCertSign.title=Remove Certificate Sign +home.removeCertSign.desc=Remove certificate signature from PDF +removeCertSign.tags=authenticate,PEM,P12,official,decrypt home.pageLayout.title=Izgled s više stranica home.pageLayout.desc=Spojite više stranica PDF dokumenta u jednu stranicu @@ -656,10 +657,13 @@ certSign.reason=Razlog certSign.location=Mjesto certSign.name=Ime certSign.submit=Potpiši PDF -# removeCertSign.title=Remove Certificate Signature -# removeCertSign.header=Remove the digital certificate from the PDF -# removeCertSign.selectPDF=Select a PDF file: -# removeCertSign.submit=Remove Signature + + +#removeCertSign +removeCertSign.title=Remove Certificate Signature +removeCertSign.header=Remove the digital certificate from the PDF +removeCertSign.selectPDF=Select a PDF file: +removeCertSign.submit=Remove Signature #removeBlanks diff --git a/src/main/resources/messages_no_NB.properties b/src/main/resources/messages_no_NB.properties index 37c45e16..cee5c3f9 100644 --- a/src/main/resources/messages_no_NB.properties +++ b/src/main/resources/messages_no_NB.properties @@ -438,7 +438,7 @@ PDFToBook.tags=bok,comic,calibre,konvertere,manga,amazon,kindle,epub,mobi,azw3,d home.BookToPDF.title=Bok til PDF home.BookToPDF.desc=Konverter bøker/tegneserier til PDF ved hjelp av calibre - +BookToPDF.tags=Book,Comic,Calibre,Convert,manga,amazon,kindle,epub,mobi,azw3,docx,rtf,txt,html,lit,fb2,pdb,lrf ########################### @@ -783,7 +783,7 @@ compress.selectText.2=Optimeringsnivå: compress.selectText.3=4 (Dårlig for tekstbilder) compress.selectText.4=Automatisk modus - Justerer automatisk kvaliteten for å få PDF til nøyaktig størrelse compress.selectText.5=Forventet PDF-størrelse (f.eks. 25MB, 10.8MB, 25KB) -compress.Submit=Komprimer +compress.submit=Komprimer #Add image @@ -855,7 +855,7 @@ split.desc.6=Dokument #4: Side 8 split.desc.7=Dokument #5: Side 9 split.desc.8=Dokument #6: Side 10 split.splitPages=Skriv inn sidene som skal deles på: -split.Submit=Del +split.submit=Del #merge From a40696f16e5a056b0100214db707ba4150b06dc5 Mon Sep 17 00:00:00 2001 From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com.> Date: Thu, 6 Jun 2024 19:49:53 +0100 Subject: [PATCH 03/74] remove settings files update for now --- build.gradle | 2 +- .../SPDF/config/ConfigInitializer.java | 95 ++++++++----------- 2 files changed, 41 insertions(+), 56 deletions(-) diff --git a/build.gradle b/build.gradle index 38ea2b2e..3cddcc32 100644 --- a/build.gradle +++ b/build.gradle @@ -12,7 +12,7 @@ plugins { import com.github.jk1.license.render.* group = 'stirling.software' -version = '0.25.1' +version = '0.25.2' //17 is lowest but we support and recommend 21 sourceCompatibility = '17' diff --git a/src/main/java/stirling/software/SPDF/config/ConfigInitializer.java b/src/main/java/stirling/software/SPDF/config/ConfigInitializer.java index 874d43c3..673fc707 100644 --- a/src/main/java/stirling/software/SPDF/config/ConfigInitializer.java +++ b/src/main/java/stirling/software/SPDF/config/ConfigInitializer.java @@ -1,10 +1,8 @@ package stirling.software.SPDF.config; -import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; @@ -47,61 +45,48 @@ public class ConfigInitializer } } } else { - // Load the template content from classpath - List templateLines; - try (InputStream in = - getClass().getClassLoader().getResourceAsStream("settings.yml.template")) { - if (in == null) { - throw new FileNotFoundException( - "Resource file not found: settings.yml.template"); - } - templateLines = new ArrayList<>(); - try (var reader = new InputStreamReader(in)) { - try (var bufferedReader = new BufferedReader(reader)) { - String line; - while ((line = bufferedReader.readLine()) != null) { - templateLines.add(line); - } - } - } - } - - // Read the user settings file if it exists - Path userPath = Paths.get("configs", "settings.yml"); - List userLines = - Files.exists(userPath) ? Files.readAllLines(userPath) : new ArrayList<>(); - - List resultLines = new ArrayList<>(); - int position = 0; - for (String templateLine : templateLines) { - // Check if the line is a comment - if (templateLine.trim().startsWith("#")) { - String entry = templateLine.trim().substring(1).trim(); - if (!entry.isEmpty()) { - // Check if this comment has been uncommented in userLines - String key = entry.split(":")[0].trim(); - addLine(resultLines, userLines, templateLine, key, position); - } else { - resultLines.add(templateLine); - } - } - // Check if the line is a key-value pair - else if (templateLine.contains(":")) { - String key = templateLine.split(":")[0].trim(); - addLine(resultLines, userLines, templateLine, key, position); - } - // Handle empty lines - else if (templateLine.trim().length() == 0) { - resultLines.add(""); - } - position++; - } - - // Write the result to the user settings file - Files.write(userPath, resultLines); +// Path templatePath = +// Paths.get( +// getClass() +// .getClassLoader() +// .getResource("settings.yml.template") +// .toURI()); +// Path userPath = Paths.get("configs", "settings.yml"); +// +// List templateLines = Files.readAllLines(templatePath); +// List userLines = +// Files.exists(userPath) ? Files.readAllLines(userPath) : new ArrayList<>(); +// +// List resultLines = new ArrayList<>(); +// int position = 0; +// for (String templateLine : templateLines) { +// // Check if the line is a comment +// if (templateLine.trim().startsWith("#")) { +// String entry = templateLine.trim().substring(1).trim(); +// if (!entry.isEmpty()) { +// // Check if this comment has been uncommented in userLines +// String key = entry.split(":")[0].trim(); +// addLine(resultLines, userLines, templateLine, key, position); +// } else { +// resultLines.add(templateLine); +// } +// } +// // Check if the line is a key-value pair +// else if (templateLine.contains(":")) { +// String key = templateLine.split(":")[0].trim(); +// addLine(resultLines, userLines, templateLine, key, position); +// } +// // Handle empty lines +// else if (templateLine.trim().length() == 0) { +// resultLines.add(""); +// } +// position++; +// } +// +// // Write the result to the user settings file +// Files.write(userPath, resultLines); } - // Ensure the custom settings file exists Path customSettingsPath = Paths.get("configs", "custom_settings.yml"); if (!Files.exists(customSettingsPath)) { Files.createFile(customSettingsPath); From 7d9edfca6d7abced4b51616e29190cbc08d96332 Mon Sep 17 00:00:00 2001 From: Ludy87 Date: Thu, 6 Jun 2024 21:03:06 +0200 Subject: [PATCH 04/74] Enhance OAuth2 Client Registration with Dynamic Provider Details --- .../security/SecurityConfiguration.java | 16 ++++++------ .../CustomOAuth2LogoutSuccessHandler.java | 2 +- .../oauth2/CustomOAuth2UserService.java | 25 ++++++++++++++++--- .../controller/web/AccountWebController.java | 8 +++--- .../SPDF/model/ApplicationProperties.java | 18 +++++++++++-- .../software/SPDF/model/Provider.java | 5 ++++ 6 files changed, 56 insertions(+), 18 deletions(-) diff --git a/src/main/java/stirling/software/SPDF/config/security/SecurityConfiguration.java b/src/main/java/stirling/software/SPDF/config/security/SecurityConfiguration.java index ce6ce799..fad0f285 100644 --- a/src/main/java/stirling/software/SPDF/config/security/SecurityConfiguration.java +++ b/src/main/java/stirling/software/SPDF/config/security/SecurityConfiguration.java @@ -238,7 +238,7 @@ public class SecurityConfiguration { GoogleProvider google = client.getGoogle(); return google != null && google.isSettingsValid() ? Optional.of( - ClientRegistration.withRegistrationId("google") + ClientRegistration.withRegistrationId(google.getName()) .clientId(google.getClientId()) .clientSecret(google.getClientSecret()) .scope(google.getScopes()) @@ -246,8 +246,8 @@ public class SecurityConfiguration { .tokenUri(google.getTokenuri()) .userInfoUri(google.getUserinfouri()) .userNameAttributeName(google.getUseAsUsername()) - .clientName("Google") - .redirectUri("{baseUrl}/login/oauth2/code/google") + .clientName(google.getClientName()) + .redirectUri("{baseUrl}/login/oauth2/code/" + google.getName()) .authorizationGrantType( org.springframework.security.oauth2.core .AuthorizationGrantType.AUTHORIZATION_CODE) @@ -269,12 +269,12 @@ public class SecurityConfiguration { return keycloak != null && keycloak.isSettingsValid() ? Optional.of( ClientRegistrations.fromIssuerLocation(keycloak.getIssuer()) - .registrationId("keycloak") + .registrationId(keycloak.getName()) .clientId(keycloak.getClientId()) .clientSecret(keycloak.getClientSecret()) .scope(keycloak.getScopes()) .userNameAttributeName(keycloak.getUseAsUsername()) - .clientName("Keycloak") + .clientName(keycloak.getClientName()) .build()) : Optional.empty(); } @@ -291,7 +291,7 @@ public class SecurityConfiguration { GithubProvider github = client.getGithub(); return github != null && github.isSettingsValid() ? Optional.of( - ClientRegistration.withRegistrationId("github") + ClientRegistration.withRegistrationId(github.getName()) .clientId(github.getClientId()) .clientSecret(github.getClientSecret()) .scope(github.getScopes()) @@ -299,8 +299,8 @@ public class SecurityConfiguration { .tokenUri(github.getTokenuri()) .userInfoUri(github.getUserinfouri()) .userNameAttributeName(github.getUseAsUsername()) - .clientName("GitHub") - .redirectUri("{baseUrl}/login/oauth2/code/github") + .clientName(github.getClientName()) + .redirectUri("{baseUrl}/login/oauth2/code/" + github.getName()) .authorizationGrantType( org.springframework.security.oauth2.core .AuthorizationGrantType.AUTHORIZATION_CODE) 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 e209d0cd..9b12b279 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 @@ -81,7 +81,7 @@ public class CustomOAuth2LogoutSuccessHandler extends SimpleUrlLogoutSuccessHand logger.info("Session invalidated: " + sessionId); } - switch (registrationId) { + switch (registrationId.toLowerCase()) { case "keycloak": // Add Keycloak specific logout URL if needed String logoutUrl = diff --git a/src/main/java/stirling/software/SPDF/config/security/oauth2/CustomOAuth2UserService.java b/src/main/java/stirling/software/SPDF/config/security/oauth2/CustomOAuth2UserService.java index a5d65ff0..b9766480 100644 --- a/src/main/java/stirling/software/SPDF/config/security/oauth2/CustomOAuth2UserService.java +++ b/src/main/java/stirling/software/SPDF/config/security/oauth2/CustomOAuth2UserService.java @@ -16,6 +16,8 @@ import org.springframework.security.oauth2.core.oidc.user.OidcUser; import stirling.software.SPDF.config.security.LoginAttemptService; import stirling.software.SPDF.config.security.UserService; import stirling.software.SPDF.model.ApplicationProperties; +import stirling.software.SPDF.model.ApplicationProperties.Security.OAUTH2; +import stirling.software.SPDF.model.ApplicationProperties.Security.OAUTH2.Client; import stirling.software.SPDF.model.User; public class CustomOAuth2UserService implements OAuth2UserService { @@ -41,11 +43,27 @@ public class CustomOAuth2UserService implements OAuth2UserService duser = userService.findByUsernameIgnoreCase(username); if (duser.isPresent()) { if (loginAttemptService.isBlocked(username)) { @@ -56,13 +74,14 @@ public class CustomOAuth2UserService implements OAuth2UserService getScopes() { if (scopes == null || scopes.isEmpty()) { - scopes.add("openid"); scopes.add("profile"); scopes.add("email"); } @@ -684,6 +693,11 @@ public class ApplicationProperties { return "keycloak"; } + @Override + public String getClientName() { + return "Keycloak"; + } + public boolean isSettingsValid() { return isValid(this.getIssuer(), "issuer") && isValid(this.getClientId(), "clientId") diff --git a/src/main/java/stirling/software/SPDF/model/Provider.java b/src/main/java/stirling/software/SPDF/model/Provider.java index a8dce446..c378975d 100644 --- a/src/main/java/stirling/software/SPDF/model/Provider.java +++ b/src/main/java/stirling/software/SPDF/model/Provider.java @@ -4,11 +4,16 @@ import java.util.Collection; public class Provider implements ProviderInterface { private String name; + private String clientName; public String getName() { return name; } + public String getClientName() { + return clientName; + } + protected boolean isValid(String value, String name) { if (value != null && !value.trim().isEmpty()) { return true; From 37c75971f298ed2694ed667ee92b4d7b4ea69ea6 Mon Sep 17 00:00:00 2001 From: Ludy87 Date: Thu, 6 Jun 2024 21:14:34 +0200 Subject: [PATCH 05/74] Update ApplicationProperties.java --- .../stirling/software/SPDF/model/ApplicationProperties.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/stirling/software/SPDF/model/ApplicationProperties.java b/src/main/java/stirling/software/SPDF/model/ApplicationProperties.java index 3ba5ffb6..bc98b24f 100644 --- a/src/main/java/stirling/software/SPDF/model/ApplicationProperties.java +++ b/src/main/java/stirling/software/SPDF/model/ApplicationProperties.java @@ -455,6 +455,7 @@ public class ApplicationProperties { @Override public Collection getScopes() { if (scopes == null || scopes.isEmpty()) { + scopes = new ArrayList<>(); scopes.add("https://www.googleapis.com/auth/userinfo.email"); scopes.add("https://www.googleapis.com/auth/userinfo.profile"); } @@ -560,6 +561,7 @@ public class ApplicationProperties { public Collection getScopes() { if (scopes == null || scopes.isEmpty()) { + scopes = new ArrayList<>(); scopes.add("read:user"); } return scopes; @@ -652,6 +654,7 @@ public class ApplicationProperties { @Override public Collection getScopes() { if (scopes == null || scopes.isEmpty()) { + scopes = new ArrayList<>(); scopes.add("profile"); scopes.add("email"); } From 319ecbcbc1c0e6212bbb3c21085e11017f72180a Mon Sep 17 00:00:00 2001 From: "GitHub Action action@github.com" Date: Thu, 6 Jun 2024 19:23:20 +0000 Subject: [PATCH 06/74] :floppy_disk: Sync Versions > Made via sync_files.yml --- chart/stirling-pdf/Chart.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chart/stirling-pdf/Chart.yaml b/chart/stirling-pdf/Chart.yaml index 30263954..ae25f637 100644 --- a/chart/stirling-pdf/Chart.yaml +++ b/chart/stirling-pdf/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v2 -appVersion: 0.25.1 +appVersion: 0.25.2 description: locally hosted web application that allows you to perform various operations on PDF files home: https://github.com/Stirling-Tools/Stirling-PDF From fd4c75279f0a9e54843fdbebcdbb9f98b7af4cb7 Mon Sep 17 00:00:00 2001 From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com.> Date: Thu, 6 Jun 2024 21:23:33 +0100 Subject: [PATCH 07/74] init --- .../SPDF/controller/api/UserController.java | 62 +++++++++---------- src/main/resources/application.properties | 2 +- src/main/resources/templates/addUsers.html | 2 +- 3 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/main/java/stirling/software/SPDF/controller/api/UserController.java b/src/main/java/stirling/software/SPDF/controller/api/UserController.java index ae85d650..44a51a3a 100644 --- a/src/main/java/stirling/software/SPDF/controller/api/UserController.java +++ b/src/main/java/stirling/software/SPDF/controller/api/UserController.java @@ -66,46 +66,46 @@ public class UserController { RedirectAttributes redirectAttributes) { if (!userService.isUsernameValid(newUsername)) { - return new RedirectView("/account?messageType=invalidUsername"); + return new RedirectView("/account?messageType=invalidUsername",true); } if (principal == null) { - return new RedirectView("/account?messageType=notAuthenticated"); + return new RedirectView("/account?messageType=notAuthenticated",true); } // The username MUST be unique when renaming Optional userOpt = userService.findByUsername(principal.getName()); if (userOpt == null || userOpt.isEmpty()) { - return new RedirectView("/account?messageType=userNotFound"); + return new RedirectView("/account?messageType=userNotFound",true); } User user = userOpt.get(); if (user.getUsername().equals(newUsername)) { - return new RedirectView("/account?messageType=usernameExists"); + return new RedirectView("/account?messageType=usernameExists",true); } if (!userService.isPasswordCorrect(user, currentPassword)) { - return new RedirectView("/account?messageType=incorrectPassword"); + return new RedirectView("/account?messageType=incorrectPassword",true); } if (!user.getUsername().equals(newUsername) && userService.usernameExists(newUsername)) { - return new RedirectView("/account?messageType=usernameExists"); + return new RedirectView("/account?messageType=usernameExists",true); } if (newUsername != null && newUsername.length() > 0) { try { userService.changeUsername(user, newUsername); } catch (IllegalArgumentException e) { - return new RedirectView("/account?messageType=invalidUsername"); + return new RedirectView("/account?messageType=invalidUsername",true); } } // Logout using Spring's utility new SecurityContextLogoutHandler().logout(request, response, null); - return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED); + return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED,true); } @PreAuthorize("!hasAuthority('ROLE_DEMO_USER')") @@ -118,19 +118,19 @@ public class UserController { HttpServletResponse response, RedirectAttributes redirectAttributes) { if (principal == null) { - return new RedirectView("/change-creds?messageType=notAuthenticated"); + return new RedirectView("/change-creds?messageType=notAuthenticated",true); } Optional userOpt = userService.findByUsernameIgnoreCase(principal.getName()); if (userOpt == null || userOpt.isEmpty()) { - return new RedirectView("/change-creds?messageType=userNotFound"); + return new RedirectView("/change-creds?messageType=userNotFound",true); } User user = userOpt.get(); if (!userService.isPasswordCorrect(user, currentPassword)) { - return new RedirectView("/change-creds?messageType=incorrectPassword"); + return new RedirectView("/change-creds?messageType=incorrectPassword",true); } userService.changePassword(user, newPassword); @@ -138,7 +138,7 @@ public class UserController { // Logout using Spring's utility new SecurityContextLogoutHandler().logout(request, response, null); - return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED); + return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED,true); } @PreAuthorize("!hasAuthority('ROLE_DEMO_USER')") @@ -151,19 +151,19 @@ public class UserController { HttpServletResponse response, RedirectAttributes redirectAttributes) { if (principal == null) { - return new RedirectView("/account?messageType=notAuthenticated"); + return new RedirectView("/account?messageType=notAuthenticated",true); } Optional userOpt = userService.findByUsernameIgnoreCase(principal.getName()); if (userOpt == null || userOpt.isEmpty()) { - return new RedirectView("/account?messageType=userNotFound"); + return new RedirectView("/account?messageType=userNotFound",true); } User user = userOpt.get(); if (!userService.isPasswordCorrect(user, currentPassword)) { - return new RedirectView("/account?messageType=incorrectPassword"); + return new RedirectView("/account?messageType=incorrectPassword",true); } userService.changePassword(user, newPassword); @@ -171,7 +171,7 @@ public class UserController { // Logout using Spring's utility new SecurityContextLogoutHandler().logout(request, response, null); - return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED); + return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED,true); } @PreAuthorize("!hasAuthority('ROLE_DEMO_USER')") @@ -204,7 +204,7 @@ public class UserController { boolean forceChange) { if (!userService.isUsernameValid(username)) { - return new RedirectView("/addUsers?messageType=invalidUsername"); + return new RedirectView("/addUsers?messageType=invalidUsername",true); } Optional userOpt = userService.findByUsernameIgnoreCase(username); @@ -212,26 +212,26 @@ public class UserController { if (userOpt.isPresent()) { User user = userOpt.get(); if (user != null && user.getUsername().equalsIgnoreCase(username)) { - return new RedirectView("/addUsers?messageType=usernameExists"); + return new RedirectView("/addUsers?messageType=usernameExists",true); } } if (userService.usernameExistsIgnoreCase(username)) { - return new RedirectView("/addUsers?messageType=usernameExists"); + return new RedirectView("/addUsers?messageType=usernameExists",true); } try { // Validate the role Role roleEnum = Role.fromString(role); if (roleEnum == Role.INTERNAL_API_USER) { // If the role is INTERNAL_API_USER, reject the request - return new RedirectView("/addUsers?messageType=invalidRole"); + return new RedirectView("/addUsers?messageType=invalidRole",true); } } catch (IllegalArgumentException e) { // If the role ID is not valid, redirect with an error message - return new RedirectView("/addUsers?messageType=invalidRole"); + return new RedirectView("/addUsers?messageType=invalidRole",true); } userService.saveUser(username, password, role, forceChange); - return new RedirectView("/addUsers"); // Redirect to account page after adding the user + return new RedirectView("/addUsers",true); // Redirect to account page after adding the user } @PreAuthorize("hasRole('ROLE_ADMIN')") @@ -244,33 +244,33 @@ public class UserController { Optional userOpt = userService.findByUsernameIgnoreCase(username); if (!userOpt.isPresent()) { - return new RedirectView("/addUsers?messageType=userNotFound"); + return new RedirectView("/addUsers?messageType=userNotFound",true); } if (!userService.usernameExistsIgnoreCase(username)) { - return new RedirectView("/addUsers?messageType=userNotFound"); + return new RedirectView("/addUsers?messageType=userNotFound",true); } // Get the currently authenticated username String currentUsername = authentication.getName(); // Check if the provided username matches the current session's username if (currentUsername.equalsIgnoreCase(username)) { - return new RedirectView("/addUsers?messageType=downgradeCurrentUser"); + return new RedirectView("/addUsers?messageType=downgradeCurrentUser",true); } try { // Validate the role Role roleEnum = Role.fromString(role); if (roleEnum == Role.INTERNAL_API_USER) { // If the role is INTERNAL_API_USER, reject the request - return new RedirectView("/addUsers?messageType=invalidRole"); + return new RedirectView("/addUsers?messageType=invalidRole",true); } } catch (IllegalArgumentException e) { // If the role ID is not valid, redirect with an error message - return new RedirectView("/addUsers?messageType=invalidRole"); + return new RedirectView("/addUsers?messageType=invalidRole",true); } User user = userOpt.get(); userService.changeRole(user, role); - return new RedirectView("/addUsers"); // Redirect to account page after adding the user + return new RedirectView("/addUsers",true); // Redirect to account page after adding the user } @PreAuthorize("hasRole('ROLE_ADMIN')") @@ -279,7 +279,7 @@ public class UserController { @PathVariable(name = "username") String username, Authentication authentication) { if (!userService.usernameExistsIgnoreCase(username)) { - return new RedirectView("/addUsers?messageType=deleteUsernameExists"); + return new RedirectView("/addUsers?messageType=deleteUsernameExists",true); } // Get the currently authenticated username @@ -287,11 +287,11 @@ public class UserController { // Check if the provided username matches the current session's username if (currentUsername.equalsIgnoreCase(username)) { - return new RedirectView("/addUsers?messageType=deleteCurrentUser"); + return new RedirectView("/addUsers?messageType=deleteCurrentUser",true); } invalidateUserSessions(username); userService.deleteUser(username); - return new RedirectView("/addUsers"); + return new RedirectView("/addUsers",true); } @Autowired private SessionRegistry sessionRegistry; diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index a5f12e64..e6961d78 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -17,7 +17,7 @@ spring.servlet.multipart.max-file-size=2000MB spring.servlet.multipart.max-request-size=2000MB server.servlet.session.tracking-modes=cookie -server.servlet.context-path=${SYSTEM_ROOTURIPATH:/} +server.servlet.context-path=/pdf spring.devtools.restart.enabled=true spring.devtools.livereload.enabled=true diff --git a/src/main/resources/templates/addUsers.html b/src/main/resources/templates/addUsers.html index 0cb5c512..848b1f13 100644 --- a/src/main/resources/templates/addUsers.html +++ b/src/main/resources/templates/addUsers.html @@ -78,7 +78,7 @@
Default message if not found
-
+
diff --git a/src/main/resources/templates/crop.html b/src/main/resources/templates/crop.html index 1547a51f..984a0b4c 100644 --- a/src/main/resources/templates/crop.html +++ b/src/main/resources/templates/crop.html @@ -16,7 +16,7 @@ crop
- +
From 4c9c0207ba9fb91b108b3918b0d4d414c3afad8f Mon Sep 17 00:00:00 2001 From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com.> Date: Thu, 6 Jun 2024 21:27:58 +0100 Subject: [PATCH 09/74] fancy button --- src/main/resources/application.properties | 2 +- src/main/resources/templates/addUsers.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e6961d78..a5f12e64 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -17,7 +17,7 @@ spring.servlet.multipart.max-file-size=2000MB spring.servlet.multipart.max-request-size=2000MB server.servlet.session.tracking-modes=cookie -server.servlet.context-path=/pdf +server.servlet.context-path=${SYSTEM_ROOTURIPATH:/} spring.devtools.restart.enabled=true spring.devtools.livereload.enabled=true diff --git a/src/main/resources/templates/addUsers.html b/src/main/resources/templates/addUsers.html index 6d2127d0..d291a4a9 100644 --- a/src/main/resources/templates/addUsers.html +++ b/src/main/resources/templates/addUsers.html @@ -34,7 +34,7 @@ - +
From 0b449af9baab3e4647b3e31c4a17c6628885622c Mon Sep 17 00:00:00 2001 From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com.> Date: Thu, 6 Jun 2024 21:34:56 +0100 Subject: [PATCH 10/74] resolve path --- src/main/resources/templates/error.html | 2 +- src/main/resources/templates/fragments/navbar.html | 2 +- src/main/resources/templates/view-pdf.html | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html index e24d114b..f9e2088a 100644 --- a/src/main/resources/templates/error.html +++ b/src/main/resources/templates/error.html @@ -21,7 +21,7 @@ - + diff --git a/src/main/resources/templates/fragments/navbar.html b/src/main/resources/templates/fragments/navbar.html index 7e72f2cd..0ddc0362 100644 --- a/src/main/resources/templates/fragments/navbar.html +++ b/src/main/resources/templates/fragments/navbar.html @@ -8,7 +8,7 @@