feat(hardcover): get Hardcover metadata from a specific edition when ISBN is provided (#2678)
* fix: clean ISBN should allow ISBNs to have an X at the end * hardcover mood filter overload for just list of tags * When ISBN is given, fetch the book directly by the edition with that ISBN, and provide metadata from that edition * chore: improved formatting * PR improvements * replaced CachedTag with GraphQL specific class * moved hardcover cached tag to shared model
This commit is contained in:
+127
-8
@@ -42,9 +42,9 @@ public class HardcoverParser implements BookParser {
|
||||
boolean searchByIsbn = isbnCleaned != null && !isbnCleaned.isBlank();
|
||||
|
||||
if (searchByIsbn) {
|
||||
log.info("Hardcover: Fetching metadata using ISBN {}", fetchMetadataRequest.getIsbn());
|
||||
List<GraphQLResponse.Hit> hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getIsbn());
|
||||
return processHits(hits, fetchMetadataRequest, true);
|
||||
log.info("Hardcover: Fetching metadata using ISBN {}", isbnCleaned);
|
||||
List<GraphQLResponse.BookWithEditions> hits = hardcoverBookSearchService.searchBookByIsbn(isbnCleaned);
|
||||
return processBooksWithEditions(hits);
|
||||
}
|
||||
|
||||
String title = fetchMetadataRequest.getTitle();
|
||||
@@ -79,6 +79,27 @@ public class HardcoverParser implements BookParser {
|
||||
return results;
|
||||
}
|
||||
|
||||
private List<BookMetadata> processBooksWithEditions(List<GraphQLResponse.BookWithEditions> books) {
|
||||
if (books == null || books.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<BookMetadata> results = new ArrayList<>();
|
||||
for (GraphQLResponse.BookWithEditions book : books) {
|
||||
if (book.getEditions() == null || book.getEditions().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
for (GraphQLResponse.Edition edition : book.getEditions()) {
|
||||
log.debug("Processing edition '{}' with id '{}' of book '{}'", edition.getTitle(), edition.getId(), book.getTitle());
|
||||
BookMetadata metadata = mapEditionToMetadata(edition, book);
|
||||
if (metadata != null) {
|
||||
results.add(metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private List<BookMetadata> processHits(List<GraphQLResponse.Hit> hits, FetchMetadataRequest request, boolean searchByIsbn) {
|
||||
if (hits == null || hits.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
@@ -110,7 +131,7 @@ public class HardcoverParser implements BookParser {
|
||||
return results;
|
||||
}
|
||||
|
||||
private boolean filterByAuthor(GraphQLResponse.Document doc, String searchAuthor,
|
||||
private boolean filterByAuthor(GraphQLResponse.Document doc, String searchAuthor,
|
||||
boolean searchByIsbn, FuzzyScore fuzzyScore) {
|
||||
// Skip author filtering for ISBN searches or when no author provided
|
||||
if (searchByIsbn || searchAuthor.isBlank()) {
|
||||
@@ -131,7 +152,7 @@ public class HardcoverParser implements BookParser {
|
||||
for (String query : searchAuthorTokens) {
|
||||
int score = fuzzyScore.fuzzyScore(actual, query);
|
||||
int maxScore = Math.max(
|
||||
fuzzyScore.fuzzyScore(query, query),
|
||||
fuzzyScore.fuzzyScore(query, query),
|
||||
fuzzyScore.fuzzyScore(actual, actual)
|
||||
);
|
||||
double similarity = maxScore > 0 ? (double) score / maxScore : 0;
|
||||
@@ -183,6 +204,104 @@ public class HardcoverParser implements BookParser {
|
||||
|
||||
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
|
||||
metadata.setProvider(MetadataProvider.Hardcover);
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private BookMetadata mapEditionToMetadata(GraphQLResponse.Edition edition, GraphQLResponse.BookWithEditions book) {
|
||||
BookMetadata metadata = new BookMetadata();
|
||||
metadata.setHardcoverId(book.getSlug());
|
||||
|
||||
Integer bookId = book.getId();
|
||||
if (bookId != null) {
|
||||
metadata.setHardcoverBookId(bookId.toString());
|
||||
}
|
||||
|
||||
metadata.setTitle(edition.getTitle());
|
||||
metadata.setSubtitle(edition.getSubtitle());
|
||||
metadata.setDescription(book.getDescription());
|
||||
|
||||
if (edition.getCachedContributors() != null) {
|
||||
metadata.setAuthors(edition.getCachedContributors().stream()
|
||||
.map(GraphQLResponse.Contributor::getAuthor)
|
||||
.filter(Objects::nonNull)
|
||||
.map(GraphQLResponse.Author::getName)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
if (book.getFeaturedBookSeries() != null && book.getFeaturedBookSeries().getSeries() != null) {
|
||||
metadata.setSeriesName(book.getFeaturedBookSeries().getSeries().getName());
|
||||
metadata.setSeriesTotal(book.getFeaturedBookSeries().getSeries().getBooksCount());
|
||||
|
||||
if (book.getFeaturedBookSeries().getPosition() != null) {
|
||||
try {
|
||||
metadata.setSeriesNumber(Float.parseFloat(String.valueOf(book.getFeaturedBookSeries().getPosition())));
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (book.getRating() != null) {
|
||||
metadata.setHardcoverRating(
|
||||
BigDecimal.valueOf(book.getRating()).setScale(2, RoundingMode.HALF_UP).doubleValue()
|
||||
);
|
||||
}
|
||||
metadata.setHardcoverReviewCount(book.getRatingsCount());
|
||||
metadata.setPageCount(edition.getPages());
|
||||
|
||||
if (edition.getReleaseDate() != null) {
|
||||
try {
|
||||
metadata.setPublishedDate(LocalDate.parse(edition.getReleaseDate()));
|
||||
} catch (Exception e) {
|
||||
log.debug("Could not parse release date: {}", edition.getReleaseDate());
|
||||
}
|
||||
}
|
||||
|
||||
// Set the language from the edition
|
||||
if (edition.getLanguage() != null && edition.getLanguage().getCode2() != null) {
|
||||
metadata.setLanguage(edition.getLanguage().getCode2());
|
||||
}
|
||||
|
||||
// Set the Publisher from the edition
|
||||
if (edition.getPublisher() != null && edition.getPublisher().getName() != null) {
|
||||
metadata.setPublisher(edition.getPublisher().getName());
|
||||
}
|
||||
|
||||
GraphQLResponse.CachedTags cachedTags = book.getCachedTags();
|
||||
|
||||
if (cachedTags != null && cachedTags.getMood() != null && !cachedTags.getMood().isEmpty()) {
|
||||
Set<String> basicFilteredMoods = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags.getMood());
|
||||
metadata.setMoods(basicFilteredMoods.stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
}
|
||||
|
||||
if (cachedTags != null && cachedTags.getGenre() != null && !cachedTags.getGenre().isEmpty()) {
|
||||
Set<String> filteredGenres = HardcoverMoodFilter.filterGenresWithCounts(cachedTags.getGenre());
|
||||
metadata.setCategories(filteredGenres.stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
if (cachedTags != null && cachedTags.getTag() != null && !cachedTags.getTag().isEmpty()) {
|
||||
Set<String> filteredTags = HardcoverMoodFilter.filterTagsWithCounts(cachedTags.getTag());
|
||||
metadata.setTags(filteredTags.stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
metadata.setIsbn10(edition.getIsbn10());
|
||||
metadata.setIsbn13(edition.getIsbn13());
|
||||
|
||||
// If only one ISBN is provided, calculate the other
|
||||
if (metadata.getIsbn10() != null && metadata.getIsbn13() == null) {
|
||||
metadata.setIsbn13(BookUtils.isbn10To13(edition.getIsbn10()));
|
||||
} else if (metadata.getIsbn13() != null && metadata.getIsbn10() == null) {
|
||||
metadata.setIsbn10(BookUtils.isbn13to10(edition.getIsbn13()));
|
||||
}
|
||||
|
||||
metadata.setThumbnailUrl(edition.getImage() != null ? edition.getImage().getUrl() : null);
|
||||
metadata.setProvider(MetadataProvider.Hardcover);
|
||||
|
||||
return metadata;
|
||||
}
|
||||
@@ -282,9 +401,9 @@ public class HardcoverParser implements BookParser {
|
||||
if (StringUtils.isBlank(inputIsbn)) {
|
||||
// If we didn't search by ISBN, use first ISBN from results
|
||||
matchingIsbn = doc.getIsbns().stream()
|
||||
.filter(isbn -> isbn.length() == 10 || isbn.length() == 13)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
.filter(isbn -> isbn.length() == 10 || isbn.length() == 13)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
} else if (doc.getIsbns().contains(inputIsbn)) {
|
||||
// If we searched by ISBN and it matches a result perfectly, use that
|
||||
matchingIsbn = inputIsbn;
|
||||
|
||||
@@ -4,10 +4,15 @@ import java.util.regex.Pattern;
|
||||
|
||||
public class ParserUtils {
|
||||
|
||||
private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]");
|
||||
private static final Pattern NON_ISBN_CHAR_PATTERN = Pattern.compile("[^0-9Xx]");
|
||||
|
||||
public static String cleanIsbn(String isbn) {
|
||||
if (isbn == null) return null;
|
||||
return NON_DIGIT_PATTERN.matcher(isbn).replaceAll("");
|
||||
String cleaned = NON_ISBN_CHAR_PATTERN.matcher(isbn).replaceAll("");
|
||||
// Normalize 'x' to 'X' for ISBN-10 check digit
|
||||
if (cleaned.length() == 10 && cleaned.endsWith("x")) {
|
||||
cleaned = cleaned.substring(0, 9) + "X";
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
}
|
||||
|
||||
+133
@@ -23,6 +23,7 @@ public class GraphQLResponse {
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Data {
|
||||
private Search search;
|
||||
private List<BookWithEditions> books;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@@ -160,6 +161,82 @@ public class GraphQLResponse {
|
||||
private Integer usersReadCount;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class BookWithEditions {
|
||||
private Integer id;
|
||||
private String slug;
|
||||
private String title;
|
||||
private String subtitle;
|
||||
private String description;
|
||||
|
||||
@JsonProperty("cached_contributors")
|
||||
private List<Contributor> cachedContributors;
|
||||
|
||||
@JsonProperty("featured_book_series")
|
||||
private FeaturedSeries featuredBookSeries;
|
||||
|
||||
private Double rating;
|
||||
|
||||
@JsonProperty("ratings_count")
|
||||
private Integer ratingsCount;
|
||||
|
||||
@JsonProperty("reviews_count")
|
||||
private Integer reviewsCount;
|
||||
|
||||
private Integer pages;
|
||||
|
||||
@JsonProperty("release_date")
|
||||
private String releaseDate;
|
||||
|
||||
@JsonProperty("release_year")
|
||||
private Integer releaseYear;
|
||||
|
||||
private Image image;
|
||||
|
||||
@JsonProperty("cached_tags")
|
||||
private CachedTags cachedTags;
|
||||
|
||||
private List<Edition> editions;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Edition {
|
||||
private Integer id;
|
||||
private String title;
|
||||
private String subtitle;
|
||||
|
||||
@JsonProperty("cached_contributors")
|
||||
private List<Contributor> cachedContributors;
|
||||
|
||||
private Integer pages;
|
||||
|
||||
@JsonProperty("release_date")
|
||||
private String releaseDate;
|
||||
|
||||
@JsonProperty("release_year")
|
||||
private Integer releaseYear;
|
||||
|
||||
private Image image;
|
||||
|
||||
private Publisher publisher;
|
||||
|
||||
@JsonProperty("isbn_10")
|
||||
private String isbn10;
|
||||
|
||||
@JsonProperty("isbn_13")
|
||||
private String isbn13;
|
||||
|
||||
private Language language;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@@ -189,4 +266,60 @@ public class GraphQLResponse {
|
||||
@JsonProperty("books_count")
|
||||
private Integer booksCount;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Contributor {
|
||||
private Author author;
|
||||
private String contribution;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Author {
|
||||
private Integer id;
|
||||
private String slug;
|
||||
private String name;
|
||||
private Image image;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CachedTags {
|
||||
@JsonProperty("Genre")
|
||||
private List<HardcoverCachedTag> genre;
|
||||
|
||||
@JsonProperty("Mood")
|
||||
private List<HardcoverCachedTag> mood;
|
||||
|
||||
@JsonProperty("Tag")
|
||||
private List<HardcoverCachedTag> tag;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Publisher {
|
||||
private String name;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Language {
|
||||
private String code2;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-23
@@ -18,27 +18,5 @@ public class HardcoverBookDetails {
|
||||
private String title;
|
||||
|
||||
@JsonProperty("cached_tags")
|
||||
private Map<String, List<CachedTag>> cachedTags;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CachedTag {
|
||||
private String tag;
|
||||
|
||||
@JsonProperty("tagSlug")
|
||||
private String tagSlug;
|
||||
|
||||
private String category;
|
||||
|
||||
@JsonProperty("categorySlug")
|
||||
private String categorySlug;
|
||||
|
||||
@JsonProperty("spoilerRatio")
|
||||
private Double spoilerRatio;
|
||||
|
||||
private Integer count;
|
||||
}
|
||||
private Map<String, List<HardcoverCachedTag>> cachedTags;
|
||||
}
|
||||
|
||||
+70
-1
@@ -35,6 +35,75 @@ public class HardcoverBookSearchService {
|
||||
.build();
|
||||
}
|
||||
|
||||
public List<GraphQLResponse.BookWithEditions> searchBookByIsbn(String isbn) {
|
||||
String apiToken = getApiToken();
|
||||
if (apiToken == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
GraphQLRequest body = new GraphQLRequest();
|
||||
body.setQuery("""
|
||||
query BookSearchByIsbn($isbn: String!) {
|
||||
books(
|
||||
where: {editions: {_or: [{isbn_13: {_eq: $isbn}}, {isbn_10: {_eq: $isbn}}]}}
|
||||
) {
|
||||
id
|
||||
slug
|
||||
title
|
||||
subtitle
|
||||
description
|
||||
cached_contributors
|
||||
featured_book_series {
|
||||
series {
|
||||
name
|
||||
books_count
|
||||
}
|
||||
position
|
||||
}
|
||||
rating
|
||||
ratings_count
|
||||
reviews_count
|
||||
pages
|
||||
release_date
|
||||
release_year
|
||||
image {
|
||||
url
|
||||
}
|
||||
cached_tags
|
||||
editions(where: {_or: [{isbn_13: {_eq: $isbn}}, {isbn_10: {_eq: $isbn}}]}) {
|
||||
id
|
||||
title
|
||||
subtitle
|
||||
cached_contributors
|
||||
pages
|
||||
release_date
|
||||
release_year
|
||||
image {
|
||||
url
|
||||
}
|
||||
publisher {
|
||||
name
|
||||
}
|
||||
isbn_10
|
||||
isbn_13
|
||||
language {
|
||||
code2
|
||||
}
|
||||
}
|
||||
}
|
||||
}""");
|
||||
body.setVariables(java.util.Map.of("isbn", isbn));
|
||||
|
||||
GraphQLResponse response = executeRequest(body, GraphQLResponse.class, apiToken);
|
||||
if (response == null || response.getData() == null ||
|
||||
response.getData().getBooks() == null ||
|
||||
response.getData().getBooks().isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
return response.getData().getBooks();
|
||||
}
|
||||
|
||||
public List<GraphQLResponse.Hit> searchBooks(String query) {
|
||||
return searchBooks(query, DEFAULT_PER_PAGE);
|
||||
}
|
||||
@@ -46,7 +115,7 @@ public class HardcoverBookSearchService {
|
||||
}
|
||||
|
||||
int sanitizedPerPage = Math.min(Math.max(perPage, 1), 100);
|
||||
|
||||
|
||||
GraphQLRequest body = new GraphQLRequest();
|
||||
body.setQuery("query BookSearch($q: String!, $limit: Int!) { search(query: $q, query_type: \"Book\", per_page: $limit, page: 1) { results } }");
|
||||
body.setVariables(java.util.Map.of("q", query, "limit", sanitizedPerPage));
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package org.booklore.service.metadata.parser.hardcover;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.*;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class HardcoverCachedTag {
|
||||
private String tag;
|
||||
|
||||
@JsonProperty("tagSlug")
|
||||
private String tagSlug;
|
||||
|
||||
private String category;
|
||||
|
||||
@JsonProperty("categorySlug")
|
||||
private String categorySlug;
|
||||
|
||||
@JsonProperty("spoilerRatio")
|
||||
private Double spoilerRatio;
|
||||
|
||||
private Integer count;
|
||||
}
|
||||
|
||||
+23
-14
@@ -38,12 +38,15 @@ public class HardcoverMoodFilter {
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
public static Set<String> filterMoodsWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
|
||||
public static Set<String> filterMoodsWithCounts(Map<String, List<HardcoverCachedTag>> cachedTags) {
|
||||
if (cachedTags == null || cachedTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> moodTags = cachedTags.get("Mood");
|
||||
return filterMoodsWithCounts(cachedTags.get("Mood"));
|
||||
}
|
||||
|
||||
public static Set<String> filterMoodsWithCounts(List<HardcoverCachedTag> moodTags) {
|
||||
if (moodTags == null || moodTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
@@ -51,7 +54,7 @@ public class HardcoverMoodFilter {
|
||||
// Find the maximum vote count
|
||||
int maxCount = moodTags.stream()
|
||||
.filter(tag -> tag.getCount() != null)
|
||||
.mapToInt(HardcoverBookDetails.CachedTag::getCount)
|
||||
.mapToInt(HardcoverCachedTag::getCount)
|
||||
.max()
|
||||
.orElse(0);
|
||||
|
||||
@@ -62,10 +65,10 @@ public class HardcoverMoodFilter {
|
||||
|
||||
int minCountThreshold = Math.max(MIN_VOTE_COUNT, (int) (maxCount * MIN_VOTE_RATIO));
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> filteredMoods = moodTags.stream()
|
||||
List<HardcoverCachedTag> filteredMoods = moodTags.stream()
|
||||
.filter(tag -> tag.getCount() != null && tag.getCount() >= minCountThreshold)
|
||||
.filter(tag -> tag.getTag() != null)
|
||||
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
|
||||
.sorted(Comparator.comparingInt(HardcoverCachedTag::getCount).reversed())
|
||||
.limit(MAX_MOODS)
|
||||
.toList();
|
||||
|
||||
@@ -73,16 +76,19 @@ public class HardcoverMoodFilter {
|
||||
moodTags.size(), filteredMoods.size(), maxCount, minCountThreshold);
|
||||
|
||||
return filteredMoods.stream()
|
||||
.map(HardcoverBookDetails.CachedTag::getTag)
|
||||
.map(HardcoverCachedTag::getTag)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
public static Set<String> filterGenresWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
|
||||
public static Set<String> filterGenresWithCounts(Map<String, List<HardcoverCachedTag>> cachedTags) {
|
||||
if (cachedTags == null || cachedTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> genreTags = cachedTags.get("Genre");
|
||||
return filterGenresWithCounts(cachedTags.get("Genre"));
|
||||
}
|
||||
|
||||
public static Set<String> filterGenresWithCounts(List<HardcoverCachedTag> genreTags) {
|
||||
if (genreTags == null || genreTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
@@ -91,18 +97,21 @@ public class HardcoverMoodFilter {
|
||||
return genreTags.stream()
|
||||
.filter(tag -> tag.getCount() != null && tag.getCount() >= 1)
|
||||
.filter(tag -> tag.getTag() != null)
|
||||
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
|
||||
.sorted(Comparator.comparingInt(HardcoverCachedTag::getCount).reversed())
|
||||
.limit(10) // Allow more genres
|
||||
.map(HardcoverBookDetails.CachedTag::getTag)
|
||||
.map(HardcoverCachedTag::getTag)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
public static Set<String> filterTagsWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
|
||||
public static Set<String> filterTagsWithCounts(Map<String, List<HardcoverCachedTag>> cachedTags) {
|
||||
if (cachedTags == null || cachedTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> tagList = cachedTags.get("Tag");
|
||||
return filterTagsWithCounts(cachedTags.get("Tag"));
|
||||
}
|
||||
|
||||
public static Set<String> filterTagsWithCounts(List<HardcoverCachedTag> tagList) {
|
||||
if (tagList == null || tagList.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
@@ -111,9 +120,9 @@ public class HardcoverMoodFilter {
|
||||
return tagList.stream()
|
||||
.filter(tag -> tag.getCount() != null && tag.getCount() >= 2)
|
||||
.filter(tag -> tag.getTag() != null)
|
||||
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
|
||||
.sorted(Comparator.comparingInt(HardcoverCachedTag::getCount).reversed())
|
||||
.limit(10)
|
||||
.map(HardcoverBookDetails.CachedTag::getTag)
|
||||
.map(HardcoverCachedTag::getTag)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
|
||||
+313
-37
@@ -7,6 +7,7 @@ import org.booklore.model.enums.MetadataProvider;
|
||||
import org.booklore.service.metadata.parser.hardcover.GraphQLResponse;
|
||||
import org.booklore.service.metadata.parser.hardcover.HardcoverBookDetails;
|
||||
import org.booklore.service.metadata.parser.hardcover.HardcoverBookSearchService;
|
||||
import org.booklore.service.metadata.parser.hardcover.HardcoverCachedTag;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
@@ -23,7 +24,7 @@ import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Unit tests for HardcoverParser.
|
||||
*
|
||||
* <p>
|
||||
* These tests verify:
|
||||
* - Combined title+author search strategy for better reliability
|
||||
* - ISBN search behavior
|
||||
@@ -79,7 +80,7 @@ class HardcoverParserTest {
|
||||
|
||||
when(hardcoverBookSearchService.searchBooks("Some Book Unknown Author"))
|
||||
.thenReturn(Collections.emptyList());
|
||||
|
||||
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("Some Book", "Different Author");
|
||||
when(hardcoverBookSearchService.searchBooks("Some Book"))
|
||||
.thenReturn(List.of(hit));
|
||||
@@ -126,17 +127,159 @@ class HardcoverParserTest {
|
||||
.isbn("978-0316769488")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("The Catcher in the Rye", "J.D. Salinger");
|
||||
hit.getDocument().setIsbns(List.of("9780316769488", "0316769487"));
|
||||
when(hardcoverBookSearchService.searchBooks("978-0316769488"))
|
||||
GraphQLResponse.BookWithEditions hit = createBookWithEditions();
|
||||
hit.getEditions().get(0).setIsbn13("9780316769488");
|
||||
hit.getEditions().get(0).setIsbn10("0316769487");
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("9780316769488"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
verify(hardcoverBookSearchService).searchBooks("978-0316769488");
|
||||
verify(hardcoverBookSearchService).searchBookByIsbn("9780316769488");
|
||||
verify(hardcoverBookSearchService, never()).searchBooks(contains("title"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return empty list when ISBN search returns book with no editions")
|
||||
void fetchMetadata_isbnSearchNoEditions_returnsEmptyList() {
|
||||
Book book = Book.builder().title("Any Title").build();
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Any Title")
|
||||
.isbn("9780316769488")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.BookWithEditions bookWithNoEditions = new GraphQLResponse.BookWithEditions();
|
||||
bookWithNoEditions.setId(12345);
|
||||
bookWithNoEditions.setTitle("Test Book");
|
||||
bookWithNoEditions.setEditions(Collections.emptyList());
|
||||
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("9780316769488"))
|
||||
.thenReturn(List.of(bookWithNoEditions));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
assertThat(results).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return empty list when ISBN search returns book with null editions")
|
||||
void fetchMetadata_isbnSearchNullEditions_returnsEmptyList() {
|
||||
Book book = Book.builder().title("Any Title").build();
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Any Title")
|
||||
.isbn("9780316769488")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.BookWithEditions bookWithNullEditions = new GraphQLResponse.BookWithEditions();
|
||||
bookWithNullEditions.setId(12345);
|
||||
bookWithNullEditions.setTitle("Test Book");
|
||||
bookWithNullEditions.setEditions(null);
|
||||
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("9780316769488"))
|
||||
.thenReturn(List.of(bookWithNullEditions));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
assertThat(results).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return empty list when ISBN search returns null")
|
||||
void fetchMetadata_isbnSearchReturnsNull_returnsEmptyList() {
|
||||
Book book = Book.builder().title("Any Title").build();
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Any Title")
|
||||
.isbn("9780316769488")
|
||||
.build();
|
||||
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("9780316769488"))
|
||||
.thenReturn(null);
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
assertThat(results).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return all editions when ISBN search returns book with multiple editions")
|
||||
void fetchMetadata_isbnSearchMultipleEditions_returnsAllEditions() {
|
||||
Book book = Book.builder().title("Any Title").build();
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Any Title")
|
||||
.isbn("9780316769488")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.BookWithEditions bookWithEditions = createBookWithEditions();
|
||||
|
||||
// Add a second edition
|
||||
GraphQLResponse.Edition secondEdition = new GraphQLResponse.Edition();
|
||||
secondEdition.setId(2);
|
||||
secondEdition.setTitle("Test Book - Paperback Edition");
|
||||
secondEdition.setIsbn13("9780316769489");
|
||||
secondEdition.setIsbn10("0316769489");
|
||||
secondEdition.setPages(400);
|
||||
|
||||
GraphQLResponse.Author author = new GraphQLResponse.Author();
|
||||
author.setName("Test Author");
|
||||
GraphQLResponse.Contributor contributor = new GraphQLResponse.Contributor();
|
||||
contributor.setAuthor(author);
|
||||
secondEdition.setCachedContributors(List.of(contributor));
|
||||
|
||||
bookWithEditions.setEditions(List.of(bookWithEditions.getEditions().get(0), secondEdition));
|
||||
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("9780316769488"))
|
||||
.thenReturn(List.of(bookWithEditions));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
assertThat(results).hasSize(2);
|
||||
assertThat(results.get(0).getTitle()).isEqualTo("Test Book - Hardcover Edition");
|
||||
assertThat(results.get(1).getTitle()).isEqualTo("Test Book - Paperback Edition");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle edition with null optional fields gracefully")
|
||||
void fetchMetadata_editionWithNullOptionalFields_handlesGracefully() {
|
||||
Book book = Book.builder().title("Any Title").build();
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Any Title")
|
||||
.isbn("9780316769488")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.BookWithEditions bookWithEditions = new GraphQLResponse.BookWithEditions();
|
||||
bookWithEditions.setId(12345);
|
||||
bookWithEditions.setSlug("test-book");
|
||||
bookWithEditions.setTitle("Test Book");
|
||||
bookWithEditions.setDescription("A description");
|
||||
bookWithEditions.setRating(4.0);
|
||||
bookWithEditions.setRatingsCount(50);
|
||||
|
||||
// Edition with null language, publisher, and cachedContributors
|
||||
GraphQLResponse.Edition edition = new GraphQLResponse.Edition();
|
||||
edition.setId(1);
|
||||
edition.setTitle("Test Book Edition");
|
||||
edition.setIsbn13("9780316769488");
|
||||
edition.setLanguage(null);
|
||||
edition.setPublisher(null);
|
||||
edition.setCachedContributors(null);
|
||||
edition.setImage(null);
|
||||
|
||||
bookWithEditions.setEditions(List.of(edition));
|
||||
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("9780316769488"))
|
||||
.thenReturn(List.of(bookWithEditions));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
assertThat(results).hasSize(1);
|
||||
BookMetadata metadata = results.get(0);
|
||||
assertThat(metadata.getTitle()).isEqualTo("Test Book Edition");
|
||||
assertThat(metadata.getLanguage()).isNull();
|
||||
assertThat(metadata.getPublisher()).isNull();
|
||||
assertThat(metadata.getAuthors()).isNullOrEmpty();
|
||||
assertThat(metadata.getThumbnailUrl()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should search title-only when no author provided")
|
||||
void fetchMetadata_noAuthor_searchesTitleOnly() {
|
||||
@@ -210,12 +353,16 @@ class HardcoverParserTest {
|
||||
.author("Wrong Author") // Should be ignored
|
||||
.build();
|
||||
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("Any Book", "Correct Author");
|
||||
when(hardcoverBookSearchService.searchBooks("123456789X"))
|
||||
.thenReturn(List.of(hit));
|
||||
GraphQLResponse.BookWithEditions bookWithEditions = createBookWithEditions();
|
||||
// The book has "Test Author" but request has "Wrong Author" - should still return results
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("123456789X"))
|
||||
.thenReturn(List.of(bookWithEditions));
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
assertThat(results).hasSize(1); // Should not filter out
|
||||
verify(hardcoverBookSearchService).searchBookByIsbn("123456789X");
|
||||
|
||||
assertThat(results.get(0).getAuthors()).contains("Test Author");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,18 +376,17 @@ class HardcoverParserTest {
|
||||
Book book = Book.builder().title("Test").build();
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Test")
|
||||
.isbn("9781234567897")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.Hit hit = createFullyPopulatedHit();
|
||||
when(hardcoverBookSearchService.searchBooks("9781234567897"))
|
||||
when(hardcoverBookSearchService.searchBooks("Test"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
assertThat(results).hasSize(1);
|
||||
BookMetadata metadata = results.get(0);
|
||||
|
||||
|
||||
assertThat(metadata.getTitle()).isEqualTo("Test Book");
|
||||
assertThat(metadata.getSubtitle()).isEqualTo("A Subtitle");
|
||||
assertThat(metadata.getDescription()).isEqualTo("A description");
|
||||
@@ -253,8 +399,48 @@ class HardcoverParserTest {
|
||||
assertThat(metadata.getSeriesName()).isEqualTo("Test Series");
|
||||
assertThat(metadata.getSeriesNumber()).isEqualTo(2.0f);
|
||||
assertThat(metadata.getSeriesTotal()).isEqualTo(5);
|
||||
assertThat(metadata.getIsbn13()).isEqualTo("9781111111113");
|
||||
assertThat(metadata.getIsbn10()).isEqualTo("1111111111");
|
||||
assertThat(metadata.getProvider()).isEqualTo(MetadataProvider.Hardcover);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should map all basic metadata fields correctly when searching with ISBN")
|
||||
void fetchMetadata_fullDocument_mapsAllFields_fromISBN() {
|
||||
Book book = Book.builder().title("Test").build();
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Test")
|
||||
.isbn("9781234567897")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.BookWithEditions hit = createBookWithEditions();
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("9781234567897"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
assertThat(results).hasSize(1);
|
||||
BookMetadata metadata = results.get(0);
|
||||
|
||||
assertThat(metadata.getTitle()).isEqualTo("Test Book - Hardcover Edition");
|
||||
assertThat(metadata.getSubtitle()).isEqualTo("A Subtitle");
|
||||
assertThat(metadata.getDescription()).isEqualTo("A description");
|
||||
assertThat(metadata.getHardcoverId()).isEqualTo("test-book-slug");
|
||||
assertThat(metadata.getHardcoverBookId()).isEqualTo("12345");
|
||||
assertThat(metadata.getHardcoverRating()).isEqualTo(4.25);
|
||||
assertThat(metadata.getHardcoverReviewCount()).isEqualTo(100);
|
||||
assertThat(metadata.getPageCount()).isEqualTo(350);
|
||||
assertThat(metadata.getAuthors()).contains("Test Author");
|
||||
assertThat(metadata.getSeriesName()).isEqualTo("Test Series");
|
||||
assertThat(metadata.getSeriesNumber()).isEqualTo(2.0f);
|
||||
assertThat(metadata.getSeriesTotal()).isEqualTo(5);
|
||||
assertThat(metadata.getIsbn13()).isEqualTo("9781234567897");
|
||||
assertThat(metadata.getIsbn10()).isEqualTo("123456789X");
|
||||
assertThat(metadata.getPublisher()).isEqualTo("Test Publisher");
|
||||
assertThat(metadata.getLanguage()).isEqualTo("en");
|
||||
assertThat(metadata.getMoods()).containsExactlyInAnyOrder("Adventurous", "Exciting");
|
||||
assertThat(metadata.getCategories()).containsExactlyInAnyOrder("Fiction", "Fantasy");
|
||||
assertThat(metadata.getTags()).containsExactlyInAnyOrder("Epic", "Quest");
|
||||
assertThat(metadata.getProvider()).isEqualTo(MetadataProvider.Hardcover);
|
||||
}
|
||||
|
||||
@@ -267,8 +453,8 @@ class HardcoverParserTest {
|
||||
.isbn("123456789X")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.Hit hit = createFullyPopulatedHit();
|
||||
when(hardcoverBookSearchService.searchBooks("123456789X"))
|
||||
GraphQLResponse.BookWithEditions hit = createBookWithEditions();
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("123456789X"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
@@ -286,8 +472,11 @@ class HardcoverParserTest {
|
||||
.isbn("9791111111112")
|
||||
.build();
|
||||
|
||||
GraphQLResponse.Hit hit = createFullyPopulatedHit();
|
||||
when(hardcoverBookSearchService.searchBooks("9791111111112"))
|
||||
GraphQLResponse.BookWithEditions hit = createBookWithEditions();
|
||||
hit.getEditions().get(0).setIsbn13("9791111111112");
|
||||
hit.getEditions().get(0).setIsbn10(null);
|
||||
|
||||
when(hardcoverBookSearchService.searchBookByIsbn("9791111111112"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
@@ -308,7 +497,7 @@ class HardcoverParserTest {
|
||||
GraphQLResponse.Image image = new GraphQLResponse.Image();
|
||||
image.setUrl("https://example.com/cover.jpg");
|
||||
hit.getDocument().setImage(image);
|
||||
|
||||
|
||||
when(hardcoverBookSearchService.searchBooks("Test"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
@@ -327,7 +516,7 @@ class HardcoverParserTest {
|
||||
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
|
||||
hit.getDocument().setImage(null);
|
||||
|
||||
|
||||
when(hardcoverBookSearchService.searchBooks("Test"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
@@ -352,7 +541,7 @@ class HardcoverParserTest {
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
|
||||
hit.getDocument().setId("12345");
|
||||
hit.getDocument().setMoods(List.of("sad", "dark", "funny", "hopeful"));
|
||||
|
||||
|
||||
when(hardcoverBookSearchService.searchBooks("Test"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
@@ -377,7 +566,7 @@ class HardcoverParserTest {
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
|
||||
hit.getDocument().setId("12345");
|
||||
hit.getDocument().setMoods(List.of("sad", "funny", "invalid-mood"));
|
||||
|
||||
|
||||
when(hardcoverBookSearchService.searchBooks("Test"))
|
||||
.thenReturn(List.of(hit));
|
||||
when(hardcoverBookSearchService.fetchBookDetails(12345))
|
||||
@@ -400,7 +589,7 @@ class HardcoverParserTest {
|
||||
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
|
||||
hit.getDocument().setMoods(null);
|
||||
|
||||
|
||||
when(hardcoverBookSearchService.searchBooks("Test"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
@@ -456,7 +645,7 @@ class HardcoverParserTest {
|
||||
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
|
||||
hit.getDocument().setId("not-a-number");
|
||||
|
||||
|
||||
when(hardcoverBookSearchService.searchBooks("Test"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
@@ -492,7 +681,7 @@ class HardcoverParserTest {
|
||||
|
||||
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
|
||||
hit.getDocument().setReleaseDate("invalid-date");
|
||||
|
||||
|
||||
when(hardcoverBookSearchService.searchBooks("Test"))
|
||||
.thenReturn(List.of(hit));
|
||||
|
||||
@@ -551,7 +740,7 @@ class HardcoverParserTest {
|
||||
doc.setSlug(title.toLowerCase().replace(" ", "-"));
|
||||
doc.setAuthorNames(Set.of(author));
|
||||
doc.setId(String.valueOf(new Random().nextInt(100000)));
|
||||
|
||||
|
||||
GraphQLResponse.Hit hit = new GraphQLResponse.Hit();
|
||||
hit.setDocument(doc);
|
||||
return hit;
|
||||
@@ -573,22 +762,22 @@ class HardcoverParserTest {
|
||||
doc.setGenres(List.of("Fiction", "Fantasy"));
|
||||
doc.setMoods(List.of("adventurous", "exciting"));
|
||||
doc.setTags(List.of("Epic"));
|
||||
|
||||
|
||||
// Series info
|
||||
GraphQLResponse.Series series = new GraphQLResponse.Series();
|
||||
series.setName("Test Series");
|
||||
series.setBooksCount(5);
|
||||
|
||||
|
||||
GraphQLResponse.FeaturedSeries featuredSeries = new GraphQLResponse.FeaturedSeries();
|
||||
featuredSeries.setSeries(series);
|
||||
featuredSeries.setPosition(2);
|
||||
doc.setFeaturedSeries(featuredSeries);
|
||||
|
||||
|
||||
// Image
|
||||
GraphQLResponse.Image image = new GraphQLResponse.Image();
|
||||
image.setUrl("https://example.com/cover.jpg");
|
||||
doc.setImage(image);
|
||||
|
||||
|
||||
GraphQLResponse.Hit hit = new GraphQLResponse.Hit();
|
||||
hit.setDocument(doc);
|
||||
return hit;
|
||||
@@ -598,27 +787,114 @@ class HardcoverParserTest {
|
||||
HardcoverBookDetails details = new HardcoverBookDetails();
|
||||
details.setId(12345);
|
||||
details.setTitle("Test Book");
|
||||
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> moods = new ArrayList<>();
|
||||
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
|
||||
List<HardcoverCachedTag> moods = new ArrayList<>();
|
||||
moods.add(createCachedTag("sad", 15));
|
||||
moods.add(createCachedTag("dark", 12));
|
||||
moods.add(createCachedTag("emotional", 8));
|
||||
moods.add(createCachedTag("funny", 2)); // Low count, should be filtered
|
||||
cachedTags.put("Mood", moods);
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> genres = new ArrayList<>();
|
||||
|
||||
List<HardcoverCachedTag> genres = new ArrayList<>();
|
||||
genres.add(createCachedTag("Fiction", 10));
|
||||
genres.add(createCachedTag("Drama", 8));
|
||||
cachedTags.put("Genre", genres);
|
||||
|
||||
|
||||
details.setCachedTags(cachedTags);
|
||||
return details;
|
||||
}
|
||||
|
||||
private HardcoverBookDetails.CachedTag createCachedTag(String tag, int count) {
|
||||
HardcoverBookDetails.CachedTag cachedTag = new HardcoverBookDetails.CachedTag();
|
||||
private GraphQLResponse.BookWithEditions createBookWithEditions() {
|
||||
GraphQLResponse.BookWithEditions book = new GraphQLResponse.BookWithEditions();
|
||||
|
||||
book.setId(12345);
|
||||
book.setSlug("test-book-slug");
|
||||
book.setTitle("Test Book");
|
||||
book.setSubtitle("A Subtitle");
|
||||
book.setDescription("A description");
|
||||
book.setRating(4.25);
|
||||
book.setRatingsCount(100);
|
||||
book.setReviewsCount(50);
|
||||
book.setPages(350);
|
||||
book.setReleaseDate("2023-01-15");
|
||||
book.setReleaseYear(2023);
|
||||
|
||||
// Series info
|
||||
GraphQLResponse.Series series = new GraphQLResponse.Series();
|
||||
series.setName("Test Series");
|
||||
series.setBooksCount(5);
|
||||
|
||||
GraphQLResponse.FeaturedSeries featuredSeries = new GraphQLResponse.FeaturedSeries();
|
||||
featuredSeries.setSeries(series);
|
||||
featuredSeries.setPosition(2);
|
||||
book.setFeaturedBookSeries(featuredSeries);
|
||||
|
||||
GraphQLResponse.Image image = new GraphQLResponse.Image();
|
||||
image.setUrl("https://example.com/cover.jpg");
|
||||
book.setImage(image);
|
||||
|
||||
// Cached contributors for the book
|
||||
GraphQLResponse.Author bookAuthor = new GraphQLResponse.Author();
|
||||
bookAuthor.setId(1);
|
||||
bookAuthor.setSlug("test-author");
|
||||
bookAuthor.setName("Test Author");
|
||||
|
||||
GraphQLResponse.Contributor bookContributor = new GraphQLResponse.Contributor();
|
||||
bookContributor.setAuthor(bookAuthor);
|
||||
bookContributor.setContribution("Author");
|
||||
book.setCachedContributors(List.of(bookContributor));
|
||||
|
||||
// Editions
|
||||
GraphQLResponse.Edition edition = new GraphQLResponse.Edition();
|
||||
edition.setId(1);
|
||||
edition.setTitle("Test Book - Hardcover Edition");
|
||||
edition.setSubtitle("A Subtitle");
|
||||
edition.setPages(350);
|
||||
edition.setReleaseDate("2023-01-15");
|
||||
edition.setReleaseYear(2023);
|
||||
|
||||
// Cached contributors for the edition
|
||||
GraphQLResponse.Author editionAuthor = new GraphQLResponse.Author();
|
||||
editionAuthor.setId(1);
|
||||
editionAuthor.setSlug("test-author");
|
||||
editionAuthor.setName("Test Author");
|
||||
|
||||
GraphQLResponse.Contributor editionContributor = new GraphQLResponse.Contributor();
|
||||
editionContributor.setAuthor(editionAuthor);
|
||||
editionContributor.setContribution("Author");
|
||||
edition.setCachedContributors(List.of(editionContributor));
|
||||
|
||||
GraphQLResponse.Image editionImage = new GraphQLResponse.Image();
|
||||
editionImage.setUrl("https://example.com/edition-cover.jpg");
|
||||
edition.setImage(editionImage);
|
||||
|
||||
edition.setIsbn10("123456789X");
|
||||
edition.setIsbn13("9781234567897");
|
||||
|
||||
GraphQLResponse.Publisher publisher = new GraphQLResponse.Publisher();
|
||||
publisher.setName("Test Publisher");
|
||||
edition.setPublisher(publisher);
|
||||
|
||||
GraphQLResponse.Language language = new GraphQLResponse.Language();
|
||||
language.setCode2("en");
|
||||
edition.setLanguage(language);
|
||||
|
||||
book.setEditions(List.of(edition));
|
||||
|
||||
// Cached tags for the book (moods, genres, tags)
|
||||
GraphQLResponse.CachedTags cachedTags = new GraphQLResponse.CachedTags();
|
||||
cachedTags.setMood(List.of(createCachedTag("adventurous", 15), createCachedTag("exciting", 12), createCachedTag("novotes", 0)));
|
||||
cachedTags.setGenre(List.of(createCachedTag("fiction", 20), createCachedTag("fantasy", 18), createCachedTag("novotes", 0)));
|
||||
cachedTags.setTag(List.of(createCachedTag("epic", 10), createCachedTag("quest", 8), createCachedTag("novotes", 0)));
|
||||
book.setCachedTags(cachedTags);
|
||||
|
||||
return book;
|
||||
}
|
||||
|
||||
private HardcoverCachedTag createCachedTag(String tag, int count) {
|
||||
HardcoverCachedTag cachedTag = new HardcoverCachedTag();
|
||||
cachedTag.setTag(tag);
|
||||
cachedTag.setCount(count);
|
||||
return cachedTag;
|
||||
|
||||
+39
-39
@@ -27,9 +27,9 @@ class HardcoverMoodFilterTest {
|
||||
@DisplayName("filterBasicMoods should only return recognized moods")
|
||||
void filterBasicMoods_mixedMoods_returnsOnlyRecognized() {
|
||||
List<String> moods = List.of("funny", "invalid-mood", "sad", "not-a-mood", "dark");
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
|
||||
|
||||
|
||||
assertThat(result)
|
||||
.containsExactlyInAnyOrder("funny", "sad", "dark")
|
||||
.doesNotContain("invalid-mood", "not-a-mood");
|
||||
@@ -39,9 +39,9 @@ class HardcoverMoodFilterTest {
|
||||
@DisplayName("filterBasicMoods should normalize case to lowercase")
|
||||
void filterBasicMoods_mixedCase_normalizesToLowercase() {
|
||||
List<String> moods = List.of("FUNNY", "Sad", "DaRk", "Emotional");
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
|
||||
|
||||
|
||||
assertThat(result)
|
||||
.containsExactlyInAnyOrder("funny", "sad", "dark", "emotional");
|
||||
}
|
||||
@@ -53,9 +53,9 @@ class HardcoverMoodFilterTest {
|
||||
"funny", "sad", "dark", "emotional", "tense",
|
||||
"hopeful", "romantic", "scary", "mysterious", "reflective"
|
||||
);
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
|
||||
|
||||
|
||||
assertThat(result).hasSize(HardcoverMoodFilter.MAX_MOODS);
|
||||
}
|
||||
|
||||
@@ -67,9 +67,9 @@ class HardcoverMoodFilterTest {
|
||||
moods.add(null);
|
||||
moods.add("sad");
|
||||
moods.add(null);
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
|
||||
|
||||
|
||||
assertThat(result).containsExactlyInAnyOrder("funny", "sad");
|
||||
}
|
||||
|
||||
@@ -77,27 +77,27 @@ class HardcoverMoodFilterTest {
|
||||
@DisplayName("filterBasicMoods should trim whitespace from moods")
|
||||
void filterBasicMoods_whitespace_trimsCorrectly() {
|
||||
List<String> moods = List.of(" funny ", " sad", "dark ");
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
|
||||
|
||||
|
||||
assertThat(result).containsExactlyInAnyOrder("funny", "sad", "dark");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("filterMoodsWithCounts should return empty set for null cached_tags")
|
||||
void filterMoodsWithCounts_nullCachedTags_returnsEmptySet() {
|
||||
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(null);
|
||||
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts((Map<String, List<HardcoverCachedTag>>) null);
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("filterMoodsWithCounts should return empty set when no Mood category")
|
||||
void filterMoodsWithCounts_noMoodCategory_returnsEmptySet() {
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
cachedTags.put("Genre", List.of(createCachedTag("Fiction", 10)));
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
|
||||
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ class HardcoverMoodFilterTest {
|
||||
// "sad" has 17 votes, "funny" has 4 votes
|
||||
// With max=17 and MIN_VOTE_RATIO=0.15, threshold is ~3
|
||||
// But "funny" at 4 votes should still be filtered if we use higher threshold
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
cachedTags.put("Mood", List.of(
|
||||
createCachedTag("sad", 17),
|
||||
createCachedTag("dark", 16),
|
||||
@@ -117,9 +117,9 @@ class HardcoverMoodFilterTest {
|
||||
createCachedTag("hopeful", 1), // Very low
|
||||
createCachedTag("scary", 1) // Very low
|
||||
));
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
|
||||
|
||||
|
||||
// Top moods should be included
|
||||
assertThat(result).contains("sad", "dark", "emotional");
|
||||
// Low-vote moods should be filtered
|
||||
@@ -129,31 +129,31 @@ class HardcoverMoodFilterTest {
|
||||
@Test
|
||||
@DisplayName("filterMoodsWithCounts should respect MAX_MOODS limit")
|
||||
void filterMoodsWithCounts_manyHighVoteMoods_limitsToMax() {
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
List<HardcoverBookDetails.CachedTag> moodTags = new ArrayList<>();
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
List<HardcoverCachedTag> moodTags = new ArrayList<>();
|
||||
// Create 10 moods all with high vote counts
|
||||
for (int i = 0; i < 10; i++) {
|
||||
moodTags.add(createCachedTag("mood" + i, 20 - i));
|
||||
}
|
||||
cachedTags.put("Mood", moodTags);
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
|
||||
|
||||
|
||||
assertThat(result).hasSize(HardcoverMoodFilter.MAX_MOODS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("filterMoodsWithCounts should order moods by vote count (highest first)")
|
||||
void filterMoodsWithCounts_orderedByVoteCount() {
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
cachedTags.put("Mood", List.of(
|
||||
createCachedTag("emotional", 5),
|
||||
createCachedTag("sad", 15),
|
||||
createCachedTag("dark", 10)
|
||||
));
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
|
||||
|
||||
|
||||
// Result should be LinkedHashSet preserving order
|
||||
List<String> resultList = new ArrayList<>(result);
|
||||
assertThat(resultList).containsExactly("sad", "dark", "emotional");
|
||||
@@ -162,16 +162,16 @@ class HardcoverMoodFilterTest {
|
||||
@Test
|
||||
@DisplayName("filterMoodsWithCounts should handle null vote counts")
|
||||
void filterMoodsWithCounts_nullVoteCounts_handlesGracefully() {
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
HardcoverBookDetails.CachedTag tagWithNullCount = createCachedTag("mysterious", null);
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
HardcoverCachedTag tagWithNullCount = createCachedTag("mysterious", null);
|
||||
cachedTags.put("Mood", List.of(
|
||||
createCachedTag("sad", 10),
|
||||
tagWithNullCount,
|
||||
createCachedTag("dark", 8)
|
||||
));
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
|
||||
|
||||
|
||||
assertThat(result).containsExactlyInAnyOrder("sad", "dark");
|
||||
assertThat(result).doesNotContain("mysterious");
|
||||
}
|
||||
@@ -179,30 +179,30 @@ class HardcoverMoodFilterTest {
|
||||
@Test
|
||||
@DisplayName("filterMoodsWithCounts should return empty when all votes are zero")
|
||||
void filterMoodsWithCounts_allZeroVotes_returnsEmpty() {
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
cachedTags.put("Mood", List.of(
|
||||
createCachedTag("sad", 0),
|
||||
createCachedTag("dark", 0)
|
||||
));
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
|
||||
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("filterGenresWithCounts should return filtered genres")
|
||||
void filterGenresWithCounts_validData_returnsFiltered() {
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
cachedTags.put("Genre", List.of(
|
||||
createCachedTag("Fiction", 10),
|
||||
createCachedTag("War", 8),
|
||||
createCachedTag("Classics", 5),
|
||||
createCachedTag("Comics", 0) // Should be filtered out
|
||||
));
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterGenresWithCounts(cachedTags);
|
||||
|
||||
|
||||
assertThat(result).containsExactlyInAnyOrder("Fiction", "War", "Classics");
|
||||
assertThat(result).doesNotContain("Comics");
|
||||
}
|
||||
@@ -210,15 +210,15 @@ class HardcoverMoodFilterTest {
|
||||
@Test
|
||||
@DisplayName("filterTagsWithCounts should filter tags with low votes")
|
||||
void filterTagsWithCounts_mixedVotes_filtersLowVotes() {
|
||||
Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags = new HashMap<>();
|
||||
Map<String, List<HardcoverCachedTag>> cachedTags = new HashMap<>();
|
||||
cachedTags.put("Tag", List.of(
|
||||
createCachedTag("Loveable Characters", 13),
|
||||
createCachedTag("Strong Character Development", 9),
|
||||
createCachedTag("Plot driven", 1) // Should be filtered (below threshold)
|
||||
));
|
||||
|
||||
|
||||
Set<String> result = HardcoverMoodFilter.filterTagsWithCounts(cachedTags);
|
||||
|
||||
|
||||
assertThat(result).contains("Loveable Characters", "Strong Character Development");
|
||||
assertThat(result).doesNotContain("Plot driven");
|
||||
}
|
||||
@@ -249,8 +249,8 @@ class HardcoverMoodFilterTest {
|
||||
/**
|
||||
* Helper method to create a CachedTag for testing.
|
||||
*/
|
||||
private HardcoverBookDetails.CachedTag createCachedTag(String tag, Integer count) {
|
||||
HardcoverBookDetails.CachedTag cachedTag = new HardcoverBookDetails.CachedTag();
|
||||
private HardcoverCachedTag createCachedTag(String tag, Integer count) {
|
||||
HardcoverCachedTag cachedTag = new HardcoverCachedTag();
|
||||
cachedTag.setTag(tag);
|
||||
cachedTag.setCount(count);
|
||||
return cachedTag;
|
||||
|
||||
Reference in New Issue
Block a user