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+");