feat(metadata): initial implementation of OpenLibrary source (#1764)
This commit is contained in:
+205
@@ -0,0 +1,205 @@
|
||||
|
||||
package org.booklore.service.metadata.parser;
|
||||
|
||||
import org.booklore.model.dto.Book;
|
||||
import org.booklore.model.dto.BookMetadata;
|
||||
import org.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import org.booklore.service.SleepService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class OpenLibraryParserTest {
|
||||
@Mock
|
||||
private HttpClient httpClient;
|
||||
|
||||
@Mock
|
||||
private SleepService sleepService;
|
||||
|
||||
private OpenLibraryParser parser;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
parser = new OpenLibraryParser(
|
||||
httpClient,
|
||||
new ObjectMapper(),
|
||||
sleepService
|
||||
);
|
||||
}
|
||||
|
||||
private String readFixture(String fixtureName) throws IOException {
|
||||
String filename = Paths.get("openlibrary", fixtureName + ".fixture").toString();
|
||||
|
||||
try (InputStream is = getClass().getClassLoader().getResourceAsStream(filename)) {
|
||||
assert is != null;
|
||||
|
||||
return new String(is.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private HttpResponse<InputStream> getMockResponse(int statusCode, String response) {
|
||||
HttpResponse<InputStream> httpResponse = (HttpResponse<InputStream>) mock(HttpResponse.class);
|
||||
|
||||
when(httpResponse.statusCode()).thenReturn(statusCode);
|
||||
|
||||
if (response != null) {
|
||||
when(httpResponse.body()).thenAnswer(
|
||||
(_) -> new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8))
|
||||
);
|
||||
}
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
private void mockHttpClientResponse(String urlPrefix, int statusCode, String response) throws Exception {
|
||||
when(
|
||||
httpClient.<String>send(
|
||||
argThat(r -> r != null && r.uri().toString().startsWith(urlPrefix)),
|
||||
any()
|
||||
)
|
||||
).thenAnswer((_) -> getMockResponse(statusCode, response));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFetchMetadata_EmptyQuery() {
|
||||
// Given
|
||||
Book book = Book.builder()
|
||||
.title("Test Book")
|
||||
.build();
|
||||
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.build();
|
||||
// Empty query - no title or ISBN
|
||||
|
||||
// When
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
// Then
|
||||
assertThat(results).isNotNull();
|
||||
assertThat(results).as("Should return empty list when query is empty").isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFetchMetadata_parsesBook() throws Exception {
|
||||
// Given
|
||||
Book book = Book.builder()
|
||||
.title("A Clockwork Orange")
|
||||
.build();
|
||||
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("A Clockwork Orange")
|
||||
.author("Anthony Burgess")
|
||||
.build();
|
||||
|
||||
// Two expected URLs
|
||||
mockHttpClientResponse("https://openlibrary.org/search.json", 200, readFixture("example-search.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/works/OL261794W.json", 200, readFixture("example-work.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/books/OL27284158M.json", 200, readFixture("example-edition.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/authors/OL142238A.json", 200, readFixture("example-author.json"));
|
||||
|
||||
// When
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
// Then
|
||||
assertThat(results).isNotNull();
|
||||
assertThat(results).as("Should return results for real book").isNotEmpty();
|
||||
|
||||
BookMetadata result = results.getFirst();
|
||||
assertThat(result.getTitle()).isEqualTo("A Clockwork Orange");
|
||||
assertThat(result.getIsbn10()).isEqualTo("1856132668");
|
||||
assertThat(result.getIsbn13()).isEqualTo("9781856132664");
|
||||
assertThat(result.getGoodreadsId()).isEqualTo("59769676");
|
||||
assertThat(result.getAuthors()).isNotNull();
|
||||
assertThat(result.getAuthors()).hasSize(1);
|
||||
assertThat(result.getAuthors().getFirst()).isEqualTo("Anthony Burgess");
|
||||
|
||||
// The description is very long, but we need to make sure we're in the right ballpark.
|
||||
assertThat(result.getDescription()).startsWith("A Clockwork Orange is a dystopian satirical black comedy novel");
|
||||
assertThat(result.getDescription()).hasSize(1307);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFetchMetadata_parsesBookWithComplexDescriptionAndSeries() throws Exception {
|
||||
// Given
|
||||
Book book = Book.builder()
|
||||
.title("")
|
||||
.build();
|
||||
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Lord of the Rings")
|
||||
.build();
|
||||
|
||||
// Two expected URLs
|
||||
mockHttpClientResponse("https://openlibrary.org/search.json", 200, readFixture("lotr-search.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/works/OL27448W.json", 200, readFixture("lotr-work.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/series/OL330052L.json", 200, readFixture("lotr-series.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/books/OL51711484M.json", 200, readFixture("lotr-edition.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/authors/OL26320A.json", 200, readFixture("lotr-author.json"));
|
||||
|
||||
// When
|
||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||
|
||||
// Then
|
||||
assertThat(results).isNotNull();
|
||||
assertThat(results).as("Should return results for real book").isNotEmpty();
|
||||
|
||||
BookMetadata result = results.getFirst();
|
||||
assertThat(result.getTitle()).isEqualTo("The Lord of the Rings");
|
||||
assertThat(result.getIsbn10()).isEqualTo("0618343997");
|
||||
assertThat(result.getIsbn13()).isNull();
|
||||
assertThat(result.getGoodreadsId()).isNull();
|
||||
assertThat(result.getAuthors()).isNotNull();
|
||||
assertThat(result.getAuthors()).hasSize(1);
|
||||
assertThat(result.getAuthors().getFirst()).isEqualTo("J.R.R. Tolkien");
|
||||
|
||||
assertThat(result.getSeriesName()).isEqualTo("The Lord of the Rings");
|
||||
assertThat(result.getSeriesNumber()).isEqualTo(1);
|
||||
assertThat(result.getSeriesTotal()).isEqualTo(3);
|
||||
|
||||
// The description is very long, but we need to make sure we're in the right ballpark.
|
||||
assertThat(result.getDescription()).startsWith("Originally published from 1954 through 1956");
|
||||
assertThat(result.getDescription()).hasSize(2137);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFetchMetadata_appliesRateLimit() throws Exception {
|
||||
// Given
|
||||
Book book = Book.builder()
|
||||
.title("")
|
||||
.build();
|
||||
|
||||
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||
.title("Lord of the Rings")
|
||||
.build();
|
||||
|
||||
// Two expected URLs
|
||||
mockHttpClientResponse("https://openlibrary.org/search.json", 200, readFixture("lotr-search.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/works/OL27448W.json", 200, readFixture("lotr-work.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/series/OL330052L.json", 200, readFixture("lotr-series.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/books/OL51711484M.json", 200, readFixture("lotr-edition.json"));
|
||||
mockHttpClientResponse("https://openlibrary.org/authors/OL26320A.json", 200, readFixture("lotr-author.json"));
|
||||
|
||||
for (int i = 0; i < 160; i++) {
|
||||
parser.fetchMetadata(book, request);
|
||||
}
|
||||
|
||||
verify(sleepService, times(4)).sleep(anyLong());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"source_records": ["amazon:0671625276", "bwb:9780486820729", "bwb:9780099778806", "bwb:9780099442592", "promise:bwb_daily_pallets_2022-07-11", "promise:bwb_daily_pallets_2022-08-30", "promise:bwb_daily_pallets_2022-10-14:KR-427-373", "promise:bwb_daily_pallets_2021-03-30", "promise:bwb_daily_pallets_2020-11-26", "promise:bwb_daily_pallets_2020-11-13", "amazon:8476698127", "amazon:8389640724", "promise:bwb_daily_pallets_2023-05-16:W3-CPM-838", "promise:bwb_daily_pallets_2023-05-22:692-ABA-806"], "bio": "John Anthony Burgess Wilson, who published under the name Anthony Burgess, was an English writer and composer.\r\n\r\nAlthough Burgess was primarily a comic writer, his dystopian satire *A Clockwork Orange* remains his best-known novel. In 1971, it was adapted into a controversial film by Stanley Kubrick, which Burgess said was chiefly responsible for the popularity of the book. Burgess produced numerous other novels, including the Enderby quartet, and Earthly Powers. He wrote librettos and screenplays, including the 1977 television mini-series Jesus of Nazareth. He worked as a literary critic for several publications, including The Observer and The Guardian, and wrote studies of classic writers, notably James Joyce. A versatile linguist, Burgess lectured in phonetics, and translated Cyrano de Bergerac, Oedipus Rex, and the opera Carmen, among others.\r\n\r\nBurgess also composed over 250 musical works; he considered himself as much a composer as an author, although he achieved considerably more success in writing.", "birth_date": "25 February 1917", "photos": [7277111, 14431059, -1], "death_date": "22 November 1993", "personal_name": "Burgess, Anthony", "links": [{"title": "VIAF", "url": "https://viaf.org/viaf/317283205", "type": {"key": "/type/link"}}, {"title": "ISNI", "url": "http://isni.org/isni/0000000456193171", "type": {"key": "/type/link"}}, {"title": "Wikidata", "url": "https://www.wikidata.org/wiki/Q217619", "type": {"key": "/type/link"}}, {"title": "The International Anthony Burgess Foundation", "url": "https://www.anthonyburgess.org/", "type": {"key": "/type/link"}}], "remote_ids": {"viaf": "71388189", "wikidata": "Q217619", "isni": "0000000121385921"}, "type": {"key": "/type/author"}, "alternate_names": ["Burgess, Anthony", "anthony-burgess", "Anthony BURGESS", "John Anthony Burgess Wilson", "ANTHONY BURGESS", "A. Burgess", "Antony Burgess", "Joseph Kell", "John Burgess Wilson", "A. BURGESS", "anthony burgess", "BURGESS,ANTHONY.", "Burgess Anthony", "\u042d\u043d\u0442\u043e\u043d\u0438 \u0411\u0451\u0440\u0434\u0436\u0435\u0441\u0441"], "name": "Anthony Burgess", "key": "/authors/OL142238A", "latest_revision": 17, "revision": 17, "created": {"type": "/type/datetime", "value": "2008-04-01T03:28:50.625462"}, "last_modified": {"type": "/type/datetime", "value": "2025-03-25T01:01:48.526462"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"publishers": ["Penguin Classics"], "identifiers": {"amazon": ["1856132668"], "goodreads": ["59769676"]}, "source_records": ["amazon:1856132668", "promise:bwb_daily_pallets_2021-01-27"], "title": "A Clockwork Orange", "number_of_pages": 141, "covers": [12393415], "physical_format": "paperback", "full_title": "A Clockwork Orange", "publish_date": "2000", "key": "/books/OL27284158M", "authors": [{"key": "/authors/OL1607339A"}], "works": [{"key": "/works/OL261794W"}], "type": {"key": "/type/edition"}, "publish_places": ["London"], "languages": [{"key": "/languages/eng"}], "pagination": "xxiii, 140p.", "copyright_date": "1996", "edition_name": "reprint 1", "description": "Fifteen-year-old Alex doesn't just like ultra-violence - he also enjoys rape, drugs and Beethoven's Ninth. He and his gang rampage through a dystopian future, hunting for terrible thrills. But when Alex finds himself at the mercy of the state and subject to the ministrations of Dr Brodsky, the government psychologist, he discovers that fun is no longer the order of the day ...\r\n\r\nThe basis for one of the most notorious films ever made, A Clockwork Orange is both a virtuoso performance from an electrifying prose stylist and a serious exploration of the morality of free will.\r\n--back cover", "local_id": ["urn:bwbsku:KP-003-259"], "ocaid": "isbn_9781856132664", "isbn_10": ["1856132668"], "isbn_13": ["9781856132664"], "latest_revision": 14, "revision": 14, "created": {"type": "/type/datetime", "value": "2019-08-26T01:59:15.196224"}, "last_modified": {"type": "/type/datetime", "value": "2025-11-15T21:27:51.839463"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":75,"start":0,"numFoundExact":true,"num_found":75,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"title:Clockwork Orange","offset":null,"docs":[{"author_key":["OL142238A"],"key":"/works/OL261794W","editions":{"numFound":110,"start":0,"numFoundExact":true,"docs":[{"key":"/books/OL27284158M"}]}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"description": "A Clockwork Orange is a dystopian satirical black comedy novel by English writer Anthony Burgess, published in 1962. It is set in a near-future society that has a youth subculture of extreme violence. The teenage protagonist, Alex, narrates his violent exploits and his experiences with state authorities intent on reforming him. The book is partially written in a Russian-influenced argot called \"Nadsat\", which takes its name from the Russian suffix that is equivalent to '-teen' in English. According to Burgess, it was a jeu d'esprit written in just three weeks.\r\n\r\nIn 2005, A Clockwork Orange was included on Time magazine's list of the 100 best English-language novels written since 1923, and it was named by Modern Library and its readers as one of the 100 best English-language novels of the 20th century. The original manuscript of the book has been kept at McMaster University's William Ready Division of Archives and Research Collections in Hamilton, Ontario, Canada since the institution purchased the documents in 1971. It is considered one of the most influential dystopian books.\r\n\r\n----------\t\t\r\nAlso contained in:\t\t\r\n\r\n[A Clockwork Orange and Honey for the Bears](https://openlibrary.org/works/OL23787405W)\r\n[A Clockwork Orange / The Wanting Seed](https://openlibrary.org/works/OL17306508W)", "first_publish_date": "1972", "title": "A Clockwork Orange", "covers": [13151224, 13950735, 13950736, 12338379, 14122257, 14122256, 11943379, 12269033, 14121728], "first_sentence": {"type": "/type/text", "value": "'WHAT'S it going to be then, eh?'"}, "excerpts": [{"excerpt": "\u2018What\u2019s it going to be then, eh?\u2019", "comment": "first sentence", "author": {"key": "/people/seabelis"}}], "key": "/works/OL261794W", "authors": [{"author": {"key": "/authors/OL142238A"}, "type": {"key": "/type/author_role"}}], "dewey_number": ["823.914"], "type": {"key": "/type/work"}, "links": [{"title": "A Clockwork Orange - The International Anthony Burgess Foundation", "url": "https://www.anthonyburgess.org/a-clockwork-orange/", "type": {"key": "/type/link"}}, {"title": "A Clockwork Orange (novel) - Wikipedia", "url": "https://en.wikipedia.org/wiki/A_Clockwork_Orange_(novel)", "type": {"key": "/type/link"}}, {"title": "The 100 best novels: No 82 \u2013 A Clockwork Orange by Anthony Burgess (1962)", "url": "https://www.theguardian.com/books/2015/apr/13/100-best-novels-clockwork-orange-anthony-burgess", "type": {"key": "/type/link"}}, {"title": "The Shock of the New \u2018A Clockwork Orange\u2019 at 50", "url": "https://www.nytimes.com/2012/09/02/books/review/a-clockwork-orange-at-50.html", "type": {"key": "/type/link"}}, {"title": "A Clockwork Orange | Summary, Analysis, & Facts | Britannica.com", "url": "https://www.britannica.com/topic/A-Clockwork-Orange-novel", "type": {"key": "/type/link"}}, {"title": "thegreatestbooks.org/items/20", "url": "https://thegreatestbooks.org/items/20", "type": {"key": "/type/link"}}], "subject_places": ["England", "Korova Milk Bar"], "subject_people": ["Ludwig van Beethoven", "Alex", "George", "Pet", "Dim", "P.R. Deltoid", "Prison Chaplain", "Billyboy", "Prison Governor", "Minister of the Interior", "Dr. Branom", "Dr. Brodsky", "F. Alexander", "Cat Woman", "Stanley Kubrick", "Anthony Burgess (1917-1993)"], "subjects": ["bible", "aversion therapy", "unintended consequences", "Beethoven's Fifth Symphony", "gang rape", "psychiatric hospitals", "maturity", "metanoia", "assault", "joyriding", "rape", "metafiction", "orgasm", "novella", "antisocial personality disorder", "classical music", "black comedy", "argot", "Nadsat", "dystopias", "satire", "literature", "Juvenile delinquents", "Science fiction", "Rehabilitation", "Fiction", "Teenage boys", "Criminals", "S\u00e1tira", "Muchachos adolescentes", "Criticism and interpretation", "Criminales", "English Authors", "Open Library Staff Picks", "Violence", "Slang language", "Gangs", "Ciencia-ficci\u00f3n", "Social conditions", "Ficci\u00f3n", "Behavior modification", "Long Now Manual for Civilization", "Juvenile delinquency", "Brainwashing", "Fiction, satire", "Fiction, dystopian", "Fiction, science fiction, general", "British and irish fiction (fictional works by one author)", "British and irish drama (dramatic works by one author)", "Kubrick, stanley, 1928-1999", "Burgess, anthony, 1917-1993", "Clockwork orange (Motion picture)", "English literature", "Juvenile delinquents in fiction", "Adventure stories", "Roman d'aventures", "D\u00e9linquance juv\u00e9nile", "Romans, nouvelles", "Jeunes d\u00e9linquants", "R\u00e9habilitation", "English Satire"], "latest_revision": 25, "revision": 25, "created": {"type": "/type/datetime", "value": "2009-10-24T07:26:31.097043"}, "last_modified": {"type": "/type/datetime", "value": "2026-01-01T17:25:03.972618"}}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"works": [{"key": "/works/OL27448W"}], "title": "The Lord of the Rings", "publishers": ["Houghton Mifflin Company"], "publish_date": "2003", "key": "/books/OL51711484M", "type": {"key": "/type/edition"}, "identifiers": {}, "isbn_10": ["0618343997"], "ocaid": "lordofrings00tolk_5", "classifications": {}, "publish_places": ["Boston"], "copyright_date": "2003", "edition_name": "Movie tie-in edition (1)", "languages": [{"key": "/languages/eng"}], "physical_format": "hardcover", "pagination": "1137p.", "covers": [15131000], "latest_revision": 5, "revision": 5, "created": {"type": "/type/datetime", "value": "2024-05-17T13:51:26.585267"}, "last_modified": {"type": "/type/datetime", "value": "2025-10-10T23:14:39.486304"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"numFound":784,"start":0,"numFoundExact":true,"num_found":784,"documentation_url":"https://openlibrary.org/dev/docs/api/search","q":"title:Lord of the Rings","offset":null,"docs":[{"author_key":["OL26320A"],"key":"/works/OL27448W","editions":{"numFound":207,"start":0,"numFoundExact":true,"docs":[{"key":"/books/OL51711484M"}]}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"links": {"self": "/series/OL330052L", "seeds": "/series/OL330052L/seeds"}, "name": "The Lord of the Rings", "type": {"key": "/series/OL330052L"}, "description": null, "seed_count": 4, "meta": {"revision": 1, "created": "2026-03-30T18:09:40.112603", "last_modified": "2026-03-30T18:09:40.112603"}}
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user