Compare commits

..

15 Commits

Author SHA1 Message Date
Anthony Stirling
fc0878704d Merge pull request #1385 from jimdouk/main
Enhance Test Coverage for SPDF/Utils Classes
2024-06-07 09:38:56 +01:00
Anthony Stirling
d5c71c8425 Merge pull request #1399 from Stirling-Tools/sync_version
💾 Update Version
2024-06-07 09:38:24 +01:00
GitHub Action action@github.com
afbe8f7abe 💾 Sync Versions
> Made via sync_files.yml
2024-06-07 08:37:00 +00:00
Anthony Stirling
3a97ff0e5e Update build.gradle 2024-06-07 09:36:46 +01:00
Anthony Stirling
4f5b19edfb Merge pull request #1397 from Stirling-Tools/pixeebot/drip-2024-06-07-sonar-java/avoid-implicit-public-constructor-s1118
(Sonar) Fixed finding: "Utility classes should not have public constructors"
2024-06-07 09:09:10 +01:00
pixeebot[bot]
88338b4dbc (Sonar) Fixed finding: "Utility classes should not have public constructors" 2024-06-07 07:52:26 +00:00
jimdouk
fc249661e2 Merge branch 'main' of https://github.com/jimdouk/Stirling-PDF 2024-06-07 10:38:21 +03:00
jimdouk
805848e627 Fix one test in Class ProcessExecutorTest 2024-06-07 10:38:05 +03:00
Dimitris Doukas
fdae1c9756 Merge branch 'main' into main 2024-06-07 09:21:06 +03:00
Anthony Stirling
32b3cfca41 Merge pull request #1396 from Stirling-Tools/pixeebot/drip-2024-06-07-sonar-java/add-missing-override-s1161
(Sonar) Fixed finding: "`@Override` should be used on overriding and implementing methods"
2024-06-07 06:27:02 +01:00
pixeebot[bot]
9147d364bc (Sonar) Fixed finding: "@Override should be used on overriding and implementing methods" 2024-06-07 04:38:10 +00:00
Anthony Stirling
6606850e4a fix version number 2024-06-06 22:38:22 +01:00
jimdouk
5277cf2b59 Add junit tests for utils classes 2024-06-06 12:54:12 +03:00
Dimitris Doukas
52e9689431 Merge branch 'Stirling-Tools:main' into main 2024-05-28 11:43:21 +03:00
Dimitris Doukas
caa5525ddd Merge branch 'Stirling-Tools:main' into main 2024-05-02 15:41:23 +03:00
15 changed files with 590 additions and 4 deletions

View File

@@ -12,7 +12,7 @@ plugins {
import com.github.jk1.license.render.*
group = 'stirling.software'
version = '0.25.2'
version = '0.25.3'
//17 is lowest but we support and recommend 21
sourceCompatibility = '17'
@@ -178,7 +178,7 @@ compileJava {
options.compilerArgs << '-parameters'
}
tasks.register('writeVersion') {
task writeVersion {
def propsFile = file('src/main/resources/version.properties')
def props = new Properties()
props.setProperty('version', version)
@@ -208,6 +208,6 @@ tasks.named('test') {
useJUnitPlatform()
}
tasks.register('printVersion') {
task printVersion {
println project.version
}

View File

@@ -1,5 +1,5 @@
apiVersion: v2
appVersion: 0.25.2
appVersion: 0.25.3
description: locally hosted web application that allows you to perform various operations
on PDF files
home: https://github.com/Stirling-Tools/Stirling-PDF

View File

@@ -18,6 +18,7 @@ class AppUpdateAuthService implements ShowAdminInterface {
@Autowired private UserRepository userRepository;
@Autowired private ApplicationProperties applicationProperties;
@Override
public boolean getShowUpdateOnlyAdmins() {
boolean showUpdate = applicationProperties.getSystem().getShowUpdate();
if (!showUpdate) {

View File

@@ -559,6 +559,7 @@ public class ApplicationProperties {
this.clientSecret = clientSecret;
}
@Override
public Collection<String> getScopes() {
if (scopes == null || scopes.isEmpty()) {
scopes = new ArrayList<>();
@@ -661,6 +662,7 @@ public class ApplicationProperties {
return scopes;
}
@Override
public void setScopes(String scopes) {
this.scopes =
Arrays.stream(scopes.split(",")).map(String::trim).collect(Collectors.toList());

View File

@@ -4,6 +4,9 @@ import jakarta.servlet.http.HttpServletRequest;
public class UrlUtils {
private UrlUtils() {
}
public static String getOrigin(HttpServletRequest request) {
String scheme = request.getScheme(); // http or https
String serverName = request.getServerName(); // localhost

View File

@@ -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"));
}
}

View File

@@ -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);
});
}
}

View File

@@ -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());
}
}
}
}

View File

@@ -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<COSName> 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);
}
}

View File

@@ -0,0 +1,55 @@
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<String> 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<String> command = new ArrayList<>();
command.add("nonexistent-command");
// Execute the command and expect an IOException
IOException thrown = assertThrows(IOException.class, () -> {
processExecutor.runCommandWithOutputHandling(command);
});
// Log the actual error message
System.out.println("Caught IOException: " + thrown.getMessage());
// Check the exception message to ensure it indicates the command was not found
String errorMessage = thrown.getMessage();
assertTrue(errorMessage.contains("error=2") || errorMessage.contains("No such file or directory"), "Unexpected error message: " + errorMessage);
}
}

View File

@@ -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<String> 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<String> 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);
}
}

View File

@@ -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"));
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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<byte[]> 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<byte[]> 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<byte[]> 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<byte[]> 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());
}
}
}