refactor(utils): convert utilities to @UtilityClass and add tests (#1609)

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Co-authored-by: Aditya Chandel <8075870+adityachandelgit@users.noreply.github.com>
This commit is contained in:
Balázs Szücs
2025-11-24 07:23:06 -07:00
committed by GitHub
co-authored by Aditya Chandel
parent 3f3b72248a
commit c1e662bde9
29 changed files with 1332 additions and 87 deletions
@@ -4,7 +4,6 @@ import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
@@ -106,7 +105,7 @@ public class BookdropMetadataService {
byte[] coverBytes = metadataExtractorFactory.extractCover(fileExt, file);
if (coverBytes != null) {
try {
fileService.saveImage(coverBytes, fileService.getTempBookdropCoverImagePath(entity.getId()));
FileService.saveImage(coverBytes, fileService.getTempBookdropCoverImagePath(entity.getId()));
} catch (IOException e) {
log.warn("Failed to save extracted cover for file: {}", entity.getFilePath(), e);
}
@@ -45,7 +45,7 @@ public class BackgroundUploadService {
deleteExistingBackgroundFiles(userId);
fileService.saveBackgroundImage(originalImage, filename, userId);
String fileUrl = fileService.getBackgroundUrl(filename, userId);
String fileUrl = FileService.getBackgroundUrl(filename, userId);
return new UploadResponse(fileUrl);
} catch (Exception e) {
log.error("Failed to upload background file: {}", e.getMessage(), e);
@@ -60,12 +60,12 @@ public class BackgroundUploadService {
String extension = getFileExtension(originalFilename);
String filename = "1." + extension;
BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl);
BufferedImage originalImage = FileService.downloadImageFromUrl(imageUrl);
deleteExistingBackgroundFiles(userId);
fileService.saveBackgroundImage(originalImage, filename, userId);
String fileUrl = fileService.getBackgroundUrl(filename, userId);
String fileUrl = FileService.getBackgroundUrl(filename, userId);
return new UploadResponse(fileUrl);
} catch (Exception e) {
log.error("Failed to upload background from URL: {}", e.getMessage(), e);
@@ -57,7 +57,7 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
String fileName = path.getFileName().toString();
String hash = FileFingerprint.generateHash(path);
Optional<Book> duplicate = fileService.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookAdditionalFileRepository, bookMapper);
Optional<Book> duplicate = fileService.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash);
if (duplicate.isPresent()) {
return handleDuplicate(duplicate.get(), libraryFile, hash);
@@ -61,7 +61,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
public BookEntity processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX);
if (generateCover(bookEntity)) {
fileService.setBookCoverPath(bookEntity.getMetadata());
FileService.setBookCoverPath(bookEntity.getMetadata());
}
extractAndSetMetadata(bookEntity);
@@ -54,7 +54,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB);
setBookMetadata(bookEntity);
if (generateCover(bookEntity)) {
fileService.setBookCoverPath(bookEntity.getMetadata());
FileService.setBookCoverPath(bookEntity.getMetadata());
}
return bookEntity;
}
@@ -53,7 +53,7 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
public BookEntity processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF);
if (generateCover(bookEntity)) {
fileService.setBookCoverPath(bookEntity.getMetadata());
FileService.setBookCoverPath(bookEntity.getMetadata());
}
extractAndSetMetadata(bookEntity);
return bookEntity;
@@ -150,7 +150,7 @@ public class AppMigrationService {
ImageIO.write(originalImage, "jpg", coverFile.toFile());
// Resize and save thumbnail.jpg
BufferedImage resized = fileService.resizeImage(originalImage, 250, 350);
BufferedImage resized = FileService.resizeImage(originalImage, 250, 350);
Path thumbnailFile = bookDir.resolve("thumbnail.jpg");
ImageIO.write(resized, "jpg", thumbnailFile.toFile());
@@ -1,7 +1,10 @@
package com.adityachandel.booklore.util;
import lombok.experimental.UtilityClass;
import java.util.regex.Pattern;
@UtilityClass
public class BookUtils {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
@@ -23,17 +26,25 @@ public class BookUtils {
}
public static String cleanAndTruncateSearchTerm(String term) {
if (term == null) {
return "";
}
String s = term;
s = SPECIAL_CHARACTERS_PATTERN.matcher(s).replaceAll("").trim();
s = WHITESPACE_PATTERN.matcher(s).replaceAll(" ");
if (s.length() > 60) {
String[] words = WHITESPACE_PATTERN.split(s);
StringBuilder truncated = new StringBuilder();
for (String word : words) {
if (truncated.length() + word.length() + 1 > 60) break;
if (!truncated.isEmpty()) truncated.append(" ");
truncated.append(word);
if (words.length > 1) {
StringBuilder truncated = new StringBuilder();
for (String word : words) {
if (truncated.length() + word.length() + 1 > 60) break;
if (!truncated.isEmpty()) truncated.append(" ");
truncated.append(word);
}
s = truncated.toString();
} else {
s = s.substring(0, Math.min(60, s.length()));
}
s = truncated.toString();
}
return s;
}
@@ -50,6 +50,9 @@ import java.util.stream.Stream;
public class FileService {
private final AppProperties appProperties;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final BookMapper bookMapper;
private final RestTemplate restTemplate;
// @formatter:off
@@ -92,7 +95,7 @@ public class FileService {
return getBackgroundsFolder(null);
}
public String getBackgroundUrl(String filename, Long userId) {
public static String getBackgroundUrl(String filename, Long userId) {
if (userId != null) {
return Paths.get("/", BACKGROUNDS_DIR, "user-" + userId, filename).toString().replace("\\", "/");
}
@@ -123,7 +126,7 @@ public class FileService {
// VALIDATION
// ========================================
private void validateCoverFile(MultipartFile file) {
private static void validateCoverFile(MultipartFile file) {
if (file.isEmpty()) {
throw new IllegalArgumentException("Uploaded file is empty");
}
@@ -140,7 +143,7 @@ public class FileService {
// IMAGE OPERATIONS
// ========================================
public BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = resizedImage.createGraphics();
@@ -149,7 +152,7 @@ public class FileService {
return resizedImage;
}
public void saveImage(byte[] imageData, String filePath) throws IOException {
public static void saveImage(byte[] imageData, String filePath) throws IOException {
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
File outputFile = new File(filePath);
File parentDir = outputFile.getParentFile();
@@ -160,7 +163,7 @@ public class FileService {
log.info("Image saved successfully to: {}", filePath);
}
public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
public static BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
try {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Metadata Fetcher)");
@@ -257,7 +260,7 @@ public class FileService {
return originalSaved && thumbnailSaved;
}
public void setBookCoverPath(BookMetadataEntity bookMetadataEntity) {
public static void setBookCoverPath(BookMetadataEntity bookMetadataEntity) {
bookMetadataEntity.setCoverUpdatedOn(Instant.now());
}
@@ -372,7 +375,7 @@ public class FileService {
// ========================================
@Transactional
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash, BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookMapper bookMapper) {
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash) {
if (StringUtils.isBlank(hash)) {
log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath());
return Optional.empty();
@@ -425,6 +428,8 @@ public class FileService {
}
public static String truncate(String input, int maxLength) {
return input == null ? null : (input.length() <= maxLength ? input : input.substring(0, maxLength));
if (input == null) return null;
if (maxLength <= 0) return "";
return input.length() <= maxLength ? input : input.substring(0, maxLength);
}
}
@@ -1,32 +1,30 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.BookEntity;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.Optional;
@UtilityClass
@Slf4j
public class FileUtils {
private static final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
private final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
public static String getBookFullPath(BookEntity bookEntity) {
public String getBookFullPath(BookEntity bookEntity) {
return Path.of(bookEntity.getLibraryPath().getPath(), bookEntity.getFileSubPath(), bookEntity.getFileName())
.normalize()
.toString()
.replace("\\", "/");
}
public static String getRelativeSubPath(String basePath, Path fullFilePath) {
public String getRelativeSubPath(String basePath, Path fullFilePath) {
return Optional.ofNullable(Path.of(basePath)
.relativize(fullFilePath)
.getParent())
@@ -34,12 +32,12 @@ public class FileUtils {
.orElse("");
}
public static Long getFileSizeInKb(BookEntity bookEntity) {
public Long getFileSizeInKb(BookEntity bookEntity) {
Path filePath = Path.of(getBookFullPath(bookEntity));
return getFileSizeInKb(filePath);
}
public static Long getFileSizeInKb(Path filePath) {
public Long getFileSizeInKb(Path filePath) {
try {
if (!Files.exists(filePath)) {
log.warn(FILE_NOT_FOUND_MESSAGE + "{}", filePath.toAbsolutePath());
@@ -52,7 +50,7 @@ public class FileUtils {
}
}
public static void deleteDirectoryRecursively(Path path) throws IOException {
public void deleteDirectoryRecursively(Path path) throws IOException {
if (!Files.exists(path)) return;
try (var walk = Files.walk(path)) {
@@ -1,14 +1,21 @@
package com.adityachandel.booklore.util;
import lombok.experimental.UtilityClass;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@UtilityClass
public class Md5Util {
public static String md5Hex(String input) {
public String md5Hex(String input) {
if (input == null) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes());
byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
@@ -3,14 +3,16 @@ package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.MetadataClearFlags;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.entity.*;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.function.Supplier;
import java.util.function.BooleanSupplier;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.BooleanUtils.isTrue;
@UtilityClass
@Slf4j
public class MetadataChangeDetector {
@@ -54,12 +56,8 @@ public class MetadataChangeDetector {
changes.add("cover lock: [" + isTrue(coverLockedExisting) + "] → [" + isTrue(coverLockedNew) + "]");
}
if (!changes.isEmpty()) {
/*changes.forEach(change -> log.info("Metadata change: {}", change));*/
return true;
}
return false;
/*changes.forEach(change -> log.info("Metadata change: {}", change));*/
return !changes.isEmpty();
}
public static boolean hasValueChanges(BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) {
@@ -119,7 +117,7 @@ public class MetadataChangeDetector {
return !diffs.isEmpty();
}
private static void compare(List<String> diffs, String field, boolean shouldClear, Object newVal, Object oldVal, Supplier<Boolean> isUnlocked, Boolean newLock, Boolean oldLock) {
private static void compare(List<String> diffs, String field, boolean shouldClear, Object newVal, Object oldVal, BooleanSupplier isUnlocked, Boolean newLock, Boolean oldLock) {
boolean valueChanged = differs(shouldClear, newVal, oldVal, isUnlocked);
boolean lockChanged = differsLock(newLock, oldLock);
@@ -133,18 +131,18 @@ public class MetadataChangeDetector {
}
private static <T> void compareValue(List<String> diffs,
String field,
boolean shouldClear,
T newVal,
T oldVal,
Supplier<Boolean> isUnlocked) {
String field,
boolean shouldClear,
T newVal,
T oldVal,
BooleanSupplier isUnlocked) {
if (differs(shouldClear, newVal, oldVal, isUnlocked)) {
diffs.add(field + " changed");
}
}
private static boolean differs(boolean shouldClear, Object newVal, Object oldVal, Supplier<Boolean> isUnlocked) {
if (!isUnlocked.get()) return false;
private static boolean differs(boolean shouldClear, Object newVal, Object oldVal, BooleanSupplier isUnlocked) {
if (!isUnlocked.getAsBoolean()) return false;
Object normNew = normalize(newVal);
Object normOld = normalize(oldVal);
@@ -4,35 +4,38 @@ import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import lombok.experimental.UtilityClass;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@UtilityClass
public class PathPatternResolver {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile(".*\\.[a-zA-Z0-9]+$");
private static final Pattern CONTROL_CHARACTER_PATTERN = Pattern.compile("[\\p{Cntrl}]");
private static final Pattern INVALID_CHARS_PATTERN = Pattern.compile("[\\\\/:*?\"<>|]");
private final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private final Pattern FILE_EXTENSION_PATTERN = Pattern.compile(".*\\.[a-zA-Z0-9]+$");
private final Pattern CONTROL_CHARACTER_PATTERN = Pattern.compile("[\\p{Cntrl}]");
private final Pattern INVALID_CHARS_PATTERN = Pattern.compile("[\\\\/:*?\"<>|]");
private final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{(.*?)}");
public static String resolvePattern(BookEntity book, String pattern) {
public String resolvePattern(BookEntity book, String pattern) {
String currentFilename = book.getFileName() != null ? book.getFileName().trim() : "";
return resolvePattern(book.getMetadata(), pattern, currentFilename);
}
public static String resolvePattern(BookMetadata metadata, String pattern, String filename) {
public String resolvePattern(BookMetadata metadata, String pattern, String filename) {
MetadataProvider metadataProvider = MetadataProvider.from(metadata);
return resolvePattern(metadataProvider, pattern, filename);
}
public static String resolvePattern(BookMetadataEntity metadata, String pattern, String filename) {
public String resolvePattern(BookMetadataEntity metadata, String pattern, String filename) {
MetadataProvider metadataProvider = MetadataProvider.from(metadata);
return resolvePattern(metadataProvider, pattern, filename);
}
private static String resolvePattern(MetadataProvider metadata, String pattern, String filename) {
private String resolvePattern(MetadataProvider metadata, String pattern, String filename) {
if (pattern == null || pattern.isBlank()) {
return filename;
}
@@ -89,7 +92,7 @@ public class PathPatternResolver {
return resolvePatternWithValues(pattern, values, filename);
}
private static String resolvePatternWithValues(String pattern, Map<String, String> values, String currentFilename) {
private String resolvePatternWithValues(String pattern, Map<String, String> values, String currentFilename) {
String extension = "";
int lastDot = currentFilename.lastIndexOf('.');
if (lastDot >= 0 && lastDot < currentFilename.length() - 1) {
@@ -105,7 +108,7 @@ public class PathPatternResolver {
while (matcher.find()) {
String block = matcher.group(1);
Matcher placeholderMatcher = Pattern.compile("\\{(.*?)}").matcher(block);
Matcher placeholderMatcher = PLACEHOLDER_PATTERN.matcher(block);
boolean allHaveValues = true;
// Check if all placeholders inside optional block have non-blank values
@@ -133,8 +136,7 @@ public class PathPatternResolver {
String result = resolved.toString();
// Replace known placeholders with values, preserve unknown ones
Pattern placeholderPattern = Pattern.compile("\\{(.*?)}");
Matcher placeholderMatcher = placeholderPattern.matcher(result);
Matcher placeholderMatcher = PLACEHOLDER_PATTERN.matcher(result);
StringBuilder finalResult = new StringBuilder();
while (placeholderMatcher.find()) {
@@ -165,7 +167,7 @@ public class PathPatternResolver {
return result;
}
private static String sanitize(String input) {
private String sanitize(String input) {
if (input == null) return "";
return WHITESPACE_PATTERN.matcher(CONTROL_CHARACTER_PATTERN.matcher(INVALID_CHARS_PATTERN.matcher(input).replaceAll("")).replaceAll("")).replaceAll(" ")
.trim();
@@ -2,15 +2,14 @@ package com.adityachandel.booklore.util;
import jakarta.servlet.http.HttpServletRequest;
import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public final class RequestUtils {
@UtilityClass
public class RequestUtils {
private RequestUtils() {
}
public static HttpServletRequest getCurrentRequest() {
public HttpServletRequest getCurrentRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attrs == null) {
throw new IllegalStateException("No current HTTP request found");
@@ -1,12 +1,14 @@
package com.adityachandel.booklore.util;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
@UtilityClass
public class SecurityContextVirtualThread {
public static void runWithSecurityContext(Runnable task) {
public void runWithSecurityContext(Runnable task) {
Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
Thread.startVirtualThread(() -> {
@@ -21,7 +23,7 @@ public class SecurityContextVirtualThread {
});
}
public static void runWithSecurityContext(SecurityContext parentContext, Runnable task) {
public void runWithSecurityContext(SecurityContext parentContext, Runnable task) {
Thread.startVirtualThread(() -> {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(parentContext.getAuthentication());
@@ -2,7 +2,9 @@ package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
import com.adityachandel.booklore.model.enums.PermissionType;
import lombok.experimental.UtilityClass;
@UtilityClass
public class UserPermissionUtils {
public static boolean hasPermission(UserPermissionsEntity perms, PermissionType type) {
@@ -50,6 +50,7 @@ public class BookloreSyncTokenGenerator {
}
public BookloreSyncToken fromRequestHeaders(HttpServletRequest request) {
if (request == null) return null;
String tokenB64 = request.getHeader(KoboHeaders.X_KOBO_SYNCTOKEN);
return tokenB64 != null ? fromBase64(tokenB64) : null;
}
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.util.kobo;
import com.adityachandel.booklore.util.RequestUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@@ -12,6 +13,7 @@ import java.util.regex.Pattern;
@Component
@Slf4j
@RequiredArgsConstructor
public class KoboUrlBuilder {
private static final Pattern IP_ADDRESS_PATTERN = Pattern.compile("\\d+\\.\\d+\\.\\d+\\.\\d+");
@@ -77,15 +77,15 @@ class BookdropMetadataServiceTest {
when(bookdropFileRepository.findById(1L)).thenReturn(Optional.of(sampleFile));
when(metadataExtractorFactory.extractMetadata(eq(BookFileExtension.EPUB), any(File.class))).thenReturn(metadata);
when(objectMapper.writeValueAsString(metadata)).thenReturn("{\"title\":\"Test Book\"}");
when(bookdropFileRepository.save(any())).thenReturn(sampleFile);
when(objectMapper.writeValueAsString(any(BookMetadata.class))).thenReturn("{\"title\":\"Test Book\"}");
when(bookdropFileRepository.save(any(BookdropFileEntity.class))).thenReturn(sampleFile);
BookdropFileEntity result = bookdropMetadataService.attachInitialMetadata(1L);
assertThat(result).isNotNull();
assertThat(result.getOriginalMetadata()).contains("Test Book");
assertThat(result.getUpdatedAt()).isBeforeOrEqualTo(Instant.now());
verify(bookdropFileRepository).save(result);
verify(bookdropFileRepository).save(any(BookdropFileEntity.class));
}
@Test
@@ -129,7 +129,6 @@ class BookdropMetadataServiceTest {
BookdropFileEntity result = bookdropMetadataService.attachInitialMetadata(1L);
assertThat(result.getOriginalMetadata()).contains("No Cover Book");
verify(fileService, never()).saveImage(any(), any());
verify(bookdropFileRepository).save(result);
}
@@ -76,10 +76,11 @@ class AbstractFileProcessorTest {
Book duplicateBook = createMockBook(1L, "file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
eq(libraryFile), eq("hash1"), eq(bookRepository), eq(bookAdditionalFileRepository), eq(bookMapper)))
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(duplicateBook));
BookEntity bookEntity = createMockBookEntity(1L, "file.pdf", "hash1", "sub", libraryFile.getLibraryPathEntity());
@@ -103,9 +104,11 @@ class AbstractFileProcessorTest {
Book existingBook = createMockBook(2L, "file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash2");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.empty());
when(bookRepository.findBookByFileNameAndLibraryId("file.pdf", 1L))
.thenReturn(Optional.of(existingEntity));
@@ -129,9 +132,11 @@ class AbstractFileProcessorTest {
Book newBook = createMockBook(3L, "file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash3");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.empty());
when(bookRepository.findBookByFileNameAndLibraryId("file.pdf", 1L))
.thenReturn(Optional.empty());
@@ -163,9 +168,11 @@ class AbstractFileProcessorTest {
Book updatedBook = createMockBook(1L, "file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(duplicateBook));
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
when(bookMapper.toBook(existingEntity)).thenReturn(updatedBook);
@@ -193,9 +200,11 @@ class AbstractFileProcessorTest {
Book updatedBook = createMockBook(1L, "new-file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(duplicateBook));
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
when(bookMapper.toBook(existingEntity)).thenReturn(updatedBook);
@@ -236,9 +245,11 @@ class AbstractFileProcessorTest {
Book updatedBook = createMockBook(1L, "file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(duplicateBook));
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
when(bookMapper.toBook(existingEntity)).thenReturn(updatedBook);
@@ -263,9 +274,11 @@ class AbstractFileProcessorTest {
BookEntity existingEntity = createMockBookEntity(1L, "file.pdf", "hash1", "sub", libraryFile.getLibraryPathEntity());
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(duplicateBook));
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
@@ -288,9 +301,11 @@ class AbstractFileProcessorTest {
Book duplicateBook = createMockBook(1L, "file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(duplicateBook));
when(bookRepository.findById(1L)).thenReturn(Optional.empty());
@@ -312,9 +327,11 @@ class AbstractFileProcessorTest {
BookEntity existingEntity = createMockBookEntity(1L, "file.pdf", "old-hash", "sub", libraryFile.getLibraryPathEntity());
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("new-hash");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(duplicateBook));
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
when(bookMapper.toBook(existingEntity)).thenReturn(duplicateBook);
@@ -350,9 +367,11 @@ class AbstractFileProcessorTest {
Book newBook = createMockBook(3L, "file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash3");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.empty());
when(bookRepository.findBookByFileNameAndLibraryId("file.pdf", 1L))
.thenReturn(Optional.empty());
@@ -394,9 +413,11 @@ class AbstractFileProcessorTest {
Book updatedBook = createMockBook(1L, "new-file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(duplicateBook));
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
when(bookMapper.toBook(existingEntity)).thenReturn(updatedBook);
@@ -421,9 +442,11 @@ class AbstractFileProcessorTest {
Book book = createMockBook(1L, "file.pdf");
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
any(LibraryFile.class), any(String.class)))
.thenReturn(Optional.of(book));
when(bookRepository.findById(1L)).thenReturn(Optional.of(
createMockBookEntity(1L, "file.pdf", "hash1", "sub", libraryFile.getLibraryPathEntity())));
@@ -0,0 +1,123 @@
package com.adityachandel.booklore.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BookUtilsTest {
@Test
void testCleanFileName_nullInput() {
String result = BookUtils.cleanFileName(null);
assertNull(result);
}
@Test
void testCleanFileName_simpleName() {
String result = BookUtils.cleanFileName("Test Book.pdf");
assertEquals("Test Book", result);
}
@Test
void testCleanFileName_withZLibrary() {
String result = BookUtils.cleanFileName("Test Book (Z-Library).pdf");
assertEquals("Test Book", result);
}
@Test
void testCleanFileName_withAuthorInParentheses() {
String result = BookUtils.cleanFileName("Test Book (John Doe).pdf");
assertEquals("Test Book", result);
}
@Test
void testCleanFileName_withMultipleExtensions() {
String result = BookUtils.cleanFileName("Test Book.epub.zip");
assertEquals("Test Book.epub", result);
}
@Test
void testCleanFileName_noExtension() {
String result = BookUtils.cleanFileName("Test Book");
assertEquals("Test Book", result);
}
@Test
void testCleanFileName_onlyExtension() {
// Hidden files (starting with dot) should keep their name to avoid empty strings
// which could cause DB constraint or filesystem errors
String result = BookUtils.cleanFileName(".pdf");
assertEquals(".pdf", result);
}
@Test
void testCleanFileName_complexCase() {
String result = BookUtils.cleanFileName("Advanced Calculus (Z-Library) (Michael Spivak).pdf");
assertEquals("Advanced Calculus", result);
}
@Test
void testCleanAndTruncateSearchTerm_nullInput() {
String result = BookUtils.cleanAndTruncateSearchTerm(null);
assertEquals("", result);
}
@Test
void testCleanAndTruncateSearchTerm_emptyString() {
String result = BookUtils.cleanAndTruncateSearchTerm("");
assertEquals("", result);
}
@Test
void testCleanAndTruncateSearchTerm_simpleText() {
String result = BookUtils.cleanAndTruncateSearchTerm("Hello World");
assertEquals("Hello World", result);
}
@Test
void testCleanAndTruncateSearchTerm_withSpecialChars() {
String result = BookUtils.cleanAndTruncateSearchTerm("Hello, World! How are you?");
assertEquals("Hello World How are you", result);
}
@Test
void testCleanAndTruncateSearchTerm_withBrackets() {
String result = BookUtils.cleanAndTruncateSearchTerm("Test [Book] {Series}");
assertEquals("Test Book Series", result);
}
@Test
void testCleanAndTruncateSearchTerm_longText() {
String longText = "This is a very long search term that should be truncated because it exceeds sixty characters in length and needs to be shortened";
String result = BookUtils.cleanAndTruncateSearchTerm(longText);
assertTrue(result.length() <= 60);
assertEquals("This is a very long search term that should be truncated", result);
}
@Test
void testCleanAndTruncateSearchTerm_longTextWithSpecialChars() {
String longText = "This-is,a@very#long$search%term^with&special*chars(that)should[be]truncated{because}it<exceeds>sixty?characters";
String result = BookUtils.cleanAndTruncateSearchTerm(longText);
assertTrue(result.length() <= 60);
assertEquals("Thisisaverylongsearchtermwithspecialcharsthatshouldbetruncat", result);
}
@Test
void testCleanAndTruncateSearchTerm_exactly60Chars() {
String text = "A".repeat(60);
String result = BookUtils.cleanAndTruncateSearchTerm(text);
assertEquals(text, result);
assertEquals(60, result.length());
}
@Test
void testCleanAndTruncateSearchTerm_whitespaceHandling() {
String result = BookUtils.cleanAndTruncateSearchTerm(" Multiple Spaces Here ");
assertEquals("Multiple Spaces Here", result);
}
@Test
void testCleanAndTruncateSearchTerm_onlySpecialChars() {
String result = BookUtils.cleanAndTruncateSearchTerm(",.!@#$%^&*()[]{}");
assertEquals("", result);
}
}
@@ -0,0 +1,72 @@
package com.adityachandel.booklore.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FileServiceTest {
@Test
void testTruncate_nullInput() {
String result = FileService.truncate(null, 10);
assertNull(result);
}
@Test
void testTruncate_emptyString() {
String result = FileService.truncate("", 10);
assertEquals("", result);
}
@Test
void testTruncate_shortString() {
String input = "short";
String result = FileService.truncate(input, 10);
assertEquals("short", result);
}
@Test
void testTruncate_exactLength() {
String input = "exactly10";
String result = FileService.truncate(input, 9);
assertEquals("exactly10", result);
}
@Test
void testTruncate_longString() {
String input = "this is a very long string that should be truncated";
String result = FileService.truncate(input, 20);
assertEquals("this is a very long ", result);
assertEquals(20, result.length());
}
@Test
void testTruncate_zeroMaxLength() {
String input = "test string";
String result = FileService.truncate(input, 0);
assertEquals("", result);
}
@Test
void testTruncate_negativeMaxLength() {
String input = "test string";
String result = FileService.truncate(input, -5);
assertEquals("", result);
}
@Test
void testTruncate_unicodeCharacters() {
String input = "héllo wörld with unicode";
String result = FileService.truncate(input, 15);
assertEquals("héllo wörld wit", result);
assertEquals(15, result.length());
}
@Test
void testTruncate_multibyteCharacters() {
String input = "🚀 rocket emoji test 🌟";
String result = FileService.truncate(input, 10);
// Note: This might not be exactly 10 characters due to how Java handles string length with emojis
assertTrue(result.length() <= input.length());
}
}
@@ -0,0 +1,80 @@
package com.adityachandel.booklore.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Md5UtilTest {
@Test
void testMd5Hex_emptyString() {
String result = Md5Util.md5Hex("");
assertEquals("d41d8cd98f00b204e9800998ecf8427e", result);
}
@Test
void testMd5Hex_simpleText() {
String result = Md5Util.md5Hex("hello");
assertEquals("5d41402abc4b2a76b9719d911017c592", result);
}
@Test
void testMd5Hex_helloWorld() {
String result = Md5Util.md5Hex("hello world");
assertEquals("5eb63bbbe01eeed093cb22bb8f5acdc3", result);
}
@Test
void testMd5Hex_numbers() {
String result = Md5Util.md5Hex("123456789");
assertEquals("25f9e794323b453885f5181f1b624d0b", result);
}
@Test
void testMd5Hex_specialCharacters() {
String result = Md5Util.md5Hex("!@#$%^&*()");
assertEquals("05b28d17a7b6e7024b6e5d8cc43a8bf7", result);
}
@Test
void testMd5Hex_unicode() {
String result = Md5Util.md5Hex("héllo wörld");
assertEquals("ed0c22cc110ede12327851863c078138", result);
}
@Test
void testMd5Hex_longText() {
String longText = "This is a longer text that should produce a consistent MD5 hash regardless of how many times we call the function with the same input.";
String result1 = Md5Util.md5Hex(longText);
String result2 = Md5Util.md5Hex(longText);
assertEquals(result1, result2);
assertEquals(32, result1.length());
}
@Test
void testMd5Hex_differentInputs() {
String result1 = Md5Util.md5Hex("hello");
String result2 = Md5Util.md5Hex("world");
assertNotEquals(result1, result2);
}
@Test
void testMd5Hex_caseSensitive() {
String result1 = Md5Util.md5Hex("Hello");
String result2 = Md5Util.md5Hex("hello");
assertNotEquals(result1, result2);
}
@Test
void testMd5Hex_nullInput() {
// MD5Util now handles null input safely by returning null
String result = Md5Util.md5Hex(null);
assertNull(result);
}
@Test
void testMd5Hex_length() {
String result = Md5Util.md5Hex("any input");
assertEquals(32, result.length()); // MD5 always produces 32 character hex string
assertTrue(result.matches("[a-f0-9]{32}")); // Only lowercase hex characters
}
}
@@ -0,0 +1,314 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class PathPatternResolverTest {
@Test
void testResolvePattern_nullPattern() {
BookMetadata metadata = BookMetadata.builder()
.title("Test Book")
.build();
String result = PathPatternResolver.resolvePattern(metadata, null, "test.pdf");
assertEquals("test.pdf", result);
}
@Test
void testResolvePattern_blankPattern() {
BookMetadata metadata = BookMetadata.builder()
.title("Test Book")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "", "test.pdf");
assertEquals("test.pdf", result);
}
@Test
void testResolvePattern_whitespacePattern() {
BookMetadata metadata = BookMetadata.builder()
.title("Test Book")
.build();
String result = PathPatternResolver.resolvePattern(metadata, " ", "test.pdf");
assertEquals("test.pdf", result);
}
@Test
void testResolvePattern_simpleTitle() {
BookMetadata metadata = BookMetadata.builder()
.title("Test Book")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "original.pdf");
assertEquals("Test Book.pdf", result);
}
@Test
void testResolvePattern_titleWithExtension() {
BookMetadata metadata = BookMetadata.builder()
.title("Test Book")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}.{extension}", "original.pdf");
assertEquals("Test Book.pdf", result);
}
@Test
void testResolvePattern_multiplePlaceholders() {
BookMetadata metadata = BookMetadata.builder()
.title("Test Book")
.authors(Set.of("John Doe", "Jane Smith"))
.publishedDate(LocalDate.of(2023, 5, 15))
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors} - {title} ({year})", "original.pdf");
// Authors from a Set may be in any order
assertTrue(result.equals("John Doe, Jane Smith - Test Book (2023).pdf") ||
result.equals("Jane Smith, John Doe - Test Book (2023).pdf"));
}
@Test
void testResolvePattern_authorsList() {
BookMetadata metadata = BookMetadata.builder()
.authors(Set.of("Author One", "Author Two"))
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "original.pdf");
// Authors from a Set may be in any order
assertTrue(result.equals("Author One, Author Two.pdf") || result.equals("Author Two, Author One.pdf"));
}
@Test
void testResolvePattern_seriesInfo() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
.seriesName("Series Name")
.seriesNumber(2.0f)
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{series} #{seriesIndex} - {title}", "original.pdf");
assertEquals("Series Name #2 - Book Title.pdf", result);
}
@Test
void testResolvePattern_seriesNumberFloat() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
.seriesName("Series Name")
.seriesNumber(2.5f)
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{series} #{seriesIndex} - {title}", "original.pdf");
assertEquals("Series Name #2.5 - Book Title.pdf", result);
}
@Test
void testResolvePattern_optionalBlock_allPresent() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
.authors(Set.of("Author Name"))
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>", "original.pdf");
assertEquals("Book Title - Author Name.pdf", result);
}
@Test
void testResolvePattern_optionalBlock_missingValue() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
// authors is missing/empty
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>", "original.pdf");
assertEquals("Book Title.pdf", result);
}
@Test
void testResolvePattern_isbnPriority() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
.isbn13("9781234567890")
.isbn10("1234567890")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title} - {isbn}", "original.pdf");
assertEquals("Book Title - 9781234567890.pdf", result);
}
@Test
void testResolvePattern_isbn10Fallback() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
.isbn10("1234567890")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title} - {isbn}", "original.pdf");
assertEquals("Book Title - 1234567890.pdf", result);
}
@Test
void testResolvePattern_nullMetadata() {
String result = PathPatternResolver.resolvePattern((BookMetadata) null, "{title}", "original.pdf");
assertEquals("Untitled.pdf", result);
}
@Test
void testResolvePattern_nullTitle() {
BookMetadata metadata = BookMetadata.builder()
.title(null)
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "original.pdf");
assertEquals("Untitled.pdf", result);
}
@Test
void testResolvePattern_currentFilename() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{currentFilename}", "original.pdf");
assertEquals("original.pdf", result);
}
@Test
void testResolvePattern_withBookEntity() {
BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Book Title");
BookEntity book = new BookEntity();
book.setFileName("book.epub");
book.setMetadata(metadata);
String result = PathPatternResolver.resolvePattern(book, "{title}.{extension}");
assertEquals("Book Title.epub", result);
}
@Test
void testResolvePattern_withBookMetadataEntity() {
BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Book Title");
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "original.pdf");
assertEquals("Book Title.pdf", result);
}
@Test
void testResolvePattern_specialCharacters() {
BookMetadata metadata = BookMetadata.builder()
.title("Book: Title? *With* Special/Chars")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "original.pdf");
// Special characters should be sanitized
assertEquals("Book Title With SpecialChars.pdf", result);
}
@Test
void testResolvePattern_emptyAuthors() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
.authors(Set.of())
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>", "original.pdf");
assertEquals("Book Title.pdf", result);
}
@Test
void testResolvePattern_handlesNullPattern() {
BookMetadata metadata = BookMetadata.builder()
.title("Test Book")
.build();
String result = PathPatternResolver.resolvePattern(metadata, null, "original.pdf");
assertEquals("original.pdf", result);
}
@Test
void testResolvePattern_sanitizesIllegalCharacters() {
BookMetadata metadata = BookMetadata.builder()
.title("Book: The Sequel/Prequel? Illegal*Chars")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}", "original.pdf");
// Should sanitize illegal filesystem characters
assertNotEquals("Book: The Sequel/Prequel? Illegal*Chars", result);
assertTrue(result.contains("Book") && result.contains("Sequel"));
}
@Test
void testResolvePattern_handlesMissingMetadataFields() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
// authors is intentionally missing/null
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>", "original.pdf");
// Optional block should be omitted since authors is missing
assertEquals("Book Title.pdf", result);
}
@Test
void testResolvePattern_emptyOptionalBlocks() {
BookMetadata metadata = BookMetadata.builder()
.title("Book Title")
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}< [{series}]>< ({year})>", "original.pdf");
// Both optional blocks should be omitted since series and year are missing
assertEquals("Book Title.pdf", result);
}
@Test
void testResolvePattern_complexPattern() {
BookMetadata metadata = BookMetadata.builder()
.title("The Great Book")
.authors(Set.of("John Doe", "Jane Smith"))
.seriesName("Awesome Series")
.seriesNumber(3.0f)
.publishedDate(LocalDate.of(2023, 5, 15))
.build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors} - {title}< [{series} #{seriesIndex}]>< ({year})>", "original.pdf");
// Authors from a Set may be in any order
assertTrue(result.equals("John Doe, Jane Smith - The Great Book [Awesome Series #3] (2023).pdf") ||
result.equals("Jane Smith, John Doe - The Great Book [Awesome Series #3] (2023).pdf"));
}
}
@@ -0,0 +1,59 @@
package com.adityachandel.booklore.util;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import static org.junit.jupiter.api.Assertions.*;
class RequestUtilsTest {
private HttpServletRequest mockRequest;
private ServletRequestAttributes requestAttributes;
@BeforeEach
void setUp() {
mockRequest = new MockHttpServletRequest();
requestAttributes = new ServletRequestAttributes(mockRequest);
RequestContextHolder.setRequestAttributes(requestAttributes);
}
@AfterEach
void tearDown() {
RequestContextHolder.resetRequestAttributes();
}
@Test
void testGetCurrentRequest_success() {
HttpServletRequest result = RequestUtils.getCurrentRequest();
assertNotNull(result);
assertEquals(mockRequest, result);
}
@Test
void testGetCurrentRequest_noRequestAttributes() {
RequestContextHolder.resetRequestAttributes();
assertThrows(IllegalStateException.class, RequestUtils::getCurrentRequest);
}
@Test
void testGetCurrentRequest_nonServletAttributes() {
RequestContextHolder.setRequestAttributes(null);
assertThrows(IllegalStateException.class, RequestUtils::getCurrentRequest);
}
@Test
void testGetCurrentRequest_multipleCalls() {
HttpServletRequest result1 = RequestUtils.getCurrentRequest();
HttpServletRequest result2 = RequestUtils.getCurrentRequest();
assertEquals(result1, result2);
assertEquals(mockRequest, result1);
}
}
@@ -0,0 +1,156 @@
package com.adityachandel.booklore.util;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class SecurityContextVirtualThreadTest {
private Authentication originalAuth;
private SecurityContext originalContext;
@BeforeEach
void setUp() {
originalAuth = new UsernamePasswordAuthenticationToken("testUser", "password", null);
originalContext = new SecurityContextImpl(originalAuth);
SecurityContextHolder.setContext(originalContext);
}
@AfterEach
void tearDown() {
SecurityContextHolder.clearContext();
}
@Test
void testRunWithSecurityContext_executesRunnable() throws ExecutionException, InterruptedException {
AtomicReference<String> result = new AtomicReference<>();
CompletableFuture<Void> future = new CompletableFuture<>();
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
result.set("executed");
future.complete(null);
} catch (Exception e) {
future.completeExceptionally(e);
}
});
// Wait for the virtual thread to complete
future.get();
assertEquals("executed", result.get());
}
@Test
void testRunWithSecurityContext_preservesSecurityContext() throws ExecutionException, InterruptedException {
AtomicReference<Authentication> capturedAuth = new AtomicReference<>();
CompletableFuture<Void> future = new CompletableFuture<>();
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
capturedAuth.set(SecurityContextHolder.getContext().getAuthentication());
future.complete(null);
} catch (Exception e) {
future.completeExceptionally(e);
}
});
future.get();
assertNotNull(capturedAuth.get());
assertEquals(originalAuth.getName(), capturedAuth.get().getName());
}
@Test
void testRunWithSecurityContext_maintainsMainThreadContext() throws ExecutionException, InterruptedException {
CompletableFuture<Void> future = new CompletableFuture<>();
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
// Context should be set here
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
future.complete(null);
} catch (Exception e) {
future.completeExceptionally(e);
}
});
future.get();
// After the virtual thread completes, the main thread's context should still be intact
Authentication mainThreadAuth = SecurityContextHolder.getContext().getAuthentication();
assertNotNull(mainThreadAuth);
assertEquals(originalAuth.getName(), mainThreadAuth.getName());
}
@Test
void testRunWithSecurityContext_withProvidedContext() throws ExecutionException, InterruptedException {
Authentication differentAuth = new UsernamePasswordAuthenticationToken("differentUser", "password", null);
SecurityContext differentContext = new SecurityContextImpl(differentAuth);
AtomicReference<Authentication> capturedAuth = new AtomicReference<>();
CompletableFuture<Void> future = new CompletableFuture<>();
SecurityContextVirtualThread.runWithSecurityContext(differentContext, () -> {
try {
capturedAuth.set(SecurityContextHolder.getContext().getAuthentication());
future.complete(null);
} catch (Exception e) {
future.completeExceptionally(e);
}
});
future.get();
assertNotNull(capturedAuth.get());
assertEquals("differentUser", capturedAuth.get().getName());
}
@Test
void testRunWithSecurityContext_withProvidedContext_clearsAfterExecution() throws ExecutionException, InterruptedException {
Authentication differentAuth = new UsernamePasswordAuthenticationToken("differentUser", "password", null);
SecurityContext differentContext = new SecurityContextImpl(differentAuth);
CompletableFuture<Void> future = new CompletableFuture<>();
SecurityContextVirtualThread.runWithSecurityContext(differentContext, () -> {
try {
// Different context should be set here
assertEquals("differentUser", SecurityContextHolder.getContext().getAuthentication().getName());
future.complete(null);
} catch (Exception e) {
future.completeExceptionally(e);
}
});
future.get();
// Main thread should still have original context
Authentication mainThreadAuth = SecurityContextHolder.getContext().getAuthentication();
assertEquals("testUser", mainThreadAuth.getName());
}
@Test
void testRunWithSecurityContext_handlesException() throws ExecutionException, InterruptedException {
CompletableFuture<Exception> future = new CompletableFuture<>();
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
throw new RuntimeException("Test exception");
} catch (Exception e) {
future.complete(e);
throw e;
}
});
Exception capturedException = future.get();
assertNotNull(capturedException);
assertEquals("Test exception", capturedException.getMessage());
}
}
@@ -0,0 +1,94 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
import com.adityachandel.booklore.model.enums.PermissionType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import static org.junit.jupiter.api.Assertions.*;
class UserPermissionUtilsTest {
@ParameterizedTest
@EnumSource(PermissionType.class)
void testHasPermission_true(PermissionType permissionType) {
UserPermissionsEntity perms = createPermissionsWith(permissionType, true);
assertTrue(UserPermissionUtils.hasPermission(perms, permissionType));
}
@ParameterizedTest
@EnumSource(PermissionType.class)
void testHasPermission_false(PermissionType permissionType) {
UserPermissionsEntity perms = createPermissionsWith(permissionType, false);
assertFalse(UserPermissionUtils.hasPermission(perms, permissionType));
}
@Test
void testHasPermission_allPermissionsFalse() {
UserPermissionsEntity perms = UserPermissionsEntity.builder()
.permissionUpload(false)
.permissionDownload(false)
.permissionEditMetadata(false)
.permissionManipulateLibrary(false)
.permissionEmailBook(false)
.permissionDeleteBook(false)
.permissionAccessOpds(false)
.permissionSyncKoreader(false)
.permissionSyncKobo(false)
.permissionAdmin(false)
.build();
for (PermissionType type : PermissionType.values()) {
assertFalse(UserPermissionUtils.hasPermission(perms, type));
}
}
@Test
void testHasPermission_allPermissionsTrue() {
UserPermissionsEntity perms = UserPermissionsEntity.builder()
.permissionUpload(true)
.permissionDownload(true)
.permissionEditMetadata(true)
.permissionManipulateLibrary(true)
.permissionEmailBook(true)
.permissionDeleteBook(true)
.permissionAccessOpds(true)
.permissionSyncKoreader(true)
.permissionSyncKobo(true)
.permissionAdmin(true)
.build();
for (PermissionType type : PermissionType.values()) {
assertTrue(UserPermissionUtils.hasPermission(perms, type));
}
}
private UserPermissionsEntity createPermissionsWith(PermissionType permissionType, boolean value) {
UserPermissionsEntity.UserPermissionsEntityBuilder builder = UserPermissionsEntity.builder()
.permissionUpload(false)
.permissionDownload(false)
.permissionEditMetadata(false)
.permissionManipulateLibrary(false)
.permissionEmailBook(false)
.permissionDeleteBook(false)
.permissionAccessOpds(false)
.permissionSyncKoreader(false)
.permissionSyncKobo(false)
.permissionAdmin(false);
switch (permissionType) {
case UPLOAD -> builder.permissionUpload(value);
case DOWNLOAD -> builder.permissionDownload(value);
case EDIT_METADATA -> builder.permissionEditMetadata(value);
case MANIPULATE_LIBRARY -> builder.permissionManipulateLibrary(value);
case EMAIL_BOOK -> builder.permissionEmailBook(value);
case DELETE_BOOK -> builder.permissionDeleteBook(value);
case ACCESS_OPDS -> builder.permissionAccessOpds(value);
case SYNC_KOREADER -> builder.permissionSyncKoreader(value);
case SYNC_KOBO -> builder.permissionSyncKobo(value);
case ADMIN -> builder.permissionAdmin(value);
}
return builder.build();
}
}
@@ -0,0 +1,170 @@
package com.adityachandel.booklore.util.kobo;
import com.adityachandel.booklore.model.dto.BookloreSyncToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class BookloreSyncTokenGeneratorTest {
private ObjectMapper objectMapper;
private BookloreSyncTokenGenerator generator;
@BeforeEach
void setUp() {
objectMapper = mock(ObjectMapper.class);
generator = new BookloreSyncTokenGenerator(objectMapper);
}
@Test
void testToBase64_success() throws Exception {
BookloreSyncToken token = BookloreSyncToken.builder()
.ongoingSyncPointId("ongoing123")
.lastSuccessfulSyncPointId("last456")
.rawKoboSyncToken("raw789")
.build();
String json = "{\"ongoingSyncPointId\":\"ongoing123\",\"lastSuccessfulSyncPointId\":\"last456\",\"rawKoboSyncToken\":\"raw789\"}";
when(objectMapper.writeValueAsString(token)).thenReturn(json);
String result = generator.toBase64(token);
assertTrue(result.startsWith("BOOKLORE."));
String base64Part = result.substring("BOOKLORE.".length());
String decodedJson = new String(Base64.getDecoder().decode(base64Part));
assertEquals(json, decodedJson);
}
@Test
void testToBase64_exception() throws Exception {
BookloreSyncToken token = BookloreSyncToken.builder().build();
when(objectMapper.writeValueAsString(any(BookloreSyncToken.class)))
.thenThrow(new RuntimeException("Serialization failed"));
String result = generator.toBase64(token);
assertEquals("BOOKLORE.", result);
}
@Test
void testFromBase64_booklorePrefix() throws Exception {
BookloreSyncToken token = BookloreSyncToken.builder()
.ongoingSyncPointId("test123")
.lastSuccessfulSyncPointId("test456")
.build();
String json = "{\"ongoingSyncPointId\":\"test123\",\"lastSuccessfulSyncPointId\":\"test456\"}";
String base64 = Base64.getEncoder().encodeToString(json.getBytes());
String tokenB64 = "BOOKLORE." + base64;
when(objectMapper.readValue(json.getBytes(), BookloreSyncToken.class)).thenReturn(token);
BookloreSyncToken result = generator.fromBase64(tokenB64);
assertNotNull(result);
assertEquals("test123", result.getOngoingSyncPointId());
assertEquals("test456", result.getLastSuccessfulSyncPointId());
}
@Test
void testFromBase64_withDot() throws Exception {
String rawToken = "some.raw.token";
BookloreSyncToken result = generator.fromBase64(rawToken);
assertNotNull(result);
assertEquals(rawToken, result.getRawKoboSyncToken());
assertNull(result.getOngoingSyncPointId());
assertNull(result.getLastSuccessfulSyncPointId());
}
@Test
void testFromBase64_invalidBase64() {
String invalidToken = "BOOKLORE.invalidbase64";
BookloreSyncToken result = generator.fromBase64(invalidToken);
assertNotNull(result);
assertNull(result.getOngoingSyncPointId());
assertNull(result.getLastSuccessfulSyncPointId());
assertNull(result.getRawKoboSyncToken());
}
@Test
void testFromBase64_deserializationException() throws Exception {
String json = "{\"invalid\":\"json\"}";
String base64 = Base64.getEncoder().encodeToString(json.getBytes());
String tokenB64 = "BOOKLORE." + base64;
when(objectMapper.readValue(any(byte[].class), eq(BookloreSyncToken.class)))
.thenThrow(new RuntimeException("Deserialization failed"));
BookloreSyncToken result = generator.fromBase64(tokenB64);
assertNotNull(result);
assertNull(result.getOngoingSyncPointId());
assertNull(result.getLastSuccessfulSyncPointId());
assertNull(result.getRawKoboSyncToken());
}
@Test
void testFromBase64_emptyString() {
BookloreSyncToken result = generator.fromBase64("");
assertNotNull(result);
assertNull(result.getOngoingSyncPointId());
assertNull(result.getLastSuccessfulSyncPointId());
assertNull(result.getRawKoboSyncToken());
}
@Test
void testFromBase64_null() {
BookloreSyncToken result = generator.fromBase64(null);
assertNotNull(result);
assertNull(result.getOngoingSyncPointId());
assertNull(result.getLastSuccessfulSyncPointId());
assertNull(result.getRawKoboSyncToken());
}
@Test
void testFromRequestHeaders_withHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-Kobo-Synctoken", "BOOKLORE.test");
BookloreSyncToken expectedToken = new BookloreSyncToken();
when(objectMapper.readValue(any(byte[].class), eq(BookloreSyncToken.class))).thenReturn(expectedToken);
BookloreSyncToken result = generator.fromRequestHeaders(request);
assertNotNull(result);
assertEquals(expectedToken, result);
}
@Test
void testFromRequestHeaders_noHeader() {
HttpServletRequest request = new MockHttpServletRequest();
BookloreSyncToken result = generator.fromRequestHeaders(request);
assertNull(result);
}
@Test
void testFromRequestHeaders_nullRequest() {
BookloreSyncToken result = generator.fromRequestHeaders(null);
assertNull(result);
}
}
@@ -0,0 +1,129 @@
package com.adityachandel.booklore.util.kobo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import static org.junit.jupiter.api.Assertions.*;
class KoboUrlBuilderTest {
private KoboUrlBuilder koboUrlBuilder;
private MockHttpServletRequest mockRequest;
@BeforeEach
void setUp() {
// Mock the request attributes
mockRequest = new MockHttpServletRequest();
mockRequest.setScheme("http");
mockRequest.setServerName("localhost");
mockRequest.setServerPort(8080);
mockRequest.setContextPath("");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(mockRequest));
// Manually instantiate KoboUrlBuilder
koboUrlBuilder = new KoboUrlBuilder();
// Set the @Value field using ReflectionTestUtils
ReflectionTestUtils.setField(koboUrlBuilder, "serverPort", 8080);
}
@AfterEach
void tearDown() {
RequestContextHolder.resetRequestAttributes();
}
@Test
void testDownloadUrl() {
String token = "testToken";
Long bookId = 123L;
String result = koboUrlBuilder.downloadUrl(token, bookId);
assertNotNull(result);
assertTrue(result.contains("/api/kobo/" + token + "/v1/books/" + bookId + "/download"),
"URL should contain the expected path segments");
assertTrue(result.startsWith("http://"), "URL should start with http://");
}
@Test
void testImageUrlTemplate() {
String token = "testToken";
String result = koboUrlBuilder.imageUrlTemplate(token);
assertNotNull(result);
assertTrue(result.contains("/api/kobo/" + token + "/v1/books/"),
"URL should contain the expected path segments");
assertTrue(result.contains("{ImageId}"), "URL should contain ImageId placeholder");
assertTrue(result.contains("{Width}"), "URL should contain Width placeholder");
assertTrue(result.contains("{Height}"), "URL should contain Height placeholder");
assertTrue(result.contains("image.jpg"), "URL should end with image.jpg");
}
@Test
void testImageUrlQualityTemplate() {
String token = "testToken";
String result = koboUrlBuilder.imageUrlQualityTemplate(token);
assertNotNull(result);
assertTrue(result.contains("/api/kobo/" + token + "/v1/books/"),
"URL should contain the expected path segments");
assertTrue(result.contains("{ImageId}"), "URL should contain ImageId placeholder");
assertTrue(result.contains("{Width}"), "URL should contain Width placeholder");
assertTrue(result.contains("{Height}"), "URL should contain Height placeholder");
assertTrue(result.contains("{Quality}"), "URL should contain Quality placeholder");
assertTrue(result.contains("{IsGreyscale}"), "URL should contain IsGreyscale placeholder");
assertTrue(result.contains("image.jpg"), "URL should end with image.jpg");
}
@Test
void testDownloadUrlWithXForwardedPort() {
// Set X-Forwarded-Port header
mockRequest.addHeader("X-Forwarded-Port", "443");
String token = "testToken";
Long bookId = 123L;
String result = koboUrlBuilder.downloadUrl(token, bookId);
assertNotNull(result);
assertTrue(result.contains("/api/kobo/" + token + "/v1/books/" + bookId + "/download"),
"URL should contain the expected path segments");
}
@Test
void testDownloadUrlWithInvalidXForwardedPort() {
// Set invalid X-Forwarded-Port header
mockRequest.addHeader("X-Forwarded-Port", "invalid");
String token = "testToken";
Long bookId = 123L;
String result = koboUrlBuilder.downloadUrl(token, bookId);
assertNotNull(result);
assertTrue(result.contains("/api/kobo/" + token + "/v1/books/" + bookId + "/download"),
"URL should contain the expected path segments even with invalid port header");
}
@Test
void testUrlBuilderWithIpAddress() {
// Test with IP address instead of localhost
mockRequest.setServerName("192.168.1.100");
mockRequest.addHeader("X-Forwarded-Port", "8443");
String token = "testToken";
Long bookId = 123L;
String result = koboUrlBuilder.downloadUrl(token, bookId);
assertNotNull(result);
assertTrue(result.contains("/api/kobo/" + token + "/v1/books/" + bookId + "/download"),
"URL should contain the expected path segments");
}
}