refactor(fb2, misc): Improve code quality, update to modern Java patterns, add reasonable initial values for StringBuilders (#1932)
* fix(FilenamePatternExtractor): correct date format regex logic and add comprehensive tests - Fix bug in buildRegexForDateFormat to handle single 'M' and 'd' at any position - Add FilenamePatternExtractorDateFormatTest and FilenamePatternExtractorIntegrationTest for date extraction scenarios - Improve StringBuilder initialization for performance in multiple classes - Precompile regex patterns in Fb2MetadataExtractor for efficiency - Add Fb2MetadataExtractorOptimizationTest for pattern and StringBuilder usage - Add null check in BookFilePersistenceService.markAllBooksUnderPathAsDeleted - Improve path validation logic in PathPatternResolver Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * test: remove unnecesary tests Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> --------- Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
+2
-2
@@ -352,13 +352,13 @@ public class FilenamePatternExtractor {
|
||||
} else if (dateFormat.startsWith("MM", i)) {
|
||||
result.append("\\d{2}");
|
||||
i += 2;
|
||||
} else if (dateFormat.startsWith("M", i)) {
|
||||
} else if (i < dateFormat.length() && dateFormat.charAt(i) == 'M') {
|
||||
result.append("\\d{1,2}");
|
||||
i += 1;
|
||||
} else if (dateFormat.startsWith("dd", i)) {
|
||||
result.append("\\d{2}");
|
||||
i += 2;
|
||||
} else if (dateFormat.startsWith("d", i)) {
|
||||
} else if (i < dateFormat.length() && dateFormat.charAt(i) == 'd') {
|
||||
result.append("\\d{1,2}");
|
||||
i += 1;
|
||||
} else {
|
||||
|
||||
+22
-17
@@ -30,6 +30,9 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
private static final String FB2_NAMESPACE = "http://www.gribuser.ru/xml/fictionbook/2.0";
|
||||
private static final Pattern YEAR_PATTERN = Pattern.compile("\\d{4}");
|
||||
private static final Pattern ISBN_PATTERN = Pattern.compile("\\d{9}[\\dXx]");
|
||||
private static final Pattern KEYWORD_SEPARATOR_PATTERN = Pattern.compile("[,;]");
|
||||
private static final Pattern ISBN_CLEANER_PATTERN = Pattern.compile("[^0-9Xx]");
|
||||
private static final Pattern ISO_DATE_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File file) {
|
||||
@@ -169,7 +172,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
if (keywords != null) {
|
||||
String keywordsText = keywords.getTextContent().trim();
|
||||
if (StringUtils.isNotBlank(keywordsText)) {
|
||||
for (String keyword : keywordsText.split("[,;]")) {
|
||||
for (String keyword : KEYWORD_SEPARATOR_PATTERN.split(keywordsText)) {
|
||||
String trimmed = keyword.trim();
|
||||
if (StringUtils.isNotBlank(trimmed)) {
|
||||
categories.add(trimmed);
|
||||
@@ -240,7 +243,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
// Extract ISBN
|
||||
Element isbn = getFirstElementByTagNameNS(publishInfo, FB2_NAMESPACE, "isbn");
|
||||
if (isbn != null) {
|
||||
String isbnText = isbn.getTextContent().trim().replaceAll("[^0-9Xx]", "");
|
||||
String isbnText = ISBN_CLEANER_PATTERN.matcher(isbn.getTextContent().trim()).replaceAll("");
|
||||
if (isbnText.length() == 13) {
|
||||
builder.isbn13(isbnText);
|
||||
} else if (isbnText.length() == 10) {
|
||||
@@ -270,22 +273,22 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
Element lastName = getFirstElementByTagNameNS(personElement, FB2_NAMESPACE, "last-name");
|
||||
Element nickname = getFirstElementByTagNameNS(personElement, FB2_NAMESPACE, "nickname");
|
||||
|
||||
StringBuilder name = new StringBuilder();
|
||||
StringBuilder name = new StringBuilder(64);
|
||||
|
||||
if (firstName != null) {
|
||||
name.append(firstName.getTextContent().trim());
|
||||
}
|
||||
if (middleName != null) {
|
||||
if (name.length() > 0) name.append(" ");
|
||||
if (!name.isEmpty()) name.append(" ");
|
||||
name.append(middleName.getTextContent().trim());
|
||||
}
|
||||
if (lastName != null) {
|
||||
if (name.length() > 0) name.append(" ");
|
||||
if (!name.isEmpty()) name.append(" ");
|
||||
name.append(lastName.getTextContent().trim());
|
||||
}
|
||||
|
||||
// If no name parts found, try nickname
|
||||
if (name.length() == 0 && nickname != null) {
|
||||
if (name.isEmpty() && nickname != null) {
|
||||
name.append(nickname.getTextContent().trim());
|
||||
}
|
||||
|
||||
@@ -320,7 +323,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
try {
|
||||
// Try parsing ISO date format (YYYY-MM-DD)
|
||||
if (dateString.matches("\\d{4}-\\d{2}-\\d{2}")) {
|
||||
if (ISO_DATE_PATTERN.matcher(dateString).matches()) {
|
||||
return LocalDate.parse(dateString);
|
||||
}
|
||||
|
||||
@@ -339,10 +342,10 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
private Element getFirstElementByTagNameNS(Node parent, String namespace, String localName) {
|
||||
NodeList nodes;
|
||||
if (parent instanceof Document) {
|
||||
nodes = ((Document) parent).getElementsByTagNameNS(namespace, localName);
|
||||
} else if (parent instanceof Element) {
|
||||
nodes = ((Element) parent).getElementsByTagNameNS(namespace, localName);
|
||||
if (parent instanceof Document document) {
|
||||
nodes = document.getElementsByTagNameNS(namespace, localName);
|
||||
} else if (parent instanceof Element element) {
|
||||
nodes = element.getElementsByTagNameNS(namespace, localName);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
@@ -351,12 +354,14 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
private InputStream getInputStream(File file) throws Exception {
|
||||
FileInputStream fis = new FileInputStream(file);
|
||||
|
||||
// Check if file is gzipped (FB2 files can be .fb2 or .fb2.zip/.fb2.gz)
|
||||
if (file.getName().toLowerCase().endsWith(".gz")) {
|
||||
return new GZIPInputStream(fis);
|
||||
try {
|
||||
if (file.getName().toLowerCase().endsWith(".gz")) {
|
||||
return new GZIPInputStream(fis);
|
||||
}
|
||||
return fis;
|
||||
} catch (Exception e) {
|
||||
fis.close();
|
||||
throw e;
|
||||
}
|
||||
|
||||
return fis;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -247,7 +247,7 @@ public class AmazonBookParser implements BookParser {
|
||||
return url;
|
||||
}
|
||||
|
||||
StringBuilder searchTerm = new StringBuilder();
|
||||
StringBuilder searchTerm = new StringBuilder(256);
|
||||
|
||||
String title = fetchMetadataRequest.getTitle();
|
||||
if (title != null && !title.isEmpty()) {
|
||||
|
||||
+1
-1
@@ -300,7 +300,7 @@ public class DoubanBookParser implements BookParser {
|
||||
}
|
||||
|
||||
private String buildQueryUrl(FetchMetadataRequest fetchMetadataRequest, Book book) {
|
||||
StringBuilder searchTerm = new StringBuilder();
|
||||
StringBuilder searchTerm = new StringBuilder(256);
|
||||
|
||||
String title = fetchMetadataRequest.getTitle();
|
||||
if (title != null && !title.isEmpty()) {
|
||||
|
||||
+3
@@ -76,6 +76,9 @@ public class BookFilePersistenceService {
|
||||
|
||||
@Transactional
|
||||
public int markAllBooksUnderPathAsDeleted(long libraryPathId, String relativeFolderPath) {
|
||||
if (relativeFolderPath == null) {
|
||||
throw new IllegalArgumentException("relativeFolderPath cannot be null");
|
||||
}
|
||||
String normalizedPrefix = relativeFolderPath.endsWith("/") ? relativeFolderPath : (relativeFolderPath + "/");
|
||||
|
||||
List<BookEntity> books = bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(libraryPathId, normalizedPrefix);
|
||||
|
||||
@@ -12,11 +12,12 @@ public class BookUtils {
|
||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[!@$%^&*_=|~`<>?/\"]");
|
||||
private static final Pattern PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN = Pattern.compile("\\s?\\(.*?\\)");
|
||||
private static final Pattern DIACRITICAL_MARKS_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
|
||||
|
||||
public static String buildSearchText(BookMetadataEntity e) {
|
||||
if (e == null) return null;
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringBuilder sb = new StringBuilder(256);
|
||||
if (e.getTitle() != null) sb.append(e.getTitle()).append(" ");
|
||||
if (e.getSubtitle() != null) sb.append(e.getSubtitle()).append(" ");
|
||||
if (e.getSeriesName() != null) sb.append(e.getSeriesName()).append(" ");
|
||||
@@ -41,7 +42,7 @@ public class BookUtils {
|
||||
return null;
|
||||
}
|
||||
String s = java.text.Normalizer.normalize(term, java.text.Normalizer.Form.NFD);
|
||||
s = s.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
|
||||
s = DIACRITICAL_MARKS_PATTERN.matcher(s).replaceAll("");
|
||||
s = s.replace("ø", "o").replace("Ø", "O")
|
||||
.replace("ł", "l").replace("Ł", "L")
|
||||
.replace("æ", "ae").replace("Æ", "AE")
|
||||
@@ -82,7 +83,7 @@ public class BookUtils {
|
||||
if (s.length() > 60) {
|
||||
String[] words = WHITESPACE_PATTERN.split(s);
|
||||
if (words.length > 1) {
|
||||
StringBuilder truncated = new StringBuilder();
|
||||
StringBuilder truncated = new StringBuilder(64);
|
||||
for (String word : words) {
|
||||
if (truncated.length() + word.length() + 1 > 60) break;
|
||||
if (!truncated.isEmpty()) truncated.append(" ");
|
||||
|
||||
@@ -128,7 +128,7 @@ public class PathPatternResolver {
|
||||
// Handle optional blocks enclosed in <...>
|
||||
Pattern optionalBlockPattern = Pattern.compile("<([^<>]*)>");
|
||||
Matcher matcher = optionalBlockPattern.matcher(pattern);
|
||||
StringBuilder resolved = new StringBuilder();
|
||||
StringBuilder resolved = new StringBuilder(1024);
|
||||
|
||||
while (matcher.find()) {
|
||||
String block = matcher.group(1);
|
||||
@@ -161,7 +161,7 @@ public class PathPatternResolver {
|
||||
|
||||
// Replace known placeholders with values, preserve unknown ones
|
||||
Matcher placeholderMatcher = PLACEHOLDER_PATTERN.matcher(result);
|
||||
StringBuilder finalResult = new StringBuilder();
|
||||
StringBuilder finalResult = new StringBuilder(1024);
|
||||
|
||||
while (placeholderMatcher.find()) {
|
||||
String key = placeholderMatcher.group(1);
|
||||
@@ -210,7 +210,7 @@ public class PathPatternResolver {
|
||||
}
|
||||
|
||||
String[] authorArray = COMMA_SPACE_PATTERN.split(authors);
|
||||
StringBuilder result = new StringBuilder();
|
||||
StringBuilder result = new StringBuilder(256);
|
||||
int currentBytes = 0;
|
||||
int truncationLimit = MAX_AUTHOR_BYTES - SUFFIX_BYTES;
|
||||
|
||||
@@ -265,7 +265,7 @@ public class PathPatternResolver {
|
||||
|
||||
private String validateFinalPath(String path) {
|
||||
String[] components = SLASH_PATTERN.split(path);
|
||||
StringBuilder result = new StringBuilder();
|
||||
StringBuilder result = new StringBuilder(512);
|
||||
|
||||
for (int i = 0; i < components.length; i++) {
|
||||
String component = components[i];
|
||||
@@ -277,7 +277,7 @@ public class PathPatternResolver {
|
||||
if (component.getBytes(StandardCharsets.UTF_8).length > MAX_FILESYSTEM_COMPONENT_BYTES) {
|
||||
component = truncatePathComponent(component, MAX_FILESYSTEM_COMPONENT_BYTES);
|
||||
}
|
||||
while (component.endsWith(".")) {
|
||||
while (component != null && !component.isEmpty() && component.endsWith(".")) {
|
||||
component = component.substring(0, component.length() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user