refactor(regex): replace string manipulation with Pattern matching for improved readability (#359)

* refactor(regex): replace string manipulation with Pattern matching for improved readability

* refactor(duplicate-detection): improve filename normalization using regex patterns for clarity

* refactor(oidc): replace regex trailing slash handling with utility method

* refactor(isbn): enhance ISBN extraction by normalizing case in cleaned output
This commit is contained in:
brios
2026-04-22 17:27:07 -04:00
committed by Zach Yale
parent fadc1293c8
commit 78099cc92c
7 changed files with 35 additions and 12 deletions
@@ -17,6 +17,7 @@ import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError;
import org.booklore.util.FileUtils;
import org.springframework.stereotype.Service;
import java.net.URI;
@@ -102,8 +103,8 @@ public class OidcTokenValidator {
private void validateIssuer(JWTClaimsSet claims, String expectedIssuer) {
String issuer = claims.getIssuer();
String normalizedExpected = expectedIssuer.replaceAll("/+$", "");
String normalizedActual = issuer != null ? issuer.replaceAll("/+$", "") : "";
String normalizedExpected = FileUtils.trimTrailingSlashes(expectedIssuer);
String normalizedActual = issuer != null ? FileUtils.trimTrailingSlashes(issuer) : "";
if (!normalizedExpected.equals(normalizedActual)) {
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token issuer mismatch");
@@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@@ -26,6 +27,9 @@ public class DuplicateDetectionService {
BookFileType.EPUB, BookFileType.PDF, BookFileType.AZW3,
BookFileType.MOBI, BookFileType.FB2, BookFileType.CBX, BookFileType.AUDIOBOOK
);
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern UNDERSCORE_HYPHEN_PATTERN = Pattern.compile("[_\\-]");
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-z0-9\\s]");
private final BookRepository bookRepository;
private final BookMapper bookMapper;
@@ -272,11 +276,10 @@ public class DuplicateDetectionService {
int dotIdx = fileName.lastIndexOf('.');
String baseName = dotIdx > 0 ? fileName.substring(0, dotIdx) : fileName;
String normalized = baseName.toLowerCase()
.replaceAll("[_\\-]", " ")
.replaceAll("[^a-z0-9\\s]", "")
.replaceAll("\\s+", " ")
.trim();
String normalized = baseName.toLowerCase();
normalized = UNDERSCORE_HYPHEN_PATTERN.matcher(normalized).replaceAll(" ");
normalized = NON_ALPHANUMERIC_PATTERN.matcher(normalized).replaceAll("");
normalized = WHITESPACE_PATTERN.matcher(normalized).replaceAll(" ").trim();
if (!normalized.isBlank()) {
nameGroups.computeIfAbsent(normalized, k -> new ArrayList<>()).add(book);
@@ -30,12 +30,14 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
@Slf4j
@Service
@AllArgsConstructor
public class PhysicalBookService {
private static final Pattern NON_ISBN_CHAR_PATTERN = Pattern.compile("[^0-9Xx]");
private final BookRepository bookRepository;
private final LibraryRepository libraryRepository;
private final AuthorRepository authorRepository;
@@ -115,13 +117,13 @@ public class PhysicalBookService {
private String extractIsbn13(String isbn) {
if (isbn == null) return null;
String cleaned = isbn.replaceAll("[^0-9X]", "");
String cleaned = NON_ISBN_CHAR_PATTERN.matcher(isbn).replaceAll("").toUpperCase();
return cleaned.length() == 13 ? cleaned : null;
}
private String extractIsbn10(String isbn) {
if (isbn == null) return null;
String cleaned = isbn.replaceAll("[^0-9X]", "");
String cleaned = NON_ISBN_CHAR_PATTERN.matcher(isbn).replaceAll("").toUpperCase();
return cleaned.length() == 10 ? cleaned : null;
}
@@ -152,7 +152,7 @@ public class LibraryFileHelper {
if (allowedFormats == null || allowedFormats.isEmpty()) {
return files;
}
Set<BookFileType> allowed = new HashSet<>(allowedFormats);
Set<BookFileType> allowed = EnumSet.copyOf(allowedFormats);
return files.stream()
.filter(file -> allowed.contains(file.getBookFileType()))
.collect(java.util.stream.Collectors.toList());
@@ -13,6 +13,7 @@ import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.booklore.util.FileUtils;
@Slf4j
@Service
@@ -36,7 +37,7 @@ public class OidcDiagnosticService {
// 1. Fetch discovery document (uncached)
Map<String, Object> doc;
try {
String issuerUri = providerDetails.getIssuerUri().replaceAll("/+$", "");
String issuerUri = FileUtils.trimTrailingSlashes(providerDetails.getIssuerUri());
String discoveryUrl = issuerUri + "/.well-known/openid-configuration";
var factory = new SimpleClientHttpRequestFactory();
@@ -9,6 +9,7 @@ import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
@@ -22,6 +23,7 @@ public class AudioFileUtilityService {
private static final Set<String> AUDIO_EXTENSIONS = Set.of(
".mp3", ".m4a", ".m4b", ".opus"
);
private static final Pattern SEPARATOR_PATTERN = Pattern.compile("[_-]+");
/**
* List all audio files in a folder, sorted naturally (Track 1, Track 2, ... Track 10).
@@ -70,7 +72,7 @@ public class AudioFileUtilityService {
if (lastDot > 0) {
filename = filename.substring(0, lastDot);
}
return filename.replaceAll("[_-]+", " ").trim();
return SEPARATOR_PATTERN.matcher(filename).replaceAll(" ").trim();
}
/**
@@ -302,4 +302,18 @@ public class FileUtils {
}
return false;
}
/**
* Efficiently remove all trailing slashes from a string without using regex.
*/
public String trimTrailingSlashes(String input) {
if (input == null) {
return "";
}
int len = input.length();
while (len > 0 && input.charAt(len - 1) == '/') {
len--;
}
return input.substring(0, len);
}
}