feat(google-parser): improve Google Books API integration with improved metadata handling and series extraction (#2375)

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2026-01-21 22:37:04 -07:00
committed by GitHub
parent 67c12223ea
commit 193c9495a1
3 changed files with 486 additions and 31 deletions
@@ -2,20 +2,25 @@ package com.adityachandel.booklore.model.dto.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data; import lombok.Data;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class GoogleBooksApiResponse { public class GoogleBooksApiResponse {
private Integer totalItems;
private List<Item> items; private List<Item> items;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Item { public static class Item {
private String id; private String id;
private String selfLink;
private VolumeInfo volumeInfo; private VolumeInfo volumeInfo;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class VolumeInfo { public static class VolumeInfo {
private String title; private String title;
private String subtitle; private String subtitle;
@@ -25,18 +30,29 @@ public class GoogleBooksApiResponse {
private String description; private String description;
private List<IndustryIdentifier> industryIdentifiers; private List<IndustryIdentifier> industryIdentifiers;
private Integer pageCount; private Integer pageCount;
private Integer printedPageCount;
private ImageLinks imageLinks; private ImageLinks imageLinks;
private String language; private String language;
private Set<String> categories; private Set<String> categories;
private Double averageRating;
private Integer ratingsCount;
private String maturityRating;
private String printType;
private String previewLink;
private String infoLink;
private String canonicalVolumeLink;
private SeriesInfo seriesInfo;
} }
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class IndustryIdentifier { public static class IndustryIdentifier {
private String type; private String type;
private String identifier; private String identifier;
} }
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ImageLinks { public static class ImageLinks {
private String smallThumbnail; private String smallThumbnail;
private String thumbnail; private String thumbnail;
@@ -45,5 +61,22 @@ public class GoogleBooksApiResponse {
private String large; private String large;
private String extraLarge; private String extraLarge;
} }
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class SeriesInfo {
private String kind;
private String shortSeriesBookTitle;
private String bookDisplayNumber;
private List<VolumeSeries> volumeSeries;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class VolumeSeries {
private String seriesId;
private String seriesBookType;
private Integer orderNumber;
}
}
} }
} }
@@ -2,14 +2,15 @@ package com.adityachandel.booklore.service.metadata.parser;
import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.response.GoogleBooksApiResponse;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest; import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.dto.response.GoogleBooksApiResponse;
import com.adityachandel.booklore.model.enums.MetadataProvider; import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.BookUtils; import com.adityachandel.booklore.util.BookUtils;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
@@ -20,12 +21,10 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse; import java.net.http.HttpResponse;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.List; import java.time.format.DateTimeParseException;
import java.util.Map; import java.util.*;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -35,11 +34,13 @@ import java.util.stream.Stream;
@RequiredArgsConstructor @RequiredArgsConstructor
public class GoogleParser implements BookParser { public class GoogleParser implements BookParser {
private static final Pattern FOUR_DIGIT_YEAR_PATTERN = Pattern.compile("\\d{4}"); private static final Pattern FOUR_DIGIT_YEAR_PATTERN = Pattern.compile("^(\\d{4})$");
private static final Pattern YEAR_MONTH_PATTERN = Pattern.compile("^(\\d{4})-(\\d{2})$");
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[.,\\-\\[\\]{}()!@#$%^&*_=+|~`<>?/\";:]"); private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[.,\\-\\[\\]{}()!@#$%^&*_=+|~`<>?/\";:]");
private static final long MIN_REQUEST_INTERVAL_MS = 1500; private static final long MIN_REQUEST_INTERVAL_MS = 1500;
private static final int MAX_SEARCH_TERM_LENGTH = 60; private static final int MAX_SEARCH_TERM_LENGTH = 60;
private static final int MAX_RESULTS = 20;
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
@@ -63,7 +64,17 @@ public class GoogleParser implements BookParser {
} }
private List<BookMetadata> getMetadataListByIsbn(String isbn) { private List<BookMetadata> getMetadataListByIsbn(String isbn) {
return fetchFromApi("isbn:" + isbn.replace("-", "")); // Try ISBN-13 format first, then ISBN-10
String cleanIsbn = isbn.replace("-", "");
List<BookMetadata> results = fetchFromApi("isbn:" + cleanIsbn, true);
if (results.isEmpty() && cleanIsbn.length() == 13) {
// If ISBN-13 failed, try searching without the prefix for broader results
log.info("ISBN-13 search returned no results, trying general search with ISBN");
results = fetchFromApi(cleanIsbn, true);
}
return results;
} }
public List<BookMetadata> getMetadataListByTerm(String term) { public List<BookMetadata> getMetadataListByTerm(String term) {
@@ -71,13 +82,22 @@ public class GoogleParser implements BookParser {
} }
private List<BookMetadata> fetchFromApi(String query) { private List<BookMetadata> fetchFromApi(String query) {
return fetchFromApi(query, false);
}
private List<BookMetadata> fetchFromApi(String query, boolean isIsbnSearch) {
try { try {
waitForRateLimit(); waitForRateLimit();
URI uri = UriComponentsBuilder.fromUriString(getApiUrl()) // Use smaller maxResults for ISBN searches (typically return 1-3 results)
// Use larger maxResults for title/author searches to find best match
int maxResults = isIsbnSearch ? 5 : MAX_RESULTS;
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(getApiUrl())
.queryParam("q", query) .queryParam("q", query)
.build() .queryParam("maxResults", maxResults);
.toUri();
URI uri = uriBuilder.build().toUri();
log.info("Google Books API URL: {}", uri); log.info("Google Books API URL: {}", uri);
@@ -88,19 +108,74 @@ public class GoogleParser implements BookParser {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) { return handleApiResponse(response);
return parseGoogleBooksApiResponse(response.body()); } catch (IOException e) {
} log.error("IO error while fetching metadata from Google Books API: {}", e.getMessage());
log.error("Failed to fetch metadata from Google Books API. Status: {}, Response: {}",
response.statusCode(), response.body());
return List.of(); return List.of();
} catch (IOException | InterruptedException e) { } catch (InterruptedException e) {
log.error("Error occurred while fetching metadata from Google Books API", e); log.error("Request to Google Books API was interrupted");
Thread.currentThread().interrupt();
return List.of(); return List.of();
} }
} }
private List<BookMetadata> handleApiResponse(HttpResponse<String> response) throws IOException {
int statusCode = response.statusCode();
if (statusCode == 200) {
List<BookMetadata> results = parseGoogleBooksApiResponse(response.body());
List<BookMetadata> filtered = filterIrrelevantResults(results);
return sortByCompleteness(filtered);
}
if (statusCode == 429) {
log.warn("Google Books API rate limit exceeded. Consider increasing request interval.");
return List.of();
}
if (statusCode >= 500) {
log.error("Google Books API server error. Status: {}", statusCode);
return List.of();
}
log.error("Google Books API request failed. Status: {}, Response: {}",
statusCode, response.body());
return List.of();
}
private List<BookMetadata> filterIrrelevantResults(List<BookMetadata> results) {
if (results == null || results.isEmpty()) {
return List.of();
}
return results.stream()
.filter(this::isRelevantResult)
.collect(Collectors.toList());
}
private boolean isRelevantResult(BookMetadata metadata) {
// Must have a title - this is the bare minimum
if (metadata.getTitle() == null || metadata.getTitle().isBlank()) {
return false;
}
// Filter out items with extremely short titles (likely garbage data)
if (metadata.getTitle().trim().length() < 2) {
return false;
}
// Must have at least some identifying information beyond just a title
// (either author, ISBN, description, or publisher)
boolean hasAuthor = metadata.getAuthors() != null && !metadata.getAuthors().isEmpty();
boolean hasIsbn = (metadata.getIsbn13() != null && !metadata.getIsbn13().isBlank()) ||
(metadata.getIsbn10() != null && !metadata.getIsbn10().isBlank());
boolean hasDescription = metadata.getDescription() != null && metadata.getDescription().length() > 10;
boolean hasPublisher = metadata.getPublisher() != null && !metadata.getPublisher().isBlank();
boolean hasGoogleId = metadata.getGoogleId() != null && !metadata.getGoogleId().isBlank();
return hasAuthor || hasIsbn || hasDescription || hasPublisher || hasGoogleId;
}
private List<BookMetadata> parseGoogleBooksApiResponse(String responseBody) throws IOException { private List<BookMetadata> parseGoogleBooksApiResponse(String responseBody) throws IOException {
GoogleBooksApiResponse googleBooksApiResponse = objectMapper.readValue(responseBody, GoogleBooksApiResponse.class); GoogleBooksApiResponse googleBooksApiResponse = objectMapper.readValue(responseBody, GoogleBooksApiResponse.class);
if (googleBooksApiResponse != null && googleBooksApiResponse.getItems() != null) { if (googleBooksApiResponse != null && googleBooksApiResponse.getItems() != null) {
@@ -115,29 +190,219 @@ public class GoogleParser implements BookParser {
GoogleBooksApiResponse.Item.VolumeInfo volumeInfo = item.getVolumeInfo(); GoogleBooksApiResponse.Item.VolumeInfo volumeInfo = item.getVolumeInfo();
Map<String, String> isbns = extractISBNs(volumeInfo.getIndustryIdentifiers()); Map<String, String> isbns = extractISBNs(volumeInfo.getIndustryIdentifiers());
String cleanDescription = cleanDescription(volumeInfo.getDescription());
Integer pageCount = volumeInfo.getPrintedPageCount() != null && volumeInfo.getPrintedPageCount() > 0
? volumeInfo.getPrintedPageCount()
: volumeInfo.getPageCount();
// Filter out invalid page counts
if (pageCount != null && pageCount <= 0) {
pageCount = null;
}
String externalUrl = getExternalUrl(volumeInfo);
SeriesData seriesData = extractSeriesInfo(volumeInfo);
return BookMetadata.builder() return BookMetadata.builder()
.provider(MetadataProvider.Google) .provider(MetadataProvider.Google)
.googleId(item.getId()) .googleId(item.getId())
.title(volumeInfo.getTitle()) .title(cleanTitle(volumeInfo.getTitle()))
.subtitle(volumeInfo.getSubtitle()) .subtitle(volumeInfo.getSubtitle())
.publisher(volumeInfo.getPublisher()) .publisher(volumeInfo.getPublisher())
.publishedDate(parseDate(volumeInfo.getPublishedDate())) .publishedDate(parseDate(volumeInfo.getPublishedDate()))
.description(volumeInfo.getDescription()) .description(cleanDescription)
.authors(Optional.ofNullable(volumeInfo.getAuthors()).orElse(Set.of())) .authors(cleanAuthors(volumeInfo.getAuthors()))
.categories(Optional.ofNullable(volumeInfo.getCategories()).orElse(Set.of())) .categories(cleanCategories(volumeInfo.getCategories()))
.isbn13(isbns.get("ISBN_13")) .isbn13(isbns.get("ISBN_13"))
.isbn10(isbns.get("ISBN_10")) .isbn10(isbns.get("ISBN_10"))
.pageCount(volumeInfo.getPageCount()) .pageCount(pageCount)
.thumbnailUrl(extractBestCoverImage(volumeInfo.getImageLinks())) .thumbnailUrl(extractBestCoverImage(volumeInfo.getImageLinks()))
.language(volumeInfo.getLanguage()) .language(normalizeLanguage(volumeInfo.getLanguage()))
.externalUrl(externalUrl)
.seriesName(seriesData.name)
.seriesNumber(seriesData.number)
.build(); .build();
} }
private record SeriesData(String name, Float number) {}
private SeriesData extractSeriesInfo(GoogleBooksApiResponse.Item.VolumeInfo volumeInfo) {
if (volumeInfo.getSeriesInfo() != null) {
GoogleBooksApiResponse.Item.SeriesInfo seriesInfo = volumeInfo.getSeriesInfo();
String seriesTitle = seriesInfo.getShortSeriesBookTitle();
Float seriesNumber = null;
if (seriesInfo.getVolumeSeries() != null && !seriesInfo.getVolumeSeries().isEmpty()) {
Integer orderNum = seriesInfo.getVolumeSeries().get(0).getOrderNumber();
if (orderNum != null) {
seriesNumber = orderNum.floatValue();
}
}
if (seriesNumber == null && seriesInfo.getBookDisplayNumber() != null) {
try {
seriesNumber = Float.parseFloat(seriesInfo.getBookDisplayNumber());
} catch (NumberFormatException ignored) {
// Not a valid number, ignore
}
}
if (seriesTitle != null || seriesNumber != null) {
return new SeriesData(seriesTitle, seriesNumber);
}
}
String title = volumeInfo.getTitle();
if (title != null) {
// Try patterns like "Title, Vol. 1", "Title Vol 1", "Title Volume 1"
SeriesData fromTitle = extractSeriesFromTitle(title);
if (fromTitle.number != null) {
return fromTitle;
}
}
return new SeriesData(null, null);
}
/**
* Extract series number from common title patterns.
* Handles formats like:
* - "One Piece, Vol. 100"
* - "Naruto Volume 5"
* - "Batman #123"
* - "Spider-Man 2099 2"
* - "Title (Band 5)"
*/
private SeriesData extractSeriesFromTitle(String title) {
if (title == null || title.isBlank()) {
return new SeriesData(null, null);
}
Pattern volPattern = Pattern.compile("(.+?)(?:,\\s*)?(?:Vol\\.?|Volume)\\s*(\\d+(?:\\.\\d+)?)", Pattern.CASE_INSENSITIVE);
Matcher volMatcher = volPattern.matcher(title);
if (volMatcher.find()) {
String seriesName = volMatcher.group(1).trim();
Float number = parseSeriesNumber(volMatcher.group(2));
return new SeriesData(seriesName, number);
}
Pattern issuePattern = Pattern.compile("(.+?)\\s*#(\\d+(?:\\.\\d+)?)", Pattern.CASE_INSENSITIVE);
Matcher issueMatcher = issuePattern.matcher(title);
if (issueMatcher.find()) {
String seriesName = issueMatcher.group(1).trim();
Float number = parseSeriesNumber(issueMatcher.group(2));
return new SeriesData(seriesName, number);
}
Pattern bandPattern = Pattern.compile("(.+?)(?:,\\s*)?Band\\s*(\\d+(?:\\.\\d+)?)", Pattern.CASE_INSENSITIVE);
Matcher bandMatcher = bandPattern.matcher(title);
if (bandMatcher.find()) {
String seriesName = bandMatcher.group(1).trim();
Float number = parseSeriesNumber(bandMatcher.group(2));
return new SeriesData(seriesName, number);
}
Pattern endNumberPattern = Pattern.compile("^(.+?)\\s+(\\d+)$");
Matcher endNumberMatcher = endNumberPattern.matcher(title);
if (endNumberMatcher.find()) {
String seriesName = endNumberMatcher.group(1).trim();
Float number = parseSeriesNumber(endNumberMatcher.group(2));
if (number != null && number >= 1 && number <= 9999) {
return new SeriesData(seriesName, number);
}
}
return new SeriesData(null, null);
}
private Float parseSeriesNumber(String numberStr) {
if (numberStr == null || numberStr.isBlank()) {
return null;
}
try {
return Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
return null;
}
}
private String cleanTitle(String title) {
if (title == null || title.isBlank()) {
return null;
}
// Remove excessive whitespace
return WHITESPACE_PATTERN.matcher(title.trim()).replaceAll(" ");
}
private Set<String> cleanAuthors(Set<String> authors) {
if (authors == null || authors.isEmpty()) {
return Set.of();
}
return authors.stream()
.filter(Objects::nonNull)
.filter(author -> !author.isBlank())
.map(String::trim)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
private Set<String> cleanCategories(Set<String> categories) {
if (categories == null || categories.isEmpty()) {
return Set.of();
}
return categories.stream()
.filter(Objects::nonNull)
.filter(cat -> !cat.isBlank())
.flatMap(cat -> {
// Split hierarchical categories (e.g., "Fiction / Fantasy / General")
if (cat.contains(" / ")) {
return Arrays.stream(cat.split(" / "))
.map(String::trim)
.filter(s -> !s.equalsIgnoreCase("General"));
}
return Stream.of(cat.trim());
})
.filter(cat -> !cat.isBlank())
.collect(Collectors.toCollection(LinkedHashSet::new));
}
String cleanDescription(String description) {
if (description == null || description.isBlank()) {
return null;
}
String cleaned = Jsoup.parse(description).text();
cleaned = WHITESPACE_PATTERN.matcher(cleaned.trim()).replaceAll(" ");
return cleaned.isEmpty() ? null : cleaned;
}
private String normalizeLanguage(String language) {
if (language == null || language.isBlank()) {
return null;
}
// Google uses ISO 639-1 codes, just ensure lowercase
return language.toLowerCase().trim();
}
private String getExternalUrl(GoogleBooksApiResponse.Item.VolumeInfo volumeInfo) {
// Prefer canonical volume link, then info link
if (volumeInfo.getCanonicalVolumeLink() != null && !volumeInfo.getCanonicalVolumeLink().isBlank()) {
return volumeInfo.getCanonicalVolumeLink();
}
if (volumeInfo.getInfoLink() != null && !volumeInfo.getInfoLink().isBlank()) {
return volumeInfo.getInfoLink();
}
return null;
}
private String extractBestCoverImage(GoogleBooksApiResponse.Item.ImageLinks links) { private String extractBestCoverImage(GoogleBooksApiResponse.Item.ImageLinks links) {
if (links == null) { if (links == null) {
return null; return null;
} }
return Stream.of(
// Priority order: extraLarge > large > medium > small > thumbnail > smallThumbnail
String imageUrl = Stream.of(
links.getExtraLarge(), links.getExtraLarge(),
links.getLarge(), links.getLarge(),
links.getMedium(), links.getMedium(),
@@ -145,8 +410,23 @@ public class GoogleParser implements BookParser {
links.getThumbnail(), links.getThumbnail(),
links.getSmallThumbnail()) links.getSmallThumbnail())
.filter(Objects::nonNull) .filter(Objects::nonNull)
.filter(url -> !url.isBlank())
.findFirst() .findFirst()
.orElse(null); .orElse(null);
if (imageUrl == null) {
return null;
}
imageUrl = imageUrl.replace("http://", "https://");
if (imageUrl.contains("zoom=")) {
imageUrl = imageUrl.replaceAll("zoom=\\d+", "zoom=0");
}
imageUrl = imageUrl.replaceAll("&?edge=curl", "");
return imageUrl;
} }
private Map<String, String> extractISBNs(List<GoogleBooksApiResponse.Item.IndustryIdentifier> identifiers) { private Map<String, String> extractISBNs(List<GoogleBooksApiResponse.Item.IndustryIdentifier> identifiers) {
@@ -200,16 +480,51 @@ public class GoogleParser implements BookParser {
return truncated.toString(); return truncated.toString();
} }
/**
* Parse date string from Google Books API.
* Handles various formats:
* - "2021-05-15" (full date)
* - "2021-05" (year-month)
* - "2021" (year only)
*/
private LocalDate parseDate(String input) { private LocalDate parseDate(String input) {
if (input == null || input.isEmpty()) { if (input == null || input.isBlank()) {
return null; return null;
} }
input = input.trim();
try { try {
if (FOUR_DIGIT_YEAR_PATTERN.matcher(input).matches()) { // Try full date format first (YYYY-MM-DD)
return LocalDate.of(Integer.parseInt(input), 1, 1); if (input.length() == 10 && input.matches("\\d{4}-\\d{2}-\\d{2}")) {
return LocalDate.parse(input, DATE_FORMATTER);
} }
return LocalDate.parse(input, DATE_FORMATTER);
} catch (Exception e) { // Try year-month format (YYYY-MM)
Matcher yearMonthMatcher = YEAR_MONTH_PATTERN.matcher(input);
if (yearMonthMatcher.matches()) {
int year = Integer.parseInt(yearMonthMatcher.group(1));
int month = Integer.parseInt(yearMonthMatcher.group(2));
// Validate month
if (month >= 1 && month <= 12) {
return LocalDate.of(year, month, 1);
}
}
// Try year only format (YYYY)
Matcher yearMatcher = FOUR_DIGIT_YEAR_PATTERN.matcher(input);
if (yearMatcher.matches()) {
int year = Integer.parseInt(yearMatcher.group(1));
// Basic year validation
if (year >= 1000 && year <= 9999) {
return LocalDate.of(year, 1, 1);
}
}
// Try parsing as ISO date as fallback
return LocalDate.parse(input);
} catch (DateTimeParseException | NumberFormatException e) {
log.debug("Could not parse date '{}': {}", input, e.getMessage());
return null; return null;
} }
} }
@@ -240,4 +555,42 @@ public class GoogleParser implements BookParser {
} }
lastRequestTime.set(System.currentTimeMillis()); lastRequestTime.set(System.currentTimeMillis());
} }
/**
* Sort results by metadata completeness.
* Items with more populated fields come first.
*/
private List<BookMetadata> sortByCompleteness(List<BookMetadata> results) {
if (results == null || results.isEmpty()) {
return List.of();
}
return results.stream()
.sorted((a, b) -> Integer.compare(
countPopulatedFields(b),
countPopulatedFields(a)))
.collect(Collectors.toList());
}
private int countPopulatedFields(BookMetadata metadata) {
int count = 0;
if (metadata.getTitle() != null && !metadata.getTitle().isBlank()) count++;
if (metadata.getSubtitle() != null && !metadata.getSubtitle().isBlank()) count++;
if (metadata.getAuthors() != null && !metadata.getAuthors().isEmpty()) count++;
if (metadata.getPublisher() != null && !metadata.getPublisher().isBlank()) count++;
if (metadata.getPublishedDate() != null) count++;
if (metadata.getDescription() != null && !metadata.getDescription().isBlank()) count++;
if (metadata.getIsbn13() != null && !metadata.getIsbn13().isBlank()) count++;
if (metadata.getIsbn10() != null && !metadata.getIsbn10().isBlank()) count++;
if (metadata.getPageCount() != null && metadata.getPageCount() > 0) count++;
if (metadata.getLanguage() != null && !metadata.getLanguage().isBlank()) count++;
if (metadata.getCategories() != null && !metadata.getCategories().isEmpty()) count++;
if (metadata.getThumbnailUrl() != null && !metadata.getThumbnailUrl().isBlank()) count++;
if (metadata.getSeriesName() != null && !metadata.getSeriesName().isBlank()) count++;
if (metadata.getSeriesNumber() != null) count++;
if (metadata.getGoogleId() != null && !metadata.getGoogleId().isBlank()) count++;
return count;
}
} }
@@ -0,0 +1,69 @@
package com.adityachandel.booklore.service.metadata.parser;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class GoogleParserTest {
@Mock
private AppSettingService appSettingService;
@Mock
private ObjectMapper objectMapper;
private GoogleParser googleParser;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
googleParser = new GoogleParser(objectMapper, appSettingService);
}
@Test
void testCleanDescription_null() {
assertNull(googleParser.cleanDescription(null));
}
@Test
void testCleanDescription_empty() {
assertNull(googleParser.cleanDescription(""));
assertNull(googleParser.cleanDescription(" "));
}
@Test
void testCleanDescription_withHtmlTags() {
String input = "This is <i>italic</i> and <b>bold</b>. <br> New line.";
String expected = "This is italic and bold. New line.";
assertEquals(expected, googleParser.cleanDescription(input));
}
@Test
void testCleanDescription_withEntities() {
String input = "Tom &amp; Jerry &lt; Disney &gt; Pixar &quot;Toy Story&quot; &#39;test&#39;";
String expected = "Tom & Jerry < Disney > Pixar \"Toy Story\" 'test'";
assertEquals(expected, googleParser.cleanDescription(input));
}
@Test
void testCleanDescription_withNestedTagsAndWhitespace() {
String input = """
<div> <p>Some text </p>
<span>More text</span> </div>""";
String expected = "Some text More text";
assertEquals(expected, googleParser.cleanDescription(input));
}
@Test
void testCleanDescription_withUnclosedTags() {
String input = "This is <i>italic and <b>bold";
String expected = "This is italic and bold";
assertEquals(expected, googleParser.cleanDescription(input));
}
}