feat(hardcover): implement book details response and search service enhancements (#2303)

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2026-01-18 18:19:58 -07:00
committed by GitHub
parent 0a3c6d72fa
commit a0f4c8e43e
8 changed files with 1474 additions and 125 deletions
@@ -4,8 +4,7 @@ import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.service.metadata.parser.hardcover.GraphQLResponse;
import com.adityachandel.booklore.service.metadata.parser.hardcover.HardcoverBookSearchService;
import com.adityachandel.booklore.service.metadata.parser.hardcover.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.WordUtils;
@@ -15,9 +14,7 @@ import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -27,6 +24,8 @@ import java.util.stream.Collectors;
public class HardcoverParser implements BookParser {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final double AUTHOR_MATCH_THRESHOLD = 0.5;
private final HardcoverBookSearchService hardcoverBookSearchService;
@Override
@@ -39,114 +38,259 @@ public class HardcoverParser implements BookParser {
log.info("Hardcover: Fetching metadata using ISBN {}", fetchMetadataRequest.getIsbn());
hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getIsbn());
} else {
log.info("Hardcover: Fetching metadata using title '{}'", fetchMetadataRequest.getTitle());
hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getTitle());
// Use improved search strategy with title cleaning and fallbacks
hits = performSmartSearch(fetchMetadataRequest);
}
if (hits == null || hits.isEmpty()) {
log.info("Hardcover: No results found for {}", searchByIsbn ? "ISBN " + fetchMetadataRequest.getIsbn() : "title " + fetchMetadataRequest.getTitle());
log.info("Hardcover: No results found for {}",
searchByIsbn ? "ISBN " + fetchMetadataRequest.getIsbn() : "title " + fetchMetadataRequest.getTitle());
return List.of();
}
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
String searchAuthor = fetchMetadataRequest.getAuthor() != null ? fetchMetadataRequest.getAuthor() : "";
return hits.stream()
// Filter by author and map to metadata
List<GraphQLResponse.Document> matchedDocs = hits.stream()
.map(GraphQLResponse.Hit::getDocument)
.filter(doc -> {
if (searchByIsbn || searchAuthor.isBlank()) return true;
if (doc.getAuthorNames() == null || doc.getAuthorNames().isEmpty()) return false;
List<String> actualAuthorTokens = doc.getAuthorNames().stream()
.map(String::toLowerCase)
.flatMap(WHITESPACE_PATTERN::splitAsStream)
.toList();
List<String> searchAuthorTokens = List.of(WHITESPACE_PATTERN.split(searchAuthor.toLowerCase()));
for (String actual : actualAuthorTokens) {
for (String query : searchAuthorTokens) {
int score = fuzzyScore.fuzzyScore(actual, query);
int maxScore = Math.max(fuzzyScore.fuzzyScore(query, query), fuzzyScore.fuzzyScore(actual, actual));
double similarity = maxScore > 0 ? (double) score / maxScore : 0;
if (similarity >= 0.5) return true;
}
}
return false;
})
.map(doc -> {
BookMetadata metadata = new BookMetadata();
metadata.setHardcoverId(doc.getSlug());
// Set numeric book ID for API operations
if (doc.getId() != null) {
try {
metadata.setHardcoverBookId(Integer.parseInt(doc.getId()));
} catch (NumberFormatException e) {
log.debug("Could not parse Hardcover book ID: {}", doc.getId());
}
}
metadata.setTitle(doc.getTitle());
metadata.setSubtitle(doc.getSubtitle());
metadata.setDescription(doc.getDescription());
if (doc.getAuthorNames() != null) {
metadata.setAuthors(Set.copyOf(doc.getAuthorNames()));
}
if (doc.getFeaturedSeries() != null) {
if (doc.getFeaturedSeries().getSeries() != null) {
metadata.setSeriesName(doc.getFeaturedSeries().getSeries().getName());
metadata.setSeriesTotal(doc.getFeaturedSeries().getSeries().getBooksCount());
}
if (doc.getFeaturedSeries().getPosition() != null) {
try {
metadata.setSeriesNumber(Float.parseFloat(String.valueOf(doc.getFeaturedSeries().getPosition())));
} catch (NumberFormatException ignored) {
}
}
}
if (doc.getRating() != null) {
metadata.setHardcoverRating(BigDecimal.valueOf(doc.getRating()).setScale(2, RoundingMode.HALF_UP).doubleValue());
}
metadata.setHardcoverReviewCount(doc.getRatingsCount());
metadata.setPageCount(doc.getPages());
metadata.setPublishedDate(doc.getReleaseDate() != null ? LocalDate.parse(doc.getReleaseDate()) : null);
if (doc.getGenres() != null && !doc.getGenres().isEmpty()) {
metadata.setCategories(doc.getGenres().stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toSet()));
}
if (doc.getMoods() != null && !doc.getMoods().isEmpty()) {
metadata.setMoods(doc.getMoods().stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toSet()));
}
if (doc.getTags() != null && !doc.getTags().isEmpty()) {
metadata.setTags(doc.getTags().stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toSet()));
}
if (doc.getIsbns() != null) {
String inputIsbn = fetchMetadataRequest.getIsbn();
if (inputIsbn != null && inputIsbn.length() == 10 && doc.getIsbns().contains(inputIsbn)) {
metadata.setIsbn10(inputIsbn);
} else {
metadata.setIsbn10(doc.getIsbns().stream().filter(isbn -> isbn.length() == 10).findFirst().orElse(null));
}
if (inputIsbn != null && inputIsbn.length() == 13 && doc.getIsbns().contains(inputIsbn)) {
metadata.setIsbn13(inputIsbn);
} else {
metadata.setIsbn13(doc.getIsbns().stream().filter(isbn -> isbn.length() == 13).findFirst().orElse(null));
}
}
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
metadata.setProvider(MetadataProvider.Hardcover);
return metadata;
})
.filter(doc -> filterByAuthor(doc, searchAuthor, searchByIsbn, fuzzyScore))
.toList();
if (matchedDocs.isEmpty()) {
return List.of();
}
// Only fetch detailed mood data for the TOP match to minimize API calls
// Other results use the basic mood data from search
List<BookMetadata> results = new ArrayList<>();
boolean isFirst = true;
for (GraphQLResponse.Document doc : matchedDocs) {
BookMetadata metadata = mapDocumentToMetadata(doc, fetchMetadataRequest, isFirst);
results.add(metadata);
isFirst = false;
}
return results;
}
private List<GraphQLResponse.Hit> performSmartSearch(FetchMetadataRequest request) {
String title = request.getTitle();
String author = request.getAuthor();
if (title == null || title.isBlank()) {
log.warn("Hardcover: No title provided for search");
return Collections.emptyList();
}
if (author != null && !author.isBlank()) {
String combinedQuery = title.trim() + " " + author.trim();
log.info("Hardcover: Searching with title+author: '{}'", combinedQuery);
List<GraphQLResponse.Hit> results = hardcoverBookSearchService.searchBooks(combinedQuery);
if (results != null && !results.isEmpty()) {
return results;
}
}
log.info("Hardcover: Searching with title: '{}'", title);
List<GraphQLResponse.Hit> results = hardcoverBookSearchService.searchBooks(title.trim());
return results != null ? results : Collections.emptyList();
}
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()) {
return true;
}
if (doc.getAuthorNames() == null || doc.getAuthorNames().isEmpty()) {
return false;
}
List<String> actualAuthorTokens = doc.getAuthorNames().stream()
.map(String::toLowerCase)
.flatMap(WHITESPACE_PATTERN::splitAsStream)
.toList();
List<String> searchAuthorTokens = List.of(WHITESPACE_PATTERN.split(searchAuthor.toLowerCase()));
for (String actual : actualAuthorTokens) {
for (String query : searchAuthorTokens) {
int score = fuzzyScore.fuzzyScore(actual, query);
int maxScore = Math.max(
fuzzyScore.fuzzyScore(query, query),
fuzzyScore.fuzzyScore(actual, actual)
);
double similarity = maxScore > 0 ? (double) score / maxScore : 0;
if (similarity >= AUTHOR_MATCH_THRESHOLD) {
return true;
}
}
}
return false;
}
private BookMetadata mapDocumentToMetadata(GraphQLResponse.Document doc, FetchMetadataRequest request, boolean fetchDetailedMoods) {
BookMetadata metadata = new BookMetadata();
metadata.setHardcoverId(doc.getSlug());
Integer bookId = parseBookId(doc.getId());
if (bookId != null) {
metadata.setHardcoverBookId(bookId);
}
metadata.setTitle(doc.getTitle());
metadata.setSubtitle(doc.getSubtitle());
metadata.setDescription(doc.getDescription());
if (doc.getAuthorNames() != null) {
metadata.setAuthors(Set.copyOf(doc.getAuthorNames()));
}
mapSeriesInfo(doc, metadata);
if (doc.getRating() != null) {
metadata.setHardcoverRating(
BigDecimal.valueOf(doc.getRating()).setScale(2, RoundingMode.HALF_UP).doubleValue()
);
}
metadata.setHardcoverReviewCount(doc.getRatingsCount());
metadata.setPageCount(doc.getPages());
if (doc.getReleaseDate() != null) {
try {
metadata.setPublishedDate(LocalDate.parse(doc.getReleaseDate()));
} catch (Exception e) {
log.debug("Could not parse release date: {}", doc.getReleaseDate());
}
}
mapTagsAndMoods(doc, metadata, bookId, fetchDetailedMoods);
mapIsbns(doc, request, metadata);
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
metadata.setProvider(MetadataProvider.Hardcover);
return metadata;
}
private Integer parseBookId(String id) {
if (id == null) {
return null;
}
try {
return Integer.parseInt(id);
} catch (NumberFormatException e) {
log.debug("Could not parse Hardcover book ID: {}", id);
return null;
}
}
private void mapSeriesInfo(GraphQLResponse.Document doc, BookMetadata metadata) {
if (doc.getFeaturedSeries() == null) {
return;
}
if (doc.getFeaturedSeries().getSeries() != null) {
metadata.setSeriesName(doc.getFeaturedSeries().getSeries().getName());
metadata.setSeriesTotal(doc.getFeaturedSeries().getSeries().getBooksCount());
}
if (doc.getFeaturedSeries().getPosition() != null) {
try {
metadata.setSeriesNumber(Float.parseFloat(String.valueOf(doc.getFeaturedSeries().getPosition())));
} catch (NumberFormatException ignored) {
}
}
}
private void mapTagsAndMoods(GraphQLResponse.Document doc, BookMetadata metadata, Integer bookId, boolean fetchDetailedMoods) {
boolean usedDetailedMoods = false;
if (fetchDetailedMoods && bookId != null) {
usedDetailedMoods = tryFetchDetailedMoods(bookId, metadata);
}
if (!usedDetailedMoods && doc.getMoods() != null && !doc.getMoods().isEmpty()) {
Set<String> basicFilteredMoods = HardcoverMoodFilter.filterBasicMoods(doc.getMoods());
metadata.setMoods(basicFilteredMoods.stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toCollection(LinkedHashSet::new)));
}
if ((metadata.getCategories() == null || metadata.getCategories().isEmpty())
&& doc.getGenres() != null && !doc.getGenres().isEmpty()) {
metadata.setCategories(doc.getGenres().stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toSet()));
}
if ((metadata.getTags() == null || metadata.getTags().isEmpty())
&& doc.getTags() != null && !doc.getTags().isEmpty()) {
metadata.setTags(doc.getTags().stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toSet()));
}
}
private boolean tryFetchDetailedMoods(Integer bookId, BookMetadata metadata) {
try {
HardcoverBookDetails details = hardcoverBookSearchService.fetchBookDetails(bookId);
if (details == null || details.getCachedTags() == null || details.getCachedTags().isEmpty()) {
return false;
}
Set<String> filteredMoods = HardcoverMoodFilter.filterMoodsWithCounts(details.getCachedTags());
if (!filteredMoods.isEmpty()) {
metadata.setMoods(filteredMoods.stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toCollection(LinkedHashSet::new)));
}
Set<String> filteredGenres = HardcoverMoodFilter.filterGenresWithCounts(details.getCachedTags());
if (!filteredGenres.isEmpty()) {
metadata.setCategories(filteredGenres.stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toCollection(LinkedHashSet::new)));
}
Set<String> filteredTags = HardcoverMoodFilter.filterTagsWithCounts(details.getCachedTags());
if (!filteredTags.isEmpty()) {
metadata.setTags(filteredTags.stream()
.map(WordUtils::capitalizeFully)
.collect(Collectors.toCollection(LinkedHashSet::new)));
}
return !filteredMoods.isEmpty();
} catch (Exception e) {
log.debug("Failed to fetch book details: {}", e.getMessage());
return false;
}
}
private void mapIsbns(GraphQLResponse.Document doc, FetchMetadataRequest request, BookMetadata metadata) {
if (doc.getIsbns() == null) {
return;
}
String inputIsbn = request.getIsbn();
if (inputIsbn != null && inputIsbn.length() == 10 && doc.getIsbns().contains(inputIsbn)) {
metadata.setIsbn10(inputIsbn);
} else {
metadata.setIsbn10(doc.getIsbns().stream()
.filter(isbn -> isbn.length() == 10)
.findFirst()
.orElse(null));
}
if (inputIsbn != null && inputIsbn.length() == 13 && doc.getIsbns().contains(inputIsbn)) {
metadata.setIsbn13(inputIsbn);
} else {
metadata.setIsbn13(doc.getIsbns().stream()
.filter(isbn -> isbn.length() == 13)
.findFirst()
.orElse(null));
}
}
@Override
@@ -0,0 +1,44 @@
package com.adityachandel.booklore.service.metadata.parser.hardcover;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import java.util.List;
import java.util.Map;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class HardcoverBookDetails {
private Integer id;
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;
}
}
@@ -0,0 +1,25 @@
package com.adityachandel.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 HardcoverBookDetailsResponse {
private Data data;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Data {
@JsonProperty("books_by_pk")
private HardcoverBookDetails booksByPk;
}
}
@@ -7,62 +7,142 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClientResponseException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
@Slf4j
@Service
public class HardcoverBookSearchService {
public static final int DEFAULT_PER_PAGE = 10;
private static final long INITIAL_DELAY_MS = 1200;
private static final long MAX_DELAY_MS = 15000;
private final RestClient restClient;
private final AppSettingService appSettingService;
private final AtomicLong requestDelayMs = new AtomicLong(INITIAL_DELAY_MS);
private final AtomicLong lastRequestTime = new AtomicLong(0);
private final AtomicLong successCount = new AtomicLong(0);
@Autowired
public HardcoverBookSearchService(AppSettingService appSettingService) {
this.appSettingService = appSettingService;
String apiUrl = "https://api.hardcover.app/v1/graphql";
this.restClient = RestClient.builder()
.baseUrl(apiUrl)
.baseUrl("https://api.hardcover.app/v1/graphql")
.build();
}
public List<GraphQLResponse.Hit> searchBooks(String query) {
String apiToken = appSettingService.getAppSettings().getMetadataProviderSettings().getHardcover().getApiKey();
if (apiToken == null || apiToken.isEmpty()) {
log.warn("Hardcover API token not set");
return searchBooks(query, DEFAULT_PER_PAGE);
}
public List<GraphQLResponse.Hit> searchBooks(String query, int perPage) {
String apiToken = getApiToken();
if (apiToken == null) {
return Collections.emptyList();
}
String graphqlQuery = String.format(
"query SearchBooks { search(query: \"%s\", query_type: \"Book\", per_page: 5, page: 1) { results } }",
query.replace("\"", "\\\"")
);
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));
GraphQLResponse response = executeRequest(body, GraphQLResponse.class, apiToken);
if (response == null || response.getData() == null ||
response.getData().getSearch() == null ||
response.getData().getSearch().getResults() == null) {
return Collections.emptyList();
}
List<GraphQLResponse.Hit> hits = response.getData().getSearch().getResults().getHits();
return hits != null ? hits : Collections.emptyList();
}
public HardcoverBookDetails fetchBookDetails(int bookId) {
String apiToken = getApiToken();
if (apiToken == null) {
return null;
}
GraphQLRequest body = new GraphQLRequest();
body.setQuery(graphqlQuery);
body.setVariables(Collections.emptyMap());
body.setQuery("query BookDetails($id: Int!) { books_by_pk(id: $id) { id title cached_tags } }");
body.setVariables(java.util.Map.of("id", bookId));
HardcoverBookDetailsResponse response = executeRequest(body, HardcoverBookDetailsResponse.class, apiToken);
if (response == null || response.getData() == null) {
return null;
}
return response.getData().getBooksByPk();
}
private <T> T executeRequest(GraphQLRequest body, Class<T> responseType, String apiToken) {
enforceRateLimit();
try {
GraphQLResponse response = restClient.post()
T response = restClient.post()
.uri("")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.AUTHORIZATION, "Bearer " + apiToken)
.body(body)
.retrieve()
.body(GraphQLResponse.class);
.body(responseType);
if (response == null || response.getData() == null || response.getData().getSearch() == null || response.getData().getSearch().getResults() == null) {
log.warn("Empty or malformed response from Hardcover API");
return Collections.emptyList();
successCount.incrementAndGet();
if (successCount.get() % 5 == 0) {
reduceDelay();
}
return response;
return response.getData().getSearch().getResults().getHits();
} catch (RestClientException e) {
log.error("Failed to fetch data from Hardcover API, Error: {}", e.getMessage());
return Collections.emptyList();
} catch (RestClientResponseException e) {
successCount.set(0);
if (e.getStatusCode().value() == 429 || e.getResponseBodyAsString().contains("Throttled")) {
increaseDelay();
log.warn("Hardcover API throttled, increased delay to {}ms", requestDelayMs.get());
} else {
log.error("Hardcover API error: {}", e.getMessage());
}
return null;
} catch (Exception e) {
log.error("Hardcover API request failed: {}", e.getMessage());
return null;
} finally {
lastRequestTime.set(System.currentTimeMillis());
}
}
}
private void enforceRateLimit() {
long now = System.currentTimeMillis();
long last = lastRequestTime.get();
long delay = requestDelayMs.get();
long elapsed = now - last;
if (elapsed < delay) {
try {
Thread.sleep(delay - elapsed);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private void increaseDelay() {
requestDelayMs.updateAndGet(current -> Math.min(current * 2, MAX_DELAY_MS));
}
private void reduceDelay() {
requestDelayMs.updateAndGet(current -> Math.max(current - 100, INITIAL_DELAY_MS));
}
private String getApiToken() {
String apiToken = appSettingService.getAppSettings().getMetadataProviderSettings().getHardcover().getApiKey();
if (apiToken == null || apiToken.isEmpty()) {
log.warn("Hardcover API token not set");
return null;
}
return apiToken;
}
}
@@ -0,0 +1,126 @@
package com.adityachandel.booklore.service.metadata.parser.hardcover;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
public class HardcoverMoodFilter {
public static final Set<String> RECOGNIZED_MOODS = Set.of(
"adventurous", "challenging", "dark", "emotional", "funny",
"hopeful", "informative", "inspiring", "lighthearted", "mysterious",
"reflective", "relaxing", "romantic", "sad", "scary", "tense"
);
public static final int MIN_VOTE_COUNT = 3;
public static final double MIN_VOTE_RATIO = 0.15;
public static final int MAX_MOODS = 5;
private HardcoverMoodFilter() {
}
public static Set<String> filterBasicMoods(List<String> moods) {
if (moods == null || moods.isEmpty()) {
return Collections.emptySet();
}
return moods.stream()
.filter(Objects::nonNull)
.map(String::toLowerCase)
.map(String::trim)
.filter(RECOGNIZED_MOODS::contains)
.limit(MAX_MOODS)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public static Set<String> filterMoodsWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
if (cachedTags == null || cachedTags.isEmpty()) {
return Collections.emptySet();
}
List<HardcoverBookDetails.CachedTag> moodTags = cachedTags.get("Mood");
if (moodTags == null || moodTags.isEmpty()) {
return Collections.emptySet();
}
// Find the maximum vote count
int maxCount = moodTags.stream()
.filter(tag -> tag.getCount() != null)
.mapToInt(HardcoverBookDetails.CachedTag::getCount)
.max()
.orElse(0);
if (maxCount == 0) {
// No votes at all, just return empty
return Collections.emptySet();
}
int minCountThreshold = Math.max(MIN_VOTE_COUNT, (int) (maxCount * MIN_VOTE_RATIO));
List<HardcoverBookDetails.CachedTag> filteredMoods = moodTags.stream()
.filter(tag -> tag.getCount() != null && tag.getCount() >= minCountThreshold)
.filter(tag -> tag.getTag() != null)
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
.limit(MAX_MOODS)
.toList();
log.debug("Filtered moods from {} to {} (max count: {}, threshold: {})",
moodTags.size(), filteredMoods.size(), maxCount, minCountThreshold);
return filteredMoods.stream()
.map(HardcoverBookDetails.CachedTag::getTag)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public static Set<String> filterGenresWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
if (cachedTags == null || cachedTags.isEmpty()) {
return Collections.emptySet();
}
List<HardcoverBookDetails.CachedTag> genreTags = cachedTags.get("Genre");
if (genreTags == null || genreTags.isEmpty()) {
return Collections.emptySet();
}
// For genres, we're more lenient as they're generally more reliable
return genreTags.stream()
.filter(tag -> tag.getCount() != null && tag.getCount() >= 1)
.filter(tag -> tag.getTag() != null)
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
.limit(10) // Allow more genres
.map(HardcoverBookDetails.CachedTag::getTag)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public static Set<String> filterTagsWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
if (cachedTags == null || cachedTags.isEmpty()) {
return Collections.emptySet();
}
List<HardcoverBookDetails.CachedTag> tagList = cachedTags.get("Tag");
if (tagList == null || tagList.isEmpty()) {
return Collections.emptySet();
}
// For general tags, use a moderate threshold
return tagList.stream()
.filter(tag -> tag.getCount() != null && tag.getCount() >= 2)
.filter(tag -> tag.getTag() != null)
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
.limit(10)
.map(HardcoverBookDetails.CachedTag::getTag)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public static String normalizeMood(String mood) {
if (mood == null) {
return null;
}
return mood.toLowerCase().trim();
}
}
@@ -0,0 +1,558 @@
package com.adityachandel.booklore.service.metadata.parser;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.service.metadata.parser.hardcover.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for HardcoverParser.
*
* These tests verify:
* - Combined title+author search strategy for better reliability
* - ISBN search behavior
* - Author filtering logic
* - Mood/genre/tag mapping with quality filtering
* - Edge cases and error handling
*/
class HardcoverParserTest {
@Mock
private HardcoverBookSearchService hardcoverBookSearchService;
private HardcoverParser parser;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
parser = new HardcoverParser(hardcoverBookSearchService);
}
@Nested
@DisplayName("Search Strategy Tests")
class SearchStrategyTests {
@Test
@DisplayName("Should search with combined title+author when both provided")
void fetchMetadata_titleAndAuthor_searchesCombined() {
Book book = Book.builder().title("Lamb").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Lamb")
.author("Christopher Moore")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Lamb: The Gospel According to Biff", "Christopher Moore");
when(hardcoverBookSearchService.searchBooks("Lamb Christopher Moore"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).searchBooks("Lamb Christopher Moore");
assertThat(results).hasSize(1);
assertThat(results.get(0).getTitle()).isEqualTo("Lamb: The Gospel According to Biff");
}
@Test
@DisplayName("Should fall back to title-only search when combined search returns empty")
void fetchMetadata_combinedSearchEmpty_fallsBackToTitleOnly() {
Book book = Book.builder().title("Some Book").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Some Book")
.author("Unknown Author")
.build();
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));
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).searchBooks("Some Book Unknown Author");
verify(hardcoverBookSearchService).searchBooks("Some Book");
}
@Test
@DisplayName("Should search by ISBN when provided")
void fetchMetadata_isbnProvided_searchesByIsbn() {
Book book = Book.builder().title("Any Title").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Any Title")
.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"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).searchBooks("978-0316769488");
verify(hardcoverBookSearchService, never()).searchBooks(contains("title"));
}
@Test
@DisplayName("Should search title-only when no author provided")
void fetchMetadata_noAuthor_searchesTitleOnly() {
Book book = Book.builder().title("The Prince").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("The Prince")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("The Prince", "Niccolò Machiavelli");
when(hardcoverBookSearchService.searchBooks("The Prince"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).searchBooks("The Prince");
}
}
@Nested
@DisplayName("Author Filtering Tests")
class AuthorFilteringTests {
@Test
@DisplayName("Should filter results by author name when author provided")
void fetchMetadata_authorProvided_filtersResults() {
Book book = Book.builder().title("The Prince").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("The Prince")
.author("Machiavelli")
.build();
List<GraphQLResponse.Hit> hits = List.of(
createHitWithAuthor("The Prince", "Kiera Cass"),
createHitWithAuthor("The Prince", "Niccolò Machiavelli"),
createHitWithAuthor("The Prince", "Tiffany Reisz")
);
when(hardcoverBookSearchService.searchBooks("The Prince Machiavelli"))
.thenReturn(hits);
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
assertThat(results.get(0).getAuthors()).contains("Niccolò Machiavelli");
}
@Test
@DisplayName("Should use fuzzy matching for author names")
void fetchMetadata_fuzzyAuthorMatch_includesPartialMatches() {
Book book = Book.builder().title("Test Book").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test Book")
.author("Moore")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test Book", "Christopher Moore");
when(hardcoverBookSearchService.searchBooks("Test Book Moore"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
}
@Test
@DisplayName("Should not filter by author for ISBN searches")
void fetchMetadata_isbnSearch_noAuthorFilter() {
Book book = Book.builder().title("Any Book").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Any Book")
.isbn("1234567890")
.author("Wrong Author") // Should be ignored
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Any Book", "Correct Author");
when(hardcoverBookSearchService.searchBooks("1234567890"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1); // Should not filter out
}
}
@Nested
@DisplayName("Metadata Mapping Tests")
class MetadataMappingTests {
@Test
@DisplayName("Should map all basic metadata fields correctly")
void fetchMetadata_fullDocument_mapsAllFields() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.isbn("9781234567890")
.build();
GraphQLResponse.Hit hit = createFullyPopulatedHit();
when(hardcoverBookSearchService.searchBooks("9781234567890"))
.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");
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("9781234567890");
assertThat(metadata.getIsbn10()).isEqualTo("1234567890");
assertThat(metadata.getProvider()).isEqualTo(MetadataProvider.Hardcover);
}
@Test
@DisplayName("Should map thumbnail URL correctly")
void fetchMetadata_withImage_mapsThumbnailUrl() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
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));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results.get(0).getThumbnailUrl()).isEqualTo("https://example.com/cover.jpg");
}
@Test
@DisplayName("Should handle null image gracefully")
void fetchMetadata_nullImage_handlesGracefully() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setImage(null);
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results.get(0).getThumbnailUrl()).isNull();
}
}
@Nested
@DisplayName("Mood and Genre Filtering Tests")
class MoodFilteringTests {
@Test
@DisplayName("Should fetch detailed book info for mood filtering when book ID available")
void fetchMetadata_withBookId_fetchesDetailedMoods() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
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));
HardcoverBookDetails details = createBookDetailsWithMoodCounts();
when(hardcoverBookSearchService.fetchBookDetails(12345))
.thenReturn(details);
List<BookMetadata> results = parser.fetchMetadata(book, request);
verify(hardcoverBookSearchService).fetchBookDetails(12345);
assertThat(results.get(0).getMoods()).isNotNull();
}
@Test
@DisplayName("Should fall back to basic mood filtering when detail fetch fails")
void fetchMetadata_detailFetchFails_fallsBackToBasicFilter() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
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))
.thenReturn(null); // Simulate failure
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results.get(0).getMoods())
.containsAnyOf("Sad", "Funny")
.doesNotContain("Invalid-Mood");
}
@Test
@DisplayName("Should handle books without moods")
void fetchMetadata_noMoods_handlesGracefully() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setMoods(null);
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
}
}
@Nested
@DisplayName("Edge Cases and Error Handling")
class EdgeCaseTests {
@Test
@DisplayName("Should return empty list when search returns null")
void fetchMetadata_nullResponse_returnsEmptyList() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
when(hardcoverBookSearchService.searchBooks(anyString()))
.thenReturn(null);
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).isEmpty();
}
@Test
@DisplayName("Should return empty list when search returns empty")
void fetchMetadata_emptyResponse_returnsEmptyList() {
Book book = Book.builder().title("Nonexistent Book").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Nonexistent Book")
.build();
when(hardcoverBookSearchService.searchBooks(anyString()))
.thenReturn(Collections.emptyList());
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).isEmpty();
}
@Test
@DisplayName("Should handle invalid book ID gracefully")
void fetchMetadata_invalidBookId_handlesGracefully() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setId("not-a-number");
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
assertThat(results.get(0).getHardcoverBookId()).isNull();
}
@Test
@DisplayName("Should handle null title in request")
void fetchMetadata_nullTitle_returnsEmptyList() {
Book book = Book.builder().build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.author("Some Author")
.build();
when(hardcoverBookSearchService.searchBooks(anyString()))
.thenReturn(Collections.emptyList());
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).isEmpty();
}
@Test
@DisplayName("Should handle invalid date format gracefully")
void fetchMetadata_invalidDate_handlesGracefully() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
GraphQLResponse.Hit hit = createHitWithAuthor("Test", "Author");
hit.getDocument().setReleaseDate("invalid-date");
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(List.of(hit));
List<BookMetadata> results = parser.fetchMetadata(book, request);
assertThat(results).hasSize(1);
assertThat(results.get(0).getPublishedDate()).isNull();
}
}
@Nested
@DisplayName("fetchTopMetadata Tests")
class FetchTopMetadataTests {
@Test
@DisplayName("Should return first result")
void fetchTopMetadata_hasResults_returnsFirst() {
Book book = Book.builder().title("Test").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Test")
.build();
List<GraphQLResponse.Hit> hits = List.of(
createHitWithAuthor("First Book", "Author 1"),
createHitWithAuthor("Second Book", "Author 2")
);
when(hardcoverBookSearchService.searchBooks("Test"))
.thenReturn(hits);
BookMetadata result = parser.fetchTopMetadata(book, request);
assertThat(result).isNotNull();
assertThat(result.getTitle()).isEqualTo("First Book");
}
@Test
@DisplayName("Should return null when no results")
void fetchTopMetadata_noResults_returnsNull() {
Book book = Book.builder().title("Nonexistent").build();
FetchMetadataRequest request = FetchMetadataRequest.builder()
.title("Nonexistent")
.build();
when(hardcoverBookSearchService.searchBooks(anyString()))
.thenReturn(Collections.emptyList());
BookMetadata result = parser.fetchTopMetadata(book, request);
assertThat(result).isNull();
}
}
private GraphQLResponse.Hit createHitWithAuthor(String title, String author) {
GraphQLResponse.Document doc = new GraphQLResponse.Document();
doc.setTitle(title);
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;
}
private GraphQLResponse.Hit createFullyPopulatedHit() {
GraphQLResponse.Document doc = new GraphQLResponse.Document();
doc.setId("12345");
doc.setSlug("test-book-slug");
doc.setTitle("Test Book");
doc.setSubtitle("A Subtitle");
doc.setDescription("A description");
doc.setAuthorNames(Set.of("Test Author"));
doc.setRating(4.25);
doc.setRatingsCount(100);
doc.setPages(350);
doc.setReleaseDate("2023-01-15");
doc.setIsbns(List.of("9781234567890", "1234567890"));
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;
}
private HardcoverBookDetails createBookDetailsWithMoodCounts() {
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<>();
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<>();
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();
cachedTag.setTag(tag);
cachedTag.setCount(count);
return cachedTag;
}
}
@@ -0,0 +1,114 @@
package com.adityachandel.booklore.service.metadata.parser.hardcover;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
class HardcoverBookSearchServiceTest {
@Mock
private AppSettingService appSettingService;
private HardcoverBookSearchService searchService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
searchService = new HardcoverBookSearchService(appSettingService);
}
@Nested
@DisplayName("API Token Validation Tests")
class ApiTokenTests {
@Test
@DisplayName("Should return empty list when API token is null")
void searchBooks_nullToken_returnsEmptyList() {
setupAppSettingsWithToken(null);
List<GraphQLResponse.Hit> results = searchService.searchBooks("test query");
assertThat(results).isEmpty();
}
@Test
@DisplayName("Should return empty list when API token is empty")
void searchBooks_emptyToken_returnsEmptyList() {
setupAppSettingsWithToken("");
List<GraphQLResponse.Hit> results = searchService.searchBooks("test query");
assertThat(results).isEmpty();
}
}
@Nested
@DisplayName("Search Parameter Tests")
class SearchParameterTests {
@Test
@DisplayName("Default per_page should be 10")
void defaultPerPage_is10() {
assertThat(HardcoverBookSearchService.DEFAULT_PER_PAGE).isEqualTo(10);
}
@Test
@DisplayName("searchBooks with perPage should respect the parameter")
void searchBooks_withPerPage_respectsParameter() {
setupAppSettingsWithToken(null); // Will return empty but logic is tested
List<GraphQLResponse.Hit> results = searchService.searchBooks("test", 50);
assertThat(results).isEmpty();
}
}
@Nested
@DisplayName("fetchBookDetails Tests")
class FetchBookDetailsTests {
@Test
@DisplayName("Should return null when API token is not set")
void fetchBookDetails_noToken_returnsNull() {
setupAppSettingsWithToken(null);
HardcoverBookDetails result = searchService.fetchBookDetails(12345);
assertThat(result).isNull();
}
@Test
@DisplayName("Should return null when API token is empty")
void fetchBookDetails_emptyToken_returnsNull() {
setupAppSettingsWithToken("");
HardcoverBookDetails result = searchService.fetchBookDetails(12345);
assertThat(result).isNull();
}
}
private void setupAppSettingsWithToken(String token) {
AppSettings appSettings = new AppSettings();
MetadataProviderSettings providerSettings = new MetadataProviderSettings();
MetadataProviderSettings.Hardcover hardcover = new MetadataProviderSettings.Hardcover();
hardcover.setApiKey(token);
providerSettings.setHardcover(hardcover);
appSettings.setMetadataProviderSettings(providerSettings);
when(appSettingService.getAppSettings()).thenReturn(appSettings);
}
}
@@ -0,0 +1,258 @@
package com.adityachandel.booklore.service.metadata.parser.hardcover;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
class HardcoverMoodFilterTest {
@Test
@DisplayName("filterBasicMoods should return empty set for null input")
void filterBasicMoods_nullInput_returnsEmptySet() {
Set<String> result = HardcoverMoodFilter.filterBasicMoods(null);
assertThat(result).isEmpty();
}
@Test
@DisplayName("filterBasicMoods should return empty set for empty list")
void filterBasicMoods_emptyList_returnsEmptySet() {
Set<String> result = HardcoverMoodFilter.filterBasicMoods(Collections.emptyList());
assertThat(result).isEmpty();
}
@Test
@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");
}
@Test
@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");
}
@Test
@DisplayName("filterBasicMoods should limit results to MAX_MOODS")
void filterBasicMoods_tooManyMoods_limitsToMax() {
List<String> moods = List.of(
"funny", "sad", "dark", "emotional", "tense",
"hopeful", "romantic", "scary", "mysterious", "reflective"
);
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
assertThat(result).hasSize(HardcoverMoodFilter.MAX_MOODS);
}
@Test
@DisplayName("filterBasicMoods should handle null entries in list")
void filterBasicMoods_nullEntries_ignoresNulls() {
List<String> moods = new ArrayList<>();
moods.add("funny");
moods.add(null);
moods.add("sad");
moods.add(null);
Set<String> result = HardcoverMoodFilter.filterBasicMoods(moods);
assertThat(result).containsExactlyInAnyOrder("funny", "sad");
}
@Test
@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);
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<>();
cachedTags.put("Genre", List.of(createCachedTag("Fiction", 10)));
Set<String> result = HardcoverMoodFilter.filterMoodsWithCounts(cachedTags);
assertThat(result).isEmpty();
}
@Test
@DisplayName("filterMoodsWithCounts should filter out low-vote moods")
void filterMoodsWithCounts_mixedVotes_filtersLowVotes() {
// Simulating "All Quiet on the Western Front" scenario
// "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<>();
cachedTags.put("Mood", List.of(
createCachedTag("sad", 17),
createCachedTag("dark", 16),
createCachedTag("emotional", 10),
createCachedTag("funny", 4), // Low relative to "sad"
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
assertThat(result).doesNotContain("hopeful", "scary");
}
@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<>();
// 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<>();
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");
}
@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);
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");
}
@Test
@DisplayName("filterMoodsWithCounts should return empty when all votes are zero")
void filterMoodsWithCounts_allZeroVotes_returnsEmpty() {
Map<String, List<HardcoverBookDetails.CachedTag>> 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<>();
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");
}
@Test
@DisplayName("filterTagsWithCounts should filter tags with low votes")
void filterTagsWithCounts_mixedVotes_filtersLowVotes() {
Map<String, List<HardcoverBookDetails.CachedTag>> 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");
}
@Test
@DisplayName("normalizeMood should return null for null input")
void normalizeMood_nullInput_returnsNull() {
String result = HardcoverMoodFilter.normalizeMood(null);
assertThat(result).isNull();
}
@Test
@DisplayName("normalizeMood should lowercase and trim")
void normalizeMood_mixedCaseWithWhitespace_normalizes() {
String result = HardcoverMoodFilter.normalizeMood(" FuNnY ");
assertThat(result).isEqualTo("funny");
}
@Test
@DisplayName("All recognized moods should be in the set")
void recognizedMoods_containsExpectedMoods() {
assertThat(HardcoverMoodFilter.RECOGNIZED_MOODS)
.contains("adventurous", "challenging", "dark", "emotional", "funny",
"hopeful", "informative", "inspiring", "lighthearted", "mysterious",
"reflective", "relaxing", "romantic", "sad", "scary", "tense");
}
/**
* Helper method to create a CachedTag for testing.
*/
private HardcoverBookDetails.CachedTag createCachedTag(String tag, Integer count) {
HardcoverBookDetails.CachedTag cachedTag = new HardcoverBookDetails.CachedTag();
cachedTag.setTag(tag);
cachedTag.setCount(count);
return cachedTag;
}
}