From c6d386baebfe744a9a337dc44666e13479bba4c9 Mon Sep 17 00:00:00 2001 From: Conor Egan <68134729+c-eg@users.noreply.github.com> Date: Sat, 13 Jun 2026 11:20:48 +0100 Subject: [PATCH 1/4] Refactor request logic (#332) * refactor request logic * move the retry logic to the http client * small cleanup + tests * remove invalid comment * add integration test support + IT for TmdbHttpClient * update comment --- README.md | 44 ++--- build.gradle.kts | 21 ++- .../movito/themoviedbapi/AbstractTmdbApi.java | 163 ------------------ .../movito/themoviedbapi/TmdbAccount.java | 31 ++-- .../info/movito/themoviedbapi/TmdbApi.java | 72 ++++---- .../themoviedbapi/TmdbAuthentication.java | 21 ++- .../themoviedbapi/TmdbCertifications.java | 13 +- .../movito/themoviedbapi/TmdbChanges.java | 15 +- .../movito/themoviedbapi/TmdbCollections.java | 15 +- .../movito/themoviedbapi/TmdbCompanies.java | 15 +- .../themoviedbapi/TmdbConfiguration.java | 21 ++- .../movito/themoviedbapi/TmdbDiscover.java | 13 +- .../info/movito/themoviedbapi/TmdbFind.java | 11 +- .../info/movito/themoviedbapi/TmdbGenre.java | 13 +- .../themoviedbapi/TmdbGuestSessions.java | 15 +- .../movito/themoviedbapi/TmdbKeywords.java | 13 +- .../info/movito/themoviedbapi/TmdbLists.java | 23 +-- .../movito/themoviedbapi/TmdbMovieLists.java | 17 +- .../info/movito/themoviedbapi/TmdbMovies.java | 47 ++--- .../movito/themoviedbapi/TmdbNetworks.java | 15 +- .../info/movito/themoviedbapi/TmdbPeople.java | 27 +-- .../movito/themoviedbapi/TmdbPeopleLists.java | 11 +- .../movito/themoviedbapi/TmdbReviews.java | 11 +- .../info/movito/themoviedbapi/TmdbSearch.java | 23 +-- .../movito/themoviedbapi/TmdbTrending.java | 17 +- .../themoviedbapi/TmdbTvEpisodeGroups.java | 11 +- .../movito/themoviedbapi/TmdbTvEpisodes.java | 29 ++-- .../movito/themoviedbapi/TmdbTvSeasons.java | 29 ++-- .../movito/themoviedbapi/TmdbTvSeries.java | 53 +++--- .../themoviedbapi/TmdbTvSeriesLists.java | 17 +- .../themoviedbapi/TmdbWatchProviders.java | 15 +- .../movito/themoviedbapi/tools/ApiUrl.java | 17 +- .../themoviedbapi/tools/TmdbApiClient.java | 101 +++++++++++ .../themoviedbapi/tools/TmdbHttpClient.java | 65 ++++++- .../themoviedbapi/tools/TmdbRequest.java | 30 ++++ .../tools/TmdbRequestExecutor.java | 15 ++ .../themoviedbapi/tools/TmdbResponse.java | 16 ++ .../themoviedbapi/tools/TmdbResponseCode.java | 133 +++++--------- .../themoviedbapi/tools/TmdbUrlReader.java | 19 -- .../discover/DiscoverParamBuilder.java | 10 +- .../themoviedbapi/AbstractTmdbApiTest.java | 18 +- .../movito/themoviedbapi/TmdbAccountTest.java | 28 +-- .../themoviedbapi/TmdbAuthenticationTest.java | 21 ++- .../themoviedbapi/TmdbCertificationsTest.java | 6 +- .../movito/themoviedbapi/TmdbChangesTest.java | 8 +- .../themoviedbapi/TmdbCollectionsTest.java | 10 +- .../themoviedbapi/TmdbCompaniesTest.java | 8 +- .../themoviedbapi/TmdbConfigurationTest.java | 14 +- .../themoviedbapi/TmdbDiscoverTest.java | 10 +- .../movito/themoviedbapi/TmdbFindTest.java | 27 ++- .../movito/themoviedbapi/TmdbGenresTest.java | 6 +- .../themoviedbapi/TmdbGuestSessionsTest.java | 8 +- .../themoviedbapi/TmdbKeywordsTest.java | 4 +- .../movito/themoviedbapi/TmdbListsTest.java | 16 +- .../themoviedbapi/TmdbMovieListsTest.java | 10 +- .../movito/themoviedbapi/TmdbMoviesTest.java | 42 ++--- .../themoviedbapi/TmdbNetworksTest.java | 8 +- .../themoviedbapi/TmdbPeopleListsTest.java | 4 +- .../movito/themoviedbapi/TmdbPeopleTest.java | 22 +-- .../movito/themoviedbapi/TmdbReviewsTest.java | 4 +- .../movito/themoviedbapi/TmdbSearchTest.java | 16 +- .../themoviedbapi/TmdbTrendingTest.java | 10 +- .../TmdbTvEpisodeGroupsTest.java | 6 +- .../themoviedbapi/TmdbTvEpisodesTest.java | 24 +-- .../themoviedbapi/TmdbTvSeasonsTest.java | 24 +-- .../themoviedbapi/TmdbTvSeriesListsTest.java | 10 +- .../themoviedbapi/TmdbTvSeriesTest.java | 48 +++--- .../themoviedbapi/TmdbWatchProvidersTest.java | 8 +- .../testutil/IntegrationTest.java | 19 ++ .../tools/TmdbApiClientTest.java | 150 ++++++++++++++++ .../themoviedbapi/tools/TmdbHttpClientIT.java | 158 +++++++++++++++++ .../tools/TmdbHttpClientTest.java | 70 ++++++-- .../themoviedbapi/tools/TmdbRequestTest.java | 75 ++++++++ .../themoviedbapi/tools/TmdbResponseTest.java | 55 ++++++ 74 files changed, 1416 insertions(+), 778 deletions(-) delete mode 100644 src/main/java/info/movito/themoviedbapi/AbstractTmdbApi.java create mode 100644 src/main/java/info/movito/themoviedbapi/tools/TmdbApiClient.java create mode 100644 src/main/java/info/movito/themoviedbapi/tools/TmdbRequest.java create mode 100644 src/main/java/info/movito/themoviedbapi/tools/TmdbRequestExecutor.java create mode 100644 src/main/java/info/movito/themoviedbapi/tools/TmdbResponse.java delete mode 100644 src/main/java/info/movito/themoviedbapi/tools/TmdbUrlReader.java create mode 100644 src/test/java/info/movito/themoviedbapi/testutil/IntegrationTest.java create mode 100644 src/test/java/info/movito/themoviedbapi/tools/TmdbApiClientTest.java create mode 100644 src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientIT.java create mode 100644 src/test/java/info/movito/themoviedbapi/tools/TmdbRequestTest.java create mode 100644 src/test/java/info/movito/themoviedbapi/tools/TmdbResponseTest.java diff --git a/README.md b/README.md index c7259ea9..0ca29bc0 100644 --- a/README.md +++ b/README.md @@ -9,30 +9,7 @@ The wrapper implements most, if not all, of the JSON API. However, because the A not be implemented, or current functionality may break. Please point this out by submitting an issue, or even better, just send us a pull request! -It's available via [Maven Central](https://central.sonatype.com/artifact/uk.co.conoregan/themoviedbapi). Just add it as dependency to your -project. - -
-Maven - -```xml - - uk.co.conoregan - themoviedbapi - {version} - -``` -
- -
-Gradle (Kotlin) - -```kotlin -dependencies { - implementation("uk.co.conoregan:themoviedbapi:{version}") -} -``` -
+It's available via [Maven Central](https://central.sonatype.com/artifact/uk.co.conoregan/themoviedbapi). Just add it as dependency to your project. ## Usage To register for a TMdB API key, click the [API link](https://www.themoviedb.org/settings/api) from within your account settings page. There are two types of API keys currently provided by TMdB, please ensure you are using the `API Read Access Token` key. @@ -42,6 +19,9 @@ With this you can instantiate `info.movito.themoviedbapi.TmdbApi`, which has get TmdbApi tmdbApi = new TmdbApi(""); ``` +By default this uses the library's built-in HTTP client. If you would rather plug in your own, see +[Using your own HTTP client](#using-your-own-http-client). + ### Examples #### Get movie details ```java @@ -78,7 +58,7 @@ MovieDb movie = tmdbMovies.getDetails(5353, "en-US", MovieAppendToResponse.value To find all methods that use append to response, see the `info.movito.themoviedbapi.tools.appendtoresponse.AppendToResponse` interface implementations. -### Exception Handling +### Exception handling Every API method can throw a `info.movito.themoviedbapi.tools.TmdbException` if the request fails for any reason. You should catch this exception and handle it appropriately. @@ -106,6 +86,20 @@ catch (TmdbException exception) { We chose to throw exceptions rather than returning `null`, so you have more control over what you do with each failure case. E.g. with the example above, you may want to display an error message to the user about failing authentication. +### Using your own HTTP client +By default, `TmdbApi` uses the built-in `info.movito.themoviedbapi.tools.TmdbHttpClient`, which is backed by the JDK's +`java.net.http.HttpClient`. If you would rather use a different HTTP client, you can provide your own +implementation of the `info.movito.themoviedbapi.tools.TmdbRequestExecutor` interface. + +Your implementation only has to make the call and hand back the raw response. If the request fails (e.g. an `IOException`), wrap it in a +`info.movito.themoviedbapi.tools.TmdbException`. Interpreting TMdB status codes (e.g. mapping unsuccessful responses to exceptions) is handled by the library on top of your executor, so +you do not need to deal with that (see `info.movito.themoviedbapi.tools.TmdbApiClient` for more information). + +Then, simply pass your implementation to `TmdbApi` instead of the API key: +```java +TmdbApi tmdbApi = new TmdbApi(new CustomHttpClient()); +``` + ## Project Logging This project uses [SLF4J](http://www.slf4j.org) to abstract the logging in the project. To use the logging in your own diff --git a/build.gradle.kts b/build.gradle.kts index 2e484bea..4e44ac35 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -28,6 +28,8 @@ dependencies { testImplementation("org.mockito:mockito-core") testImplementation("org.mockito:mockito-junit-jupiter") + testImplementation("org.wiremock:wiremock:3.13.2") + // util compileOnly("org.projectlombok:lombok:1.18.46") annotationProcessor("org.projectlombok:lombok:1.18.46") @@ -49,7 +51,24 @@ java { } tasks.test { - useJUnitPlatform() + useJUnitPlatform { + excludeTags("integration") + } +} + +tasks.register("integrationTest") { + description = "Runs integration tests (tagged with \"integration\")." + group = "verification" + useJUnitPlatform { + includeTags("integration") + } + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + shouldRunAfter(tasks.test) +} + +tasks.check { + dependsOn("integrationTest") } checkstyle { diff --git a/src/main/java/info/movito/themoviedbapi/AbstractTmdbApi.java b/src/main/java/info/movito/themoviedbapi/AbstractTmdbApi.java deleted file mode 100644 index b2bab4bf..00000000 --- a/src/main/java/info/movito/themoviedbapi/AbstractTmdbApi.java +++ /dev/null @@ -1,163 +0,0 @@ -package info.movito.themoviedbapi; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectReader; -import info.movito.themoviedbapi.model.core.responses.ResponseStatus; -import info.movito.themoviedbapi.model.core.responses.TmdbResponseException; -import info.movito.themoviedbapi.tools.ApiUrl; -import info.movito.themoviedbapi.tools.RequestType; -import info.movito.themoviedbapi.tools.TmdbException; -import info.movito.themoviedbapi.tools.TmdbResponseCode; -import info.movito.themoviedbapi.util.JsonUtil; -import lombok.extern.slf4j.Slf4j; - -import static info.movito.themoviedbapi.tools.TmdbResponseCode.REQUEST_LIMIT_EXCEEDED; - -/** - * Class to be inherited by a TmdbApi class. - */ -@Slf4j -public abstract class AbstractTmdbApi { - public static final String PARAM_PAGE = "page"; - - public static final String PARAM_LANGUAGE = "language"; - - public static final String PARAM_ADULT = "include_adult"; - - public static final String PARAM_SORT_BY = "sort_by"; - - private static final ObjectReader RESPONSE_STATUS_READER = JsonUtil.OBJECT_MAPPER.readerFor(ResponseStatus.class); - - private final TmdbApi tmdbApi; - - AbstractTmdbApi(TmdbApi tmdbApi) { - this.tmdbApi = tmdbApi; - } - - /** - * Maps a json result to a class. - * - * @param apiUrl the api url to map - * @param clazz the class to map to - * @param the type of class to map to - * @return the mapped class - */ - protected T mapJsonResult(ApiUrl apiUrl, Class clazz) throws TmdbException { - return mapJsonResult(apiUrl, null, clazz); - } - - /** - * Maps a json result to a class. - * - * @param apiUrl the api url to map - * @param resultClass the class to map to - * @param the type of class to map to - * @return the mapped class - */ - protected T mapJsonResult(ApiUrl apiUrl, TypeReference resultClass) throws TmdbException { - return mapJsonResult(apiUrl, null, resultClass); - } - - /** - * Maps a json result to a class. - * - * @param apiUrl the api url to map - * @param jsonBody the json body - * @param clazz the class to map to - * @param the type of class to map to - * @return the mapped class. - */ - protected T mapJsonResult(ApiUrl apiUrl, String jsonBody, Class clazz) throws TmdbException { - return mapJsonResult(apiUrl, jsonBody, RequestType.GET, clazz); - } - - /** - * Maps a json result to a class. - * - * @param apiUrl the api url to map - * @param jsonBody the json body - * @param resultClass the class to map to - * @param the type of class to map to - * @return the mapped class - */ - protected T mapJsonResult(ApiUrl apiUrl, String jsonBody, TypeReference resultClass) throws TmdbException { - return mapJsonResult(apiUrl, jsonBody, RequestType.GET, resultClass); - } - - /** - * Maps a json result to a class. - * - * @param apiUrl the api url to map - * @param jsonBody the json body - * @param requestType the type of request - * @param clazz the class to map to - * @param the type of class to map to - * @return the mapped class. - */ - protected T mapJsonResult(ApiUrl apiUrl, String jsonBody, RequestType requestType, Class clazz) throws TmdbException { - return mapJsonResult(apiUrl, jsonBody, requestType, JsonUtil.OBJECT_MAPPER.readerFor(clazz)); - } - - /** - * Maps a json result to a class. - * - * @param apiUrl the api url to map - * @param jsonBody the json body - * @param requestType the type of request - * @param resultClass the class to map to - * @param the type of class to map to - * @return the mapped class. - */ - protected T mapJsonResult(ApiUrl apiUrl, String jsonBody, RequestType requestType, TypeReference resultClass) - throws TmdbException { - return mapJsonResult(apiUrl, jsonBody, requestType, JsonUtil.OBJECT_MAPPER.readerFor(resultClass)); - } - - /** - * Maps a json result to a class. - * - * @param apiUrl the api url to map - * @param jsonBody the json body - * @param requestType the type of request - * @param objectReader the object reader - * @param the type of class to map to - * @return the mapped class. - */ - private T mapJsonResult(ApiUrl apiUrl, String jsonBody, RequestType requestType, ObjectReader objectReader) throws TmdbException { - String jsonResponse = tmdbApi.getTmdbUrlReader().readUrl(apiUrl.buildUrl(), jsonBody, requestType); - - try { - // check if the response was successful. tmdb have their own codes for successful and unsuccessful responses. - // some 2xx codes are not successful. See: https://developer.themoviedb.org/docs/errors for more info. - ResponseStatus responseStatus = RESPONSE_STATUS_READER.readValue(jsonResponse); - TmdbResponseCode tmdbResponseCode = responseStatus.getStatusCode(); - - if (tmdbResponseCode != null) { - if (REQUEST_LIMIT_EXCEEDED == tmdbResponseCode) { - log.info("TMDB API: Request limit exceeded. Waiting 1 second before retrying."); - Thread.sleep(1000); - return mapJsonResult(apiUrl, jsonBody, requestType, objectReader); - } - else if (!tmdbResponseCode.isSuccess()) { - throw new TmdbResponseException(tmdbResponseCode); - } - } - } - catch (JsonProcessingException exception) { - // ignore, not an error - caused by RESPONSE_STATUS_READER.readValue(jsonResponse); - // this is necessary because if some requests fail (including 2xx responses), the response is a json object - } - catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new TmdbException(exception); - } - - try { - return objectReader.readValue(jsonResponse); - } - catch (JsonProcessingException exception) { - throw new TmdbException(exception); - } - } -} diff --git a/src/main/java/info/movito/themoviedbapi/TmdbAccount.java b/src/main/java/info/movito/themoviedbapi/TmdbAccount.java index 83fb2704..3d619dbb 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbAccount.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbAccount.java @@ -12,6 +12,7 @@ import info.movito.themoviedbapi.model.rated.RatedTvSeriesResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; import info.movito.themoviedbapi.tools.RequestType; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.sortby.AccountSortBy; import info.movito.themoviedbapi.util.JsonUtil; @@ -20,15 +21,17 @@ * The movie database api for accounts. See the * documentation for more info. */ -public class TmdbAccount extends AbstractTmdbApi { +public class TmdbAccount { public static final String PARAM_SESSION = "session_id"; protected static final String TMDB_METHOD_ACCOUNT = "account"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbAccount instance to call the account related TMDb API methods. */ - TmdbAccount(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbAccount(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -44,7 +47,7 @@ public Account getDetails(Integer accountId, String sessionId) throws TmdbExcept ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_ACCOUNT, accountId) .addQueryParam(PARAM_SESSION, sessionId); - return mapJsonResult(apiUrl, Account.class); + return tmdbApiClient.get(apiUrl, Account.class); } /** @@ -90,7 +93,7 @@ private ResponseStatus changeFavoriteStatus(Integer accountId, String sessionId, body.put("favorite", isFavorite); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); } /** @@ -136,7 +139,7 @@ private ResponseStatus changeWatchListStatus(Integer accountId, String sessionId body.put("watchlist", isWatchList); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); } /** @@ -159,7 +162,7 @@ public MovieResultsPage getFavoriteMovies(Integer accountId, String sessionId, S .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -182,7 +185,7 @@ public TvSeriesResultsPage getFavoriteTv(Integer accountId, String sessionId, St .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } /** @@ -200,7 +203,7 @@ public MovieListResultsPage getLists(Integer accountId, String sessionId, Intege .addQueryParam(PARAM_SESSION, sessionId) .addPage(page); - return mapJsonResult(apiUrl, MovieListResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieListResultsPage.class); } /** @@ -223,7 +226,7 @@ public RatedMovieResultsPage getRatedMovies(int accountId, String sessionId, Str .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, RatedMovieResultsPage.class); + return tmdbApiClient.get(apiUrl, RatedMovieResultsPage.class); } /** @@ -246,7 +249,7 @@ public RatedTvSeriesResultsPage getRatedTvSeries(int accountId, String sessionId .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, RatedTvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, RatedTvSeriesResultsPage.class); } /** @@ -269,7 +272,7 @@ public RatedTvEpisodeResultsPage getRatedTvEpisodes(int accountId, String sessio .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, RatedTvEpisodeResultsPage.class); + return tmdbApiClient.get(apiUrl, RatedTvEpisodeResultsPage.class); } /** @@ -292,7 +295,7 @@ public MovieResultsPage getWatchListMovies(Integer accountId, String sessionId, .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -315,7 +318,7 @@ public TvSeriesResultsPage getWatchListTvSeries(Integer accountId, String sessio .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } /** diff --git a/src/main/java/info/movito/themoviedbapi/TmdbApi.java b/src/main/java/info/movito/themoviedbapi/TmdbApi.java index 89362e64..72349b21 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbApi.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbApi.java @@ -1,22 +1,20 @@ package info.movito.themoviedbapi; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbHttpClient; -import info.movito.themoviedbapi.tools.TmdbUrlReader; -import lombok.AccessLevel; -import lombok.Getter; +import info.movito.themoviedbapi.tools.TmdbRequestExecutor; /** * The movie db api for getting started. See the * documentation for more info. * - * @author Holger Brandl. + * @author Holger Brandl, c-eg. */ public class TmdbApi { /** - * Http client to make requests to the movie database api. + * Client used by each api class to make and map requests to the movie database api. */ - @Getter(AccessLevel.PROTECTED) - private final TmdbUrlReader tmdbUrlReader; + private final TmdbApiClient tmdbApiClient; /** * Constructor. @@ -30,117 +28,117 @@ public TmdbApi(String apiKey) { /** * Constructor. * - * @param tmdbUrlReader the url reader to use + * @param requestExecutor the request executor to use */ - public TmdbApi(TmdbUrlReader tmdbUrlReader) { - this.tmdbUrlReader = tmdbUrlReader; + public TmdbApi(TmdbRequestExecutor requestExecutor) { + this.tmdbApiClient = new TmdbApiClient(requestExecutor); } public TmdbAccount getAccount() { - return new TmdbAccount(this); + return new TmdbAccount(tmdbApiClient); } public TmdbAuthentication getAuthentication() { - return new TmdbAuthentication(this); + return new TmdbAuthentication(tmdbApiClient); } public TmdbCertifications getCertifications() { - return new TmdbCertifications(this); + return new TmdbCertifications(tmdbApiClient); } public TmdbChanges getChanges() { - return new TmdbChanges(this); + return new TmdbChanges(tmdbApiClient); } public TmdbCollections getCollections() { - return new TmdbCollections(this); + return new TmdbCollections(tmdbApiClient); } public TmdbCompanies getCompanies() { - return new TmdbCompanies(this); + return new TmdbCompanies(tmdbApiClient); } public TmdbConfiguration getConfiguration() { - return new TmdbConfiguration(this); + return new TmdbConfiguration(tmdbApiClient); } public TmdbDiscover getDiscover() { - return new TmdbDiscover(this); + return new TmdbDiscover(tmdbApiClient); } public TmdbFind getFind() { - return new TmdbFind(this); + return new TmdbFind(tmdbApiClient); } public TmdbGenre getGenre() { - return new TmdbGenre(this); + return new TmdbGenre(tmdbApiClient); } public TmdbGuestSessions getGuestSessions() { - return new TmdbGuestSessions(this); + return new TmdbGuestSessions(tmdbApiClient); } public TmdbKeywords getKeywords() { - return new TmdbKeywords(this); + return new TmdbKeywords(tmdbApiClient); } public TmdbLists getLists() { - return new TmdbLists(this); + return new TmdbLists(tmdbApiClient); } public TmdbMovieLists getMovieLists() { - return new TmdbMovieLists(this); + return new TmdbMovieLists(tmdbApiClient); } public TmdbMovies getMovies() { - return new TmdbMovies(this); + return new TmdbMovies(tmdbApiClient); } public TmdbNetworks getNetworks() { - return new TmdbNetworks(this); + return new TmdbNetworks(tmdbApiClient); } public TmdbPeopleLists getPeopleLists() { - return new TmdbPeopleLists(this); + return new TmdbPeopleLists(tmdbApiClient); } public TmdbPeople getPeople() { - return new TmdbPeople(this); + return new TmdbPeople(tmdbApiClient); } public TmdbReviews getReviews() { - return new TmdbReviews(this); + return new TmdbReviews(tmdbApiClient); } public TmdbSearch getSearch() { - return new TmdbSearch(this); + return new TmdbSearch(tmdbApiClient); } public TmdbTrending getTrending() { - return new TmdbTrending(this); + return new TmdbTrending(tmdbApiClient); } public TmdbTvEpisodes getTvEpisodes() { - return new TmdbTvEpisodes(this); + return new TmdbTvEpisodes(tmdbApiClient); } public TmdbTvEpisodeGroups getTvEpisodeGroups() { - return new TmdbTvEpisodeGroups(this); + return new TmdbTvEpisodeGroups(tmdbApiClient); } public TmdbTvSeasons getTvSeasons() { - return new TmdbTvSeasons(this); + return new TmdbTvSeasons(tmdbApiClient); } public TmdbTvSeries getTvSeries() { - return new TmdbTvSeries(this); + return new TmdbTvSeries(tmdbApiClient); } public TmdbTvSeriesLists getTvSeriesLists() { - return new TmdbTvSeriesLists(this); + return new TmdbTvSeriesLists(tmdbApiClient); } public TmdbWatchProviders getWatchProviders() { - return new TmdbWatchProviders(this); + return new TmdbWatchProviders(tmdbApiClient); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbAuthentication.java b/src/main/java/info/movito/themoviedbapi/TmdbAuthentication.java index 111ffeb6..5f96c1bc 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbAuthentication.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbAuthentication.java @@ -9,6 +9,7 @@ import info.movito.themoviedbapi.model.core.responses.ResponseStatusDelete; import info.movito.themoviedbapi.tools.ApiUrl; import info.movito.themoviedbapi.tools.RequestType; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.util.JsonUtil; @@ -16,16 +17,18 @@ * The movie database api for authentication. See the * documentation for more info. */ -public class TmdbAuthentication extends AbstractTmdbApi { +public class TmdbAuthentication { protected static final String TMDB_METHOD_AUTH = "authentication"; private static final String PARAM_REQUEST_TOKEN = "request_token"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbAuthentication instance to call the authentication related TMDb API methods. */ - TmdbAuthentication(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbAuthentication(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -38,7 +41,7 @@ public class TmdbAuthentication extends AbstractTmdbApi { */ public GuestSession createGuestSession() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_AUTH, "guest_session/new"); - return mapJsonResult(apiUrl, GuestSession.class); + return tmdbApiClient.get(apiUrl, GuestSession.class); } /** @@ -53,7 +56,7 @@ public GuestSession createGuestSession() throws TmdbException { */ public RequestToken createRequestToken() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_AUTH, "token/new"); - return mapJsonResult(apiUrl, RequestToken.class); + return tmdbApiClient.get(apiUrl, RequestToken.class); } /** @@ -107,7 +110,7 @@ public RequestToken createAuthenticatedRequestToken(RequestToken token, String u body.put(PARAM_REQUEST_TOKEN, token.getRequestToken()); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, RequestToken.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, RequestToken.class); } /** @@ -130,7 +133,7 @@ public Session createSession(RequestToken token) throws TmdbException { body.put(PARAM_REQUEST_TOKEN, token.getRequestToken()); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, Session.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, Session.class); } /** @@ -153,7 +156,7 @@ public ResponseStatusDelete deleteSession(String sessionId) throws TmdbException body.put("session_id", sessionId); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.DELETE, ResponseStatusDelete.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.DELETE, ResponseStatusDelete.class); } /** @@ -166,6 +169,6 @@ public ResponseStatusDelete deleteSession(String sessionId) throws TmdbException */ public ResponseStatusAuthentication validateKey() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_AUTH); - return mapJsonResult(apiUrl, ResponseStatusAuthentication.class); + return tmdbApiClient.get(apiUrl, ResponseStatusAuthentication.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbCertifications.java b/src/main/java/info/movito/themoviedbapi/TmdbCertifications.java index 6adced06..c0588e05 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbCertifications.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbCertifications.java @@ -2,21 +2,24 @@ import info.movito.themoviedbapi.model.certifications.CertificationResults; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for certifications. See the * documentation for more info. */ -public class TmdbCertifications extends AbstractTmdbApi { +public class TmdbCertifications { protected static final String TMDB_METHOD_CERTIFICATIONS = "certification"; protected static final String TMDB_METHOD_MOVIE_CERTIFICATIONS = "movie/list"; protected static final String TMDB_METHOD_TV_CERTIFICATIONS = "tv/list"; - TmdbCertifications(TmdbApi tmdbApi) { - super(tmdbApi); + private final TmdbApiClient tmdbApiClient; + + TmdbCertifications(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -28,7 +31,7 @@ public class TmdbCertifications extends AbstractTmdbApi { */ public CertificationResults getMovieCertifications() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_CERTIFICATIONS, TMDB_METHOD_MOVIE_CERTIFICATIONS); - return mapJsonResult(apiUrl, CertificationResults.class); + return tmdbApiClient.get(apiUrl, CertificationResults.class); } /** @@ -40,6 +43,6 @@ public CertificationResults getMovieCertifications() throws TmdbException { */ public CertificationResults getTvCertifications() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_CERTIFICATIONS, TMDB_METHOD_TV_CERTIFICATIONS); - return mapJsonResult(apiUrl, CertificationResults.class); + return tmdbApiClient.get(apiUrl, CertificationResults.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbChanges.java b/src/main/java/info/movito/themoviedbapi/TmdbChanges.java index fdc4f33a..d150e087 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbChanges.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbChanges.java @@ -6,13 +6,14 @@ import info.movito.themoviedbapi.model.changes.ChangesResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for changes. See the * documentation for more info. */ -public class TmdbChanges extends AbstractTmdbApi { +public class TmdbChanges { protected static final String TMDB_METHOD_CHANGES = "changes"; protected static final String TMDB_METHOD_MOVIE = "movie"; @@ -21,11 +22,13 @@ public class TmdbChanges extends AbstractTmdbApi { protected static final String TMDB_METHOD_TV = "tv"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbChanges instance to call the changes related TMDb API methods. */ - TmdbChanges(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbChanges(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -48,7 +51,7 @@ public ChangesResultsPage getMovieChangesList(String startDate, String endDate, .addQueryParam("end_date", endDate) .addPage(page); - return mapJsonResult(apiUrl, ChangesResultsPage.class); + return tmdbApiClient.get(apiUrl, ChangesResultsPage.class); } /** @@ -71,7 +74,7 @@ public ChangesResultsPage getPeopleChangesList(String startDate, String endDate, .addQueryParam("end_date", endDate) .addPage(page); - return mapJsonResult(apiUrl, ChangesResultsPage.class); + return tmdbApiClient.get(apiUrl, ChangesResultsPage.class); } /** @@ -94,7 +97,7 @@ public ChangesResultsPage getTvChangesList(String startDate, String endDate, Int .addQueryParam("end_date", endDate) .addPage(page); - return mapJsonResult(apiUrl, ChangesResultsPage.class); + return tmdbApiClient.get(apiUrl, ChangesResultsPage.class); } /** diff --git a/src/main/java/info/movito/themoviedbapi/TmdbCollections.java b/src/main/java/info/movito/themoviedbapi/TmdbCollections.java index f7f00d16..eb0a667e 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbCollections.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbCollections.java @@ -7,20 +7,23 @@ import info.movito.themoviedbapi.model.collections.Translation; import info.movito.themoviedbapi.model.collections.Translations; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for collections. See the * documentation for more info. */ -public class TmdbCollections extends AbstractTmdbApi { +public class TmdbCollections { protected static final String TMDB_METHOD_COLLECTION = "collection"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbCollections instance to call the collections related TMDb API methods. */ - TmdbCollections(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbCollections(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -35,7 +38,7 @@ public class TmdbCollections extends AbstractTmdbApi { public CollectionInfo getDetails(Integer collectionId, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_COLLECTION, collectionId) .addLanguage(language); - return mapJsonResult(apiUrl, CollectionInfo.class); + return tmdbApiClient.get(apiUrl, CollectionInfo.class); } /** @@ -52,7 +55,7 @@ public Images getImages(Integer collectionId, String language, String... include ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_COLLECTION, collectionId, "images") .addLanguage(language) .addQueryParamCommandSeparated("include_image_language", includeImageLanguage); - return mapJsonResult(apiUrl, Images.class); + return tmdbApiClient.get(apiUrl, Images.class); } /** @@ -65,6 +68,6 @@ public Images getImages(Integer collectionId, String language, String... include */ public List getTranslations(Integer collectionId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_COLLECTION, collectionId, "translations"); - return mapJsonResult(apiUrl, Translations.class).getTranslations(); + return tmdbApiClient.get(apiUrl, Translations.class).getTranslations(); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbCompanies.java b/src/main/java/info/movito/themoviedbapi/TmdbCompanies.java index 63491305..6d2e53b1 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbCompanies.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbCompanies.java @@ -4,20 +4,23 @@ import info.movito.themoviedbapi.model.companies.Company; import info.movito.themoviedbapi.model.core.image.ImageResults; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for companies. See the * documentation for more info. */ -public class TmdbCompanies extends AbstractTmdbApi { +public class TmdbCompanies { protected static final String TMDB_METHOD_COMPANY = "company"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbCompany instance to call the company related TMDb API methods. */ - TmdbCompanies(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbCompanies(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -30,7 +33,7 @@ public class TmdbCompanies extends AbstractTmdbApi { */ public Company getDetails(Integer companyId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_COMPANY, companyId); - return mapJsonResult(apiUrl, Company.class); + return tmdbApiClient.get(apiUrl, Company.class); } /** @@ -43,7 +46,7 @@ public Company getDetails(Integer companyId) throws TmdbException { */ public AlternativeNamesResultsPage getAlternativeNames(Integer companyId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_COMPANY, companyId, "alternative_names"); - return mapJsonResult(apiUrl, AlternativeNamesResultsPage.class); + return tmdbApiClient.get(apiUrl, AlternativeNamesResultsPage.class); } /** @@ -56,6 +59,6 @@ public AlternativeNamesResultsPage getAlternativeNames(Integer companyId) throws */ public ImageResults getImages(Integer companyId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_COMPANY, companyId, "images"); - return mapJsonResult(apiUrl, ImageResults.class); + return tmdbApiClient.get(apiUrl, ImageResults.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbConfiguration.java b/src/main/java/info/movito/themoviedbapi/TmdbConfiguration.java index 1d0464f2..2b0a515e 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbConfiguration.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbConfiguration.java @@ -9,20 +9,23 @@ import info.movito.themoviedbapi.model.configuration.Timezone; import info.movito.themoviedbapi.model.core.Language; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for configuration. See the * documentation for more info. */ -public class TmdbConfiguration extends AbstractTmdbApi { +public class TmdbConfiguration { protected static final String TMDB_METHOD_CONFIGURATION = "configuration"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbConfig instance to call the config related TMDb API methods. */ - TmdbConfiguration(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbConfiguration(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -34,7 +37,7 @@ public class TmdbConfiguration extends AbstractTmdbApi { */ public Configuration getDetails() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_CONFIGURATION); - return mapJsonResult(apiUrl, Configuration.class); + return tmdbApiClient.get(apiUrl, Configuration.class); } /** @@ -48,7 +51,7 @@ public Configuration getDetails() throws TmdbException { public List getCountries(String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_CONFIGURATION, "countries") .addLanguage(language); - return mapJsonResult(apiUrl, new TypeReference<>() { + return tmdbApiClient.get(apiUrl, new TypeReference<>() { }); } @@ -61,7 +64,7 @@ public List getCountries(String language) throws TmdbException { */ public List getJobs() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_CONFIGURATION, "jobs"); - return mapJsonResult(apiUrl, new TypeReference<>() { + return tmdbApiClient.get(apiUrl, new TypeReference<>() { }); } @@ -74,7 +77,7 @@ public List getJobs() throws TmdbException { */ public List getLanguages() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_CONFIGURATION, "languages"); - return mapJsonResult(apiUrl, new TypeReference<>() { + return tmdbApiClient.get(apiUrl, new TypeReference<>() { }); } @@ -88,7 +91,7 @@ public List getLanguages() throws TmdbException { */ public List getPrimaryTranslations() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_CONFIGURATION, "primary_translations"); - return mapJsonResult(apiUrl, new TypeReference<>() { + return tmdbApiClient.get(apiUrl, new TypeReference<>() { }); } @@ -101,7 +104,7 @@ public List getPrimaryTranslations() throws TmdbException { */ public List getTimezones() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_CONFIGURATION, "timezones"); - return mapJsonResult(apiUrl, new TypeReference<>() { + return tmdbApiClient.get(apiUrl, new TypeReference<>() { }); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbDiscover.java b/src/main/java/info/movito/themoviedbapi/TmdbDiscover.java index 286eef8d..e72fa603 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbDiscover.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbDiscover.java @@ -3,6 +3,7 @@ import info.movito.themoviedbapi.model.core.MovieResultsPage; import info.movito.themoviedbapi.model.core.TvSeriesResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.builders.discover.DiscoverMovieParamBuilder; import info.movito.themoviedbapi.tools.builders.discover.DiscoverTvParamBuilder; @@ -11,16 +12,18 @@ * The movie database api for discover. See the * documentation for more info. */ -public class TmdbDiscover extends AbstractTmdbApi { +public class TmdbDiscover { protected static final String TMDB_METHOD_DISCOVER = "discover"; protected static final String TMDB_METHOD_MOVIE = "movie"; protected static final String TMDB_METHOD_TV = "tv"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbDiscover instance to call the discover related TMDb API methods. */ - TmdbDiscover(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbDiscover(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -33,7 +36,7 @@ public class TmdbDiscover extends AbstractTmdbApi { public MovieResultsPage getMovie(DiscoverMovieParamBuilder builder) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_DISCOVER, TMDB_METHOD_MOVIE) .addPathParams(builder); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -46,6 +49,6 @@ public MovieResultsPage getMovie(DiscoverMovieParamBuilder builder) throws TmdbE public TvSeriesResultsPage getTv(DiscoverTvParamBuilder builder) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_DISCOVER, TMDB_METHOD_TV) .addPathParams(builder); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbFind.java b/src/main/java/info/movito/themoviedbapi/TmdbFind.java index b8f4fd08..8eda0986 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbFind.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbFind.java @@ -2,6 +2,7 @@ import info.movito.themoviedbapi.model.find.FindResults; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.model.time.ExternalSource; @@ -9,14 +10,16 @@ * The movie database api for find. See the * documentation for more info. */ -public class TmdbFind extends AbstractTmdbApi { +public class TmdbFind { protected static final String TMDB_METHOD_FIND = "find"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbFind instance to call the find related TMDb API methods. */ - TmdbFind(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbFind(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -32,6 +35,6 @@ public FindResults findById(String externalId, ExternalSource externalSource, St ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_FIND, externalId) .addPathParam("external_source", externalSource.getValue()) .addLanguage(language); - return mapJsonResult(apiUrl, FindResults.class); + return tmdbApiClient.get(apiUrl, FindResults.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbGenre.java b/src/main/java/info/movito/themoviedbapi/TmdbGenre.java index 587c0ea0..99d316eb 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbGenre.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbGenre.java @@ -5,20 +5,23 @@ import info.movito.themoviedbapi.model.core.Genre; import info.movito.themoviedbapi.model.core.Genres; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for genre. See the * documentation for more info. */ -public class TmdbGenre extends AbstractTmdbApi { +public class TmdbGenre { protected static final String TMDB_METHOD_GENRE = "genre"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbGenre instance to call the genre related TMDb API methods. */ - public TmdbGenre(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbGenre(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -32,7 +35,7 @@ public TmdbGenre(TmdbApi tmdbApi) { public List getMovieList(String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_GENRE, "movie/list") .addLanguage(language); - return mapJsonResult(apiUrl, Genres.class).getGenres(); + return tmdbApiClient.get(apiUrl, Genres.class).getGenres(); } /** @@ -46,6 +49,6 @@ public List getMovieList(String language) throws TmdbException { public List getTvList(String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_GENRE, "tv/list") .addLanguage(language); - return mapJsonResult(apiUrl, Genres.class).getGenres(); + return tmdbApiClient.get(apiUrl, Genres.class).getGenres(); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbGuestSessions.java b/src/main/java/info/movito/themoviedbapi/TmdbGuestSessions.java index 0d091584..18333668 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbGuestSessions.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbGuestSessions.java @@ -4,6 +4,7 @@ import info.movito.themoviedbapi.model.rated.RatedTvEpisodeResultsPage; import info.movito.themoviedbapi.model.rated.RatedTvSeriesResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.sortby.AccountSortBy; @@ -11,14 +12,16 @@ * The movie database api for guest sessions. See the * documentation for more info. */ -public class TmdbGuestSessions extends AbstractTmdbApi { +public class TmdbGuestSessions { protected static final String TMDB_METHOD_GUEST_SESSIONS = "guest_session"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbGuestSessions instance to call the guest sessions related TMDb API methods. */ - public TmdbGuestSessions(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbGuestSessions(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -39,7 +42,7 @@ public RatedMovieResultsPage getRatedMovies(int guestSessionId, String language, .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, RatedMovieResultsPage.class); + return tmdbApiClient.get(apiUrl, RatedMovieResultsPage.class); } /** @@ -60,7 +63,7 @@ public RatedTvSeriesResultsPage getRatedTvSeries(int guestSessionId, String lang .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, RatedTvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, RatedTvSeriesResultsPage.class); } /** @@ -81,6 +84,6 @@ public RatedTvEpisodeResultsPage getRatedTvEpisodes(int guestSessionId, String l .addPage(page) .addSortBy(sortBy); - return mapJsonResult(apiUrl, RatedTvEpisodeResultsPage.class); + return tmdbApiClient.get(apiUrl, RatedTvEpisodeResultsPage.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbKeywords.java b/src/main/java/info/movito/themoviedbapi/TmdbKeywords.java index 173f4954..60f7b157 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbKeywords.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbKeywords.java @@ -3,6 +3,7 @@ import info.movito.themoviedbapi.model.core.MovieDbResultsPage; import info.movito.themoviedbapi.model.keywords.Keyword; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.builders.discover.DiscoverMovieParamBuilder; @@ -10,14 +11,16 @@ * The movie database api for keywords. See the * documentation for more info. */ -public class TmdbKeywords extends AbstractTmdbApi { +public class TmdbKeywords { protected static final String TMDB_METHOD_KEYWORD = "keyword"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbKeywords instance to call the keywords TMDb API methods. */ - TmdbKeywords(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbKeywords(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -29,7 +32,7 @@ public class TmdbKeywords extends AbstractTmdbApi { */ public Keyword getDetails(int keywordId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_KEYWORD, keywordId); - return mapJsonResult(apiUrl, Keyword.class); + return tmdbApiClient.get(apiUrl, Keyword.class); } /** @@ -44,6 +47,6 @@ public MovieDbResultsPage getKeywordMovies(String keywordId, String language, In .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, MovieDbResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieDbResultsPage.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbLists.java b/src/main/java/info/movito/themoviedbapi/TmdbLists.java index 38219b69..905069f9 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbLists.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbLists.java @@ -8,6 +8,7 @@ import info.movito.themoviedbapi.model.lists.MovieListCreationStatus; import info.movito.themoviedbapi.tools.ApiUrl; import info.movito.themoviedbapi.tools.RequestType; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.util.JsonUtil; @@ -15,14 +16,16 @@ * The movie database api for lists. See the * documentation for more info. */ -public class TmdbLists extends AbstractTmdbApi { +public class TmdbLists { protected static final String TMDB_METHOD_LIST = "list"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbLists instance to call the lists TMDb API methods. */ - public TmdbLists(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbLists(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -43,7 +46,7 @@ public ResponseStatus addMovie(Integer listId, String sessionId, Integer movieId body.put("media_id", movieId); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); } /** @@ -60,7 +63,7 @@ public ListItemStatus checkItemStatus(Integer listId, String language, Integer m ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_LIST, listId, "item_status") .addLanguage(language) .addQueryParam("movie_id", movieId); - return mapJsonResult(apiUrl, ListItemStatus.class); + return tmdbApiClient.get(apiUrl, ListItemStatus.class); } /** @@ -77,7 +80,7 @@ public ResponseStatus clear(Integer listId, String sessionId, Boolean confirm) t ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_LIST, listId, "clear") .addPathParam("session_id", sessionId) .addPathParam("confirm", confirm); - return mapJsonResult(apiUrl, null, RequestType.POST, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, null, RequestType.POST, ResponseStatus.class); } /** @@ -101,7 +104,7 @@ public MovieListCreationStatus create(String sessionId, String name, String desc body.put("language", language); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, MovieListCreationStatus.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, MovieListCreationStatus.class); } /** @@ -116,7 +119,7 @@ public MovieListCreationStatus create(String sessionId, String name, String desc public ResponseStatus delete(Integer listId, String sessionId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_LIST, listId) .addPathParam("session_id", sessionId); - return mapJsonResult(apiUrl, null, RequestType.DELETE, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, null, RequestType.DELETE, ResponseStatus.class); } /** @@ -133,7 +136,7 @@ public ListDetails getDetails(Integer listId, String language, Integer page) thr ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_LIST, listId) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, ListDetails.class); + return tmdbApiClient.get(apiUrl, ListDetails.class); } /** @@ -154,6 +157,6 @@ public ResponseStatus removeMovie(Integer listId, String sessionId, Integer movi body.put("media_id", movieId); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbMovieLists.java b/src/main/java/info/movito/themoviedbapi/TmdbMovieLists.java index 4011c8cc..6875996e 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbMovieLists.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbMovieLists.java @@ -3,20 +3,23 @@ import info.movito.themoviedbapi.model.core.MovieResultsPage; import info.movito.themoviedbapi.model.movielists.MovieResultsPageWithDates; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for movie lists. See the * documentation for more info. */ -public class TmdbMovieLists extends AbstractTmdbApi { +public class TmdbMovieLists { protected static final String TMDB_METHOD_MOVIE_LISTS = "movie"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbMovieLists instance to call the movie lists related TMDb API methods. */ - TmdbMovieLists(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbMovieLists(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -34,7 +37,7 @@ public MovieResultsPageWithDates getNowPlaying(String language, Integer page, St .addLanguage(language) .addPage(page) .addQueryParam("region", region); - return mapJsonResult(apiUrl, MovieResultsPageWithDates.class); + return tmdbApiClient.get(apiUrl, MovieResultsPageWithDates.class); } /** @@ -52,7 +55,7 @@ public MovieResultsPage getPopular(String language, Integer page, String region) .addLanguage(language) .addPage(page) .addQueryParam("region", region); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -70,7 +73,7 @@ public MovieResultsPage getTopRated(String language, Integer page, String region .addLanguage(language) .addPage(page) .addQueryParam("region", region); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -88,6 +91,6 @@ public MovieResultsPageWithDates getUpcoming(String language, Integer page, Stri .addLanguage(language) .addPage(page) .addQueryParam("region", region); - return mapJsonResult(apiUrl, MovieResultsPageWithDates.class); + return tmdbApiClient.get(apiUrl, MovieResultsPageWithDates.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbMovies.java b/src/main/java/info/movito/themoviedbapi/TmdbMovies.java index a5b1573e..0ed90685 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbMovies.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbMovies.java @@ -20,6 +20,7 @@ import info.movito.themoviedbapi.model.movies.changes.ChangeResults; import info.movito.themoviedbapi.tools.ApiUrl; import info.movito.themoviedbapi.tools.RequestType; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.appendtoresponse.MovieAppendToResponse; import info.movito.themoviedbapi.util.JsonUtil; @@ -28,14 +29,16 @@ * The movie database api for movies. See the * documentation for more info. */ -public class TmdbMovies extends AbstractTmdbApi { +public class TmdbMovies { protected static final String TMDB_METHOD_MOVIE = "movie"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbMovies instance to call the movie related TMDb API methods. */ - public TmdbMovies(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbMovies(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -52,7 +55,7 @@ public MovieDb getDetails(int movieId, String language, MovieAppendToResponse... ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId) .addLanguage(language) .addAppendToResponses(appendToResponse); - return mapJsonResult(apiUrl, MovieDb.class); + return tmdbApiClient.get(apiUrl, MovieDb.class); } /** @@ -69,7 +72,7 @@ public AccountStates getAccountStates(int movieId, String sessionId, String gues ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "account_states") .addQueryParam("session_id", sessionId) .addQueryParam("guest_session_id", guestSessionId); - return mapJsonResult(apiUrl, AccountStates.class); + return tmdbApiClient.get(apiUrl, AccountStates.class); } /** @@ -84,7 +87,7 @@ public AccountStates getAccountStates(int movieId, String sessionId, String gues public AlternativeTitles getAlternativeTitles(int movieId, String country) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "alternative_titles") .addQueryParam("country", country); - return mapJsonResult(apiUrl, AlternativeTitles.class); + return tmdbApiClient.get(apiUrl, AlternativeTitles.class); } /** @@ -103,7 +106,7 @@ public ChangeResults getChanges(int movieId, String startDate, String endDate, I .addQueryParam("start_date", startDate) .addQueryParam("end_date", endDate) .addPage(page); - return mapJsonResult(apiUrl, ChangeResults.class); + return tmdbApiClient.get(apiUrl, ChangeResults.class); } /** @@ -118,7 +121,7 @@ public ChangeResults getChanges(int movieId, String startDate, String endDate, I public Credits getCredits(int movieId, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "credits") .addLanguage(language); - return mapJsonResult(apiUrl, Credits.class); + return tmdbApiClient.get(apiUrl, Credits.class); } /** @@ -131,7 +134,7 @@ public Credits getCredits(int movieId, String language) throws TmdbException { */ public ExternalIds getExternalIds(int movieId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "external_ids"); - return mapJsonResult(apiUrl, ExternalIds.class); + return tmdbApiClient.get(apiUrl, ExternalIds.class); } /** @@ -148,7 +151,7 @@ public Images getImages(int movieId, String language, String... includeImageLang ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "images") .addLanguage(language) .addQueryParamCommandSeparated("include_image_language", includeImageLanguage); - return mapJsonResult(apiUrl, Images.class); + return tmdbApiClient.get(apiUrl, Images.class); } /** @@ -161,7 +164,7 @@ public Images getImages(int movieId, String language, String... includeImageLang */ public KeywordResults getKeywords(int movieId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "keywords"); - return mapJsonResult(apiUrl, KeywordResults.class); + return tmdbApiClient.get(apiUrl, KeywordResults.class); } /** @@ -173,7 +176,7 @@ public KeywordResults getKeywords(int movieId) throws TmdbException { */ public MovieDb getLatest() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, "latest"); - return mapJsonResult(apiUrl, MovieDb.class); + return tmdbApiClient.get(apiUrl, MovieDb.class); } /** @@ -190,7 +193,7 @@ public MovieListResultsPage getLists(int movieId, String language, Integer page) ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "lists") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, MovieListResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieListResultsPage.class); } /** @@ -207,7 +210,7 @@ public MovieResultsPage getRecommendations(int movieId, String language, Integer ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "recommendations") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -220,7 +223,7 @@ public MovieResultsPage getRecommendations(int movieId, String language, Integer */ public ReleaseDateResults getReleaseDates(int movieId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "release_dates"); - return mapJsonResult(apiUrl, ReleaseDateResults.class); + return tmdbApiClient.get(apiUrl, ReleaseDateResults.class); } /** @@ -237,7 +240,7 @@ public ReviewResultsPage getReviews(int movieId, String language, Integer page) ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "reviews") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, ReviewResultsPage.class); + return tmdbApiClient.get(apiUrl, ReviewResultsPage.class); } /** @@ -254,7 +257,7 @@ public MovieResultsPage getSimilar(int movieId, String language, Integer page) t ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "similar") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -267,7 +270,7 @@ public MovieResultsPage getSimilar(int movieId, String language, Integer page) t */ public Translations getTranslations(int movieId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "translations"); - return mapJsonResult(apiUrl, Translations.class); + return tmdbApiClient.get(apiUrl, Translations.class); } /** @@ -282,7 +285,7 @@ public Translations getTranslations(int movieId) throws TmdbException { public VideoResults getVideos(int movieId, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "videos") .addLanguage(language); - return mapJsonResult(apiUrl, VideoResults.class); + return tmdbApiClient.get(apiUrl, VideoResults.class); } /** @@ -297,7 +300,7 @@ public VideoResults getVideos(int movieId, String language) throws TmdbException */ public ProviderResults getWatchProviders(int movieId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "watch/providers"); - return mapJsonResult(apiUrl, ProviderResults.class); + return tmdbApiClient.get(apiUrl, ProviderResults.class); } /** @@ -326,7 +329,7 @@ public ResponseStatus addRating(int movieId, String guestSessionId, String sessi body.put("value", rating); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); } /** @@ -345,6 +348,6 @@ public ResponseStatus deleteRating(int movieId, String guestSessionId, String se ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE, movieId, "rating") .addQueryParam("session_id", sessionId) .addQueryParam("guest_session_id", guestSessionId); - return mapJsonResult(apiUrl, null, RequestType.DELETE, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, null, RequestType.DELETE, ResponseStatus.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbNetworks.java b/src/main/java/info/movito/themoviedbapi/TmdbNetworks.java index a0d9b024..2b8d7df9 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbNetworks.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbNetworks.java @@ -4,20 +4,23 @@ import info.movito.themoviedbapi.model.networks.AlternativeNamesResults; import info.movito.themoviedbapi.model.networks.Network; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for networks. See the * documentation for more info. */ -public class TmdbNetworks extends AbstractTmdbApi { +public class TmdbNetworks { protected static final String TMDB_METHOD_NETWORK = "network"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbNetworks instance to call the network related TMDb API methods. */ - public TmdbNetworks(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbNetworks(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -30,7 +33,7 @@ public TmdbNetworks(TmdbApi tmdbApi) { */ public Network getDetails(int networkId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_NETWORK, networkId); - return mapJsonResult(apiUrl, Network.class); + return tmdbApiClient.get(apiUrl, Network.class); } /** @@ -43,7 +46,7 @@ public Network getDetails(int networkId) throws TmdbException { */ public AlternativeNamesResults getAlternativeNames(int networkId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_NETWORK, networkId, "alternative_names"); - return mapJsonResult(apiUrl, AlternativeNamesResults.class); + return tmdbApiClient.get(apiUrl, AlternativeNamesResults.class); } /** @@ -56,6 +59,6 @@ public AlternativeNamesResults getAlternativeNames(int networkId) throws TmdbExc */ public ImageResults getImages(int networkId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_NETWORK, networkId, "images"); - return mapJsonResult(apiUrl, ImageResults.class); + return tmdbApiClient.get(apiUrl, ImageResults.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbPeople.java b/src/main/java/info/movito/themoviedbapi/TmdbPeople.java index 300db6d4..92a7ca7e 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbPeople.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbPeople.java @@ -9,6 +9,7 @@ import info.movito.themoviedbapi.model.people.credits.MovieCredits; import info.movito.themoviedbapi.model.people.credits.TvCredits; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.appendtoresponse.PersonAppendToResponse; @@ -16,14 +17,16 @@ * The movie database api for people. See the * documentation for more info. */ -public class TmdbPeople extends AbstractTmdbApi { +public class TmdbPeople { protected static final String TMDB_METHOD_PERSON = "person"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbPeople instance to call the people related TMDb API methods. */ - TmdbPeople(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbPeople(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -40,7 +43,7 @@ public PersonDb getDetails(int personId, String language, PersonAppendToResponse ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId) .addLanguage(language) .addAppendToResponses(appendToResponse); - return mapJsonResult(apiUrl, PersonDb.class); + return tmdbApiClient.get(apiUrl, PersonDb.class); } /** @@ -59,7 +62,7 @@ public ChangeResults getChanges(int personId, String startDate, String endDate, .addQueryParam("start_date", startDate) .addQueryParam("end_date", endDate) .addPage(page); - return mapJsonResult(apiUrl, ChangeResults.class); + return tmdbApiClient.get(apiUrl, ChangeResults.class); } /** @@ -74,7 +77,7 @@ public ChangeResults getChanges(int personId, String startDate, String endDate, public CombinedPersonCredits getCombinedCredits(int personId, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId, "combined_credits") .addLanguage(language); - return mapJsonResult(apiUrl, CombinedPersonCredits.class); + return tmdbApiClient.get(apiUrl, CombinedPersonCredits.class); } /** @@ -87,7 +90,7 @@ public CombinedPersonCredits getCombinedCredits(int personId, String language) t */ public ExternalIds getExternalIds(int personId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId, "external_ids"); - return mapJsonResult(apiUrl, ExternalIds.class); + return tmdbApiClient.get(apiUrl, ExternalIds.class); } /** @@ -100,7 +103,7 @@ public ExternalIds getExternalIds(int personId) throws TmdbException { */ public PersonImages getImages(int personId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId, "images"); - return mapJsonResult(apiUrl, PersonImages.class); + return tmdbApiClient.get(apiUrl, PersonImages.class); } /** @@ -112,7 +115,7 @@ public PersonImages getImages(int personId) throws TmdbException { */ public PersonDb getLatest() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, "latest"); - return mapJsonResult(apiUrl, PersonDb.class); + return tmdbApiClient.get(apiUrl, PersonDb.class); } /** @@ -127,7 +130,7 @@ public PersonDb getLatest() throws TmdbException { public MovieCredits getMovieCredits(int personId, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId, "movie_credits") .addLanguage(language); - return mapJsonResult(apiUrl, MovieCredits.class); + return tmdbApiClient.get(apiUrl, MovieCredits.class); } /** @@ -142,7 +145,7 @@ public MovieCredits getMovieCredits(int personId, String language) throws TmdbEx public TvCredits getTvCredits(int personId, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId, "tv_credits") .addLanguage(language); - return mapJsonResult(apiUrl, TvCredits.class); + return tmdbApiClient.get(apiUrl, TvCredits.class); } /** @@ -155,6 +158,6 @@ public TvCredits getTvCredits(int personId, String language) throws TmdbExceptio */ public Translations getTranslations(int personId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PERSON, personId, "translations"); - return mapJsonResult(apiUrl, Translations.class); + return tmdbApiClient.get(apiUrl, Translations.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbPeopleLists.java b/src/main/java/info/movito/themoviedbapi/TmdbPeopleLists.java index 365afced..0b63e7a7 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbPeopleLists.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbPeopleLists.java @@ -2,17 +2,20 @@ import info.movito.themoviedbapi.model.core.popularperson.PopularPersonResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for people lists. See the * documentation for more info. */ -public class TmdbPeopleLists extends AbstractTmdbApi { +public class TmdbPeopleLists { protected static final String TMDB_METHOD_PEOPLE_LISTS = "person/popular"; - TmdbPeopleLists(TmdbApi tmdbApi) { - super(tmdbApi); + private final TmdbApiClient tmdbApiClient; + + TmdbPeopleLists(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -28,6 +31,6 @@ public PopularPersonResultsPage getPopular(String language, Integer page) throws ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_PEOPLE_LISTS) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, PopularPersonResultsPage.class); + return tmdbApiClient.get(apiUrl, PopularPersonResultsPage.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbReviews.java b/src/main/java/info/movito/themoviedbapi/TmdbReviews.java index abb730ec..10ad3cc9 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbReviews.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbReviews.java @@ -2,20 +2,23 @@ import info.movito.themoviedbapi.model.reviews.Review; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for reviews. See the * documentation for more info. */ -public class TmdbReviews extends AbstractTmdbApi { +public class TmdbReviews { protected static final String TMDB_METHOD_MOVIE_REVIEW = "reviews"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbReviews instance to call the reviews related TMDb API methods. */ - TmdbReviews(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbReviews(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -27,6 +30,6 @@ public class TmdbReviews extends AbstractTmdbApi { */ public Review getDetails(int reviewId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_MOVIE_REVIEW, reviewId); - return mapJsonResult(apiUrl, Review.class); + return tmdbApiClient.get(apiUrl, Review.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbSearch.java b/src/main/java/info/movito/themoviedbapi/TmdbSearch.java index bf654dbb..252703f8 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbSearch.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbSearch.java @@ -8,6 +8,7 @@ import info.movito.themoviedbapi.model.search.CompanyResultsPage; import info.movito.themoviedbapi.model.search.KeywordResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import static info.movito.themoviedbapi.TmdbCollections.TMDB_METHOD_COLLECTION; @@ -19,17 +20,19 @@ * The movie database api for searching. See the * documentation for more info. */ -public class TmdbSearch extends AbstractTmdbApi { +public class TmdbSearch { protected static final String TMDB_METHOD_SEARCH = "search"; protected static final String TMDB_METHOD_MULTI = "multi"; private static final String PARAM_QUERY = "query"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbSearch instance to call the search TMDb API methods. */ - public TmdbSearch(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbSearch(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -52,7 +55,7 @@ public CollectionResultsPage searchCollection(String query, String language, Boo .addQueryParam("region", region) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, CollectionResultsPage.class); + return tmdbApiClient.get(apiUrl, CollectionResultsPage.class); } /** @@ -68,7 +71,7 @@ public CompanyResultsPage searchCompany(String query, Integer page) throws TmdbE ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_SEARCH, "company") .addPathParam(PARAM_QUERY, query) .addPage(page); - return mapJsonResult(apiUrl, CompanyResultsPage.class); + return tmdbApiClient.get(apiUrl, CompanyResultsPage.class); } /** @@ -84,7 +87,7 @@ public KeywordResultsPage searchKeyword(String query, Integer page) throws TmdbE ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_SEARCH, "keyword") .addPathParam(PARAM_QUERY, query) .addPage(page); - return mapJsonResult(apiUrl, KeywordResultsPage.class); + return tmdbApiClient.get(apiUrl, KeywordResultsPage.class); } /** @@ -111,7 +114,7 @@ public MovieResultsPage searchMovie(String query, Boolean includeAdult, String l .addQueryParam("year", year) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -131,7 +134,7 @@ public MultiResultsPage searchMulti(String query, Boolean includeAdult, String l .addQueryParam("include_adult", includeAdult) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, MultiResultsPage.class); + return tmdbApiClient.get(apiUrl, MultiResultsPage.class); } /** @@ -151,7 +154,7 @@ public PopularPersonResultsPage searchPerson(String query, Boolean includeAdult, .addQueryParam("include_adult", includeAdult) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, PopularPersonResultsPage.class); + return tmdbApiClient.get(apiUrl, PopularPersonResultsPage.class); } /** @@ -176,6 +179,6 @@ public TvSeriesResultsPage searchTv(String query, Integer firstAirDateYear, Bool .addQueryParam("year", year) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbTrending.java b/src/main/java/info/movito/themoviedbapi/TmdbTrending.java index 10f5f7a5..65e922ef 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbTrending.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbTrending.java @@ -5,6 +5,7 @@ import info.movito.themoviedbapi.model.core.multi.MultiResultsPage; import info.movito.themoviedbapi.model.core.popularperson.PopularPersonResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.model.time.TimeWindow; @@ -12,14 +13,16 @@ * The movie database api for trending media. See the * documentation for more info. */ -public class TmdbTrending extends AbstractTmdbApi { +public class TmdbTrending { protected static final String TMDB_METHOD_TRENDING = "trending"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbTrending instance to call the rending TMDb API methods. */ - TmdbTrending(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbTrending(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -49,7 +52,7 @@ public MultiResultsPage getAll(TimeWindow timeWindow, String language, Integer p ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TRENDING, "all", timeWindow.getValue()) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, MultiResultsPage.class); + return tmdbApiClient.get(apiUrl, MultiResultsPage.class); } /** @@ -79,7 +82,7 @@ public MovieResultsPage getMovies(TimeWindow timeWindow, String language, Intege ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TRENDING, "movie", timeWindow.getValue()) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, MovieResultsPage.class); + return tmdbApiClient.get(apiUrl, MovieResultsPage.class); } /** @@ -109,7 +112,7 @@ public PopularPersonResultsPage getPeople(TimeWindow timeWindow, String language ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TRENDING, "person", timeWindow.getValue()) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, PopularPersonResultsPage.class); + return tmdbApiClient.get(apiUrl, PopularPersonResultsPage.class); } /** @@ -139,6 +142,6 @@ public TvSeriesResultsPage getTv(TimeWindow timeWindow, String language, Integer ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TRENDING, "tv", timeWindow.getValue()) .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbTvEpisodeGroups.java b/src/main/java/info/movito/themoviedbapi/TmdbTvEpisodeGroups.java index 04a4b111..ee6a1719 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbTvEpisodeGroups.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbTvEpisodeGroups.java @@ -2,20 +2,23 @@ import info.movito.themoviedbapi.model.tv.episodegroups.TvEpisodeGroups; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for tv episode groups. See the * documentation for more info. */ -public class TmdbTvEpisodeGroups extends AbstractTmdbApi { +public class TmdbTvEpisodeGroups { protected static final String TMDB_METHOD_TV_EPISODE_GROUPS = "tv/episode_group"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbTvEpisodeGroups instance to call the tv episode groups TMDb API methods. */ - TmdbTvEpisodeGroups(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbTvEpisodeGroups(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -28,6 +31,6 @@ public class TmdbTvEpisodeGroups extends AbstractTmdbApi { */ public TvEpisodeGroups getDetails(String tvEpisodeGroupId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV_EPISODE_GROUPS, tvEpisodeGroupId); - return mapJsonResult(apiUrl, TvEpisodeGroups.class); + return tmdbApiClient.get(apiUrl, TvEpisodeGroups.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbTvEpisodes.java b/src/main/java/info/movito/themoviedbapi/TmdbTvEpisodes.java index 140bf284..4b4dcd70 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbTvEpisodes.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbTvEpisodes.java @@ -13,6 +13,7 @@ import info.movito.themoviedbapi.model.tv.episode.TvEpisodeDb; import info.movito.themoviedbapi.tools.ApiUrl; import info.movito.themoviedbapi.tools.RequestType; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.appendtoresponse.TvEpisodesAppendToResponse; import info.movito.themoviedbapi.util.JsonUtil; @@ -24,14 +25,16 @@ * The movie database api for tv episodes. See the * documentation for more info. */ -public class TmdbTvEpisodes extends AbstractTmdbApi { +public class TmdbTvEpisodes { public static final String TMDB_METHOD_TV_EPISODE = "episode"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbTvEpisodes instance to call the tv episodes TMDb API methods. */ - TmdbTvEpisodes(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbTvEpisodes(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -51,7 +54,7 @@ public TvEpisodeDb getDetails(int seriesId, int seasonNumber, int episodeNumber, ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, TMDB_METHOD_TV_EPISODE, episodeNumber) .addLanguage(language) .addAppendToResponses(appendToResponse); - return mapJsonResult(apiUrl, TvEpisodeDb.class); + return tmdbApiClient.get(apiUrl, TvEpisodeDb.class); } /** @@ -72,7 +75,7 @@ public AccountStates getAccountStates(int seriesId, int seasonNumber, int episod TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, TMDB_METHOD_TV_EPISODE, episodeNumber, "account_states") .addQueryParam("session_id", sessionId) .addQueryParam("guest_session_id", guestSessionId); - return mapJsonResult(apiUrl, AccountStates.class); + return tmdbApiClient.get(apiUrl, AccountStates.class); } /** @@ -86,7 +89,7 @@ public AccountStates getAccountStates(int seriesId, int seasonNumber, int episod public ChangeResults getChanges(int episodeId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, TMDB_METHOD_TV_EPISODE, episodeId, "changes"); - return mapJsonResult(apiUrl, ChangeResults.class); + return tmdbApiClient.get(apiUrl, ChangeResults.class); } /** @@ -105,7 +108,7 @@ public EpisodeCredits getCredits(int seriesId, int seasonNumber, int episodeNumb ApiUrl apiUrl = new ApiUrl( TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, TMDB_METHOD_TV_EPISODE, episodeNumber, "credits") .addLanguage(language); - return mapJsonResult(apiUrl, EpisodeCredits.class); + return tmdbApiClient.get(apiUrl, EpisodeCredits.class); } /** @@ -122,7 +125,7 @@ public ExternalIds getExternalIds(int seriesId, int seasonNumber, int episodeNum throws TmdbException { ApiUrl apiUrl = new ApiUrl( TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, TMDB_METHOD_TV_EPISODE, episodeNumber, "external_ids"); - return mapJsonResult(apiUrl, ExternalIds.class); + return tmdbApiClient.get(apiUrl, ExternalIds.class); } /** @@ -143,7 +146,7 @@ public Images getImages(int seriesId, int seasonNumber, int episodeNumber, Strin TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, TMDB_METHOD_TV_EPISODE, episodeNumber, "images") .addLanguage(language) .addQueryParamCommandSeparated("include_image_language", includeImageLanguage); - return mapJsonResult(apiUrl, Images.class); + return tmdbApiClient.get(apiUrl, Images.class); } /** @@ -160,7 +163,7 @@ public Translations getTranslations(int seriesId, int seasonNumber, int episodeN throws TmdbException { ApiUrl apiUrl = new ApiUrl( TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, TMDB_METHOD_TV_EPISODE, episodeNumber, "translations"); - return mapJsonResult(apiUrl, Translations.class); + return tmdbApiClient.get(apiUrl, Translations.class); } /** @@ -181,7 +184,7 @@ public VideoResults getVideos(int seriesId, int seasonNumber, int episodeNumber, TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, TMDB_METHOD_TV_EPISODE, episodeNumber, "videos") .addLanguage(language) .addQueryParamCommandSeparated("include_video_language", includeVideoLanguage); - return mapJsonResult(apiUrl, VideoResults.class); + return tmdbApiClient.get(apiUrl, VideoResults.class); } /** @@ -214,7 +217,7 @@ public ResponseStatus addRating(int seriesId, int seasonNumber, int episodeNumbe body.put("value", rating); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); } /** @@ -237,6 +240,6 @@ public ResponseStatus deleteRating(int seriesId, int seasonNumber, int episodeNu TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, TMDB_METHOD_TV_EPISODE, episodeNumber, "rating") .addQueryParam("session_id", sessionId) .addQueryParam("guest_session_id", guestSessionId); - return mapJsonResult(apiUrl, null, RequestType.DELETE, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, null, RequestType.DELETE, ResponseStatus.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbTvSeasons.java b/src/main/java/info/movito/themoviedbapi/TmdbTvSeasons.java index 8ae569a0..3d71bd37 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbTvSeasons.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbTvSeasons.java @@ -11,6 +11,7 @@ import info.movito.themoviedbapi.model.tv.season.Images; import info.movito.themoviedbapi.model.tv.season.TvSeasonDb; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.appendtoresponse.TvSeasonsAppendToResponse; @@ -20,14 +21,16 @@ * The movie database api for tv seasons. See the * documentation for more info. */ -public class TmdbTvSeasons extends AbstractTmdbApi { +public class TmdbTvSeasons { public static final String TMDB_METHOD_TV_SEASON = "season"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbTvSeasons instance to call the tv seasons TMDb API methods. */ - TmdbTvSeasons(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbTvSeasons(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -46,7 +49,7 @@ public TvSeasonDb getDetails(int seriesId, int seasonNumber, String language, Tv ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber) .addLanguage(language) .addAppendToResponses(appendToResponse); - return mapJsonResult(apiUrl, TvSeasonDb.class); + return tmdbApiClient.get(apiUrl, TvSeasonDb.class); } /** @@ -65,7 +68,7 @@ public AccountStateResults getAccountStates(int seriesId, int seasonNumber, Stri ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, "account_states") .addQueryParam("session_id", sessionId) .addQueryParam("guest_session_id", guestSessionId); - return mapJsonResult(apiUrl, AccountStateResults.class); + return tmdbApiClient.get(apiUrl, AccountStateResults.class); } /** @@ -81,7 +84,7 @@ public AccountStateResults getAccountStates(int seriesId, int seasonNumber, Stri public AggregateCredits getAggregateCredits(int seriesId, int seasonNumber, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, "aggregate_credits") .addLanguage(language); - return mapJsonResult(apiUrl, AggregateCredits.class); + return tmdbApiClient.get(apiUrl, AggregateCredits.class); } /** @@ -100,7 +103,7 @@ public ChangeResults getChanges(int seasonId, String startDate, String endDate, .addQueryParam("start_date", startDate) .addQueryParam("end_date", endDate) .addPage(page); - return mapJsonResult(apiUrl, ChangeResults.class); + return tmdbApiClient.get(apiUrl, ChangeResults.class); } /** @@ -116,7 +119,7 @@ public ChangeResults getChanges(int seasonId, String startDate, String endDate, public Credits getCredits(int seriesId, int seasonNumber, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, "credits") .addLanguage(language); - return mapJsonResult(apiUrl, Credits.class); + return tmdbApiClient.get(apiUrl, Credits.class); } /** @@ -130,7 +133,7 @@ public Credits getCredits(int seriesId, int seasonNumber, String language) throw */ public ExternalIds getExternalIds(int seriesId, int seasonNumber) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, "external_ids"); - return mapJsonResult(apiUrl, ExternalIds.class); + return tmdbApiClient.get(apiUrl, ExternalIds.class); } /** @@ -148,7 +151,7 @@ public Images getImages(int seriesId, int seasonNumber, String language, String. ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, "images") .addLanguage(language) .addQueryParamCommandSeparated("include_image_language", includeImageLanguage); - return mapJsonResult(apiUrl, Images.class); + return tmdbApiClient.get(apiUrl, Images.class); } /** @@ -162,7 +165,7 @@ public Images getImages(int seriesId, int seasonNumber, String language, String. */ public Translations getTranslations(int seriesId, int seasonNumber) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, "translations"); - return mapJsonResult(apiUrl, Translations.class); + return tmdbApiClient.get(apiUrl, Translations.class); } /** @@ -180,7 +183,7 @@ public VideoResults getVideos(int seriesId, int seasonNumber, String language, S ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, "videos") .addLanguage(language) .addQueryParamCommandSeparated("include_video_language", includeVideoLanguage); - return mapJsonResult(apiUrl, VideoResults.class); + return tmdbApiClient.get(apiUrl, VideoResults.class); } /** @@ -198,6 +201,6 @@ public VideoResults getVideos(int seriesId, int seasonNumber, String language, S public ProviderResults getWatchProviders(int seriesId, int seasonNumber, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, TMDB_METHOD_TV_SEASON, seasonNumber, "watch/providers") .addLanguage(language); - return mapJsonResult(apiUrl, ProviderResults.class); + return tmdbApiClient.get(apiUrl, ProviderResults.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbTvSeries.java b/src/main/java/info/movito/themoviedbapi/TmdbTvSeries.java index 83f4f283..064d6b1e 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbTvSeries.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbTvSeries.java @@ -23,6 +23,7 @@ import info.movito.themoviedbapi.model.tv.series.TvSeriesListResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; import info.movito.themoviedbapi.tools.RequestType; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import info.movito.themoviedbapi.tools.appendtoresponse.TvSeriesAppendToResponse; import info.movito.themoviedbapi.util.JsonUtil; @@ -31,14 +32,16 @@ * The movie database api for tv series. See the * documentation for more info. */ -public class TmdbTvSeries extends AbstractTmdbApi { +public class TmdbTvSeries { public static final String TMDB_METHOD_TV = "tv"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbTvSeries instance to call the tv series TMDb API methods. */ - TmdbTvSeries(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbTvSeries(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -55,7 +58,7 @@ public TvSeriesDb getDetails(int seriesId, String language, TvSeriesAppendToResp ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId) .addLanguage(language) .addAppendToResponses(appendToResponse); - return mapJsonResult(apiUrl, TvSeriesDb.class); + return tmdbApiClient.get(apiUrl, TvSeriesDb.class); } /** @@ -72,7 +75,7 @@ public AccountStates getAccountStates(int seriesId, String sessionId, String gue ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "account_states") .addQueryParam("session_id", sessionId) .addQueryParam("guest_session_id", guestSessionId); - return mapJsonResult(apiUrl, AccountStates.class); + return tmdbApiClient.get(apiUrl, AccountStates.class); } /** @@ -86,7 +89,7 @@ public AccountStates getAccountStates(int seriesId, String sessionId, String gue public AggregateCredits getAggregateCredits(int seriesId, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "aggregate_credits") .addLanguage(language); - return mapJsonResult(apiUrl, AggregateCredits.class); + return tmdbApiClient.get(apiUrl, AggregateCredits.class); } /** @@ -99,7 +102,7 @@ public AggregateCredits getAggregateCredits(int seriesId, String language) throw */ public AlternativeTitleResults getAlternativeTitles(int seriesId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "alternative_titles"); - return mapJsonResult(apiUrl, AlternativeTitleResults.class); + return tmdbApiClient.get(apiUrl, AlternativeTitleResults.class); } /** @@ -118,7 +121,7 @@ public ChangeResults getChanges(int seriesId, String startDate, String endDate, .addQueryParam("start_date", startDate) .addQueryParam("end_date", endDate) .addPage(page); - return mapJsonResult(apiUrl, ChangeResults.class); + return tmdbApiClient.get(apiUrl, ChangeResults.class); } /** @@ -131,7 +134,7 @@ public ChangeResults getChanges(int seriesId, String startDate, String endDate, */ public ContentRatingResults getContentRatings(int seriesId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "content_ratings"); - return mapJsonResult(apiUrl, ContentRatingResults.class); + return tmdbApiClient.get(apiUrl, ContentRatingResults.class); } /** @@ -146,7 +149,7 @@ public ContentRatingResults getContentRatings(int seriesId) throws TmdbException public Credits getCredits(int seriesId, String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "credits") .addLanguage(language); - return mapJsonResult(apiUrl, Credits.class); + return tmdbApiClient.get(apiUrl, Credits.class); } /** @@ -159,7 +162,7 @@ public Credits getCredits(int seriesId, String language) throws TmdbException { */ public EpisodeGroupResults getEpisodeGroups(int seriesId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "episode_groups"); - return mapJsonResult(apiUrl, EpisodeGroupResults.class); + return tmdbApiClient.get(apiUrl, EpisodeGroupResults.class); } /** @@ -172,7 +175,7 @@ public EpisodeGroupResults getEpisodeGroups(int seriesId) throws TmdbException { */ public ExternalIds getExternalIds(int seriesId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "external_ids"); - return mapJsonResult(apiUrl, ExternalIds.class); + return tmdbApiClient.get(apiUrl, ExternalIds.class); } /** @@ -189,7 +192,7 @@ public Images getImages(int seriesId, String language, String... includeImageLan ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "images") .addLanguage(language) .addQueryParamCommandSeparated("include_image_language", includeImageLanguage); - return mapJsonResult(apiUrl, Images.class); + return tmdbApiClient.get(apiUrl, Images.class); } /** @@ -202,7 +205,7 @@ public Images getImages(int seriesId, String language, String... includeImageLan */ public TvKeywords getKeywords(int seriesId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "keywords"); - return mapJsonResult(apiUrl, TvKeywords.class); + return tmdbApiClient.get(apiUrl, TvKeywords.class); } /** @@ -214,7 +217,7 @@ public TvKeywords getKeywords(int seriesId) throws TmdbException { */ public TvSeriesDb getLatest() throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, "latest"); - return mapJsonResult(apiUrl, TvSeriesDb.class); + return tmdbApiClient.get(apiUrl, TvSeriesDb.class); } /** @@ -231,7 +234,7 @@ public TvSeriesListResultsPage getLists(int seriesId, String language, Integer p ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "lists") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, TvSeriesListResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesListResultsPage.class); } /** @@ -248,7 +251,7 @@ public TvSeriesResultsPage getRecommendations(int seriesId, String language, Int ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "recommendations") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } /** @@ -265,7 +268,7 @@ public ReviewResultsPage getReviews(int seriesId, String language, Integer page) ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "reviews") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, ReviewResultsPage.class); + return tmdbApiClient.get(apiUrl, ReviewResultsPage.class); } /** @@ -278,7 +281,7 @@ public ReviewResultsPage getReviews(int seriesId, String language, Integer page) */ public ScreenedTheatricallyResults getScreenedTheatrically(int seriesId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "screened_theatrically"); - return mapJsonResult(apiUrl, ScreenedTheatricallyResults.class); + return tmdbApiClient.get(apiUrl, ScreenedTheatricallyResults.class); } /** @@ -295,7 +298,7 @@ public TvSeriesResultsPage getSimilar(int seriesId, String language, Integer pag ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "similar") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } /** @@ -308,7 +311,7 @@ public TvSeriesResultsPage getSimilar(int seriesId, String language, Integer pag */ public Translations getTranslations(int seriesId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "translations"); - return mapJsonResult(apiUrl, Translations.class); + return tmdbApiClient.get(apiUrl, Translations.class); } /** @@ -325,7 +328,7 @@ public VideoResults getVideos(int seriesId, String language, String... includeVi ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "videos") .addLanguage(language) .addQueryParamCommandSeparated("include_image_language", includeVideoLanguage); - return mapJsonResult(apiUrl, VideoResults.class); + return tmdbApiClient.get(apiUrl, VideoResults.class); } /** @@ -340,7 +343,7 @@ public VideoResults getVideos(int seriesId, String language, String... includeVi */ public ProviderResults getWatchProviders(int seriesId) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "watch/providers"); - return mapJsonResult(apiUrl, ProviderResults.class); + return tmdbApiClient.get(apiUrl, ProviderResults.class); } /** @@ -369,7 +372,7 @@ public ResponseStatus addRating(int seriesId, String guestSessionId, String sess body.put("value", rating); String jsonBody = JsonUtil.toJson(body); - return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class); } /** @@ -388,6 +391,6 @@ public ResponseStatus deleteRating(int seriesId, String guestSessionId, String s ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, seriesId, "rating") .addQueryParam("session_id", sessionId) .addQueryParam("guest_session_id", guestSessionId); - return mapJsonResult(apiUrl, null, RequestType.DELETE, ResponseStatus.class); + return tmdbApiClient.request(apiUrl, null, RequestType.DELETE, ResponseStatus.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbTvSeriesLists.java b/src/main/java/info/movito/themoviedbapi/TmdbTvSeriesLists.java index 5664a9f8..a3fbf388 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbTvSeriesLists.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbTvSeriesLists.java @@ -2,6 +2,7 @@ import info.movito.themoviedbapi.model.core.TvSeriesResultsPage; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; import static info.movito.themoviedbapi.TmdbTvSeries.TMDB_METHOD_TV; @@ -10,12 +11,14 @@ * The movie database api for tv series lists. See the * documentation for more info. */ -public class TmdbTvSeriesLists extends AbstractTmdbApi { +public class TmdbTvSeriesLists { + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbTvSeriesLists instance to call the tv series lists TMDb API methods. */ - TmdbTvSeriesLists(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbTvSeriesLists(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -33,7 +36,7 @@ public TvSeriesResultsPage getAiringToday(String language, Integer page, String .addLanguage(language) .addPage(page) .addQueryParam("timezone", timezone); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } /** @@ -51,7 +54,7 @@ public TvSeriesResultsPage getOnTheAir(String language, Integer page, String tim .addLanguage(language) .addPage(page) .addQueryParam("timezone", timezone); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } /** @@ -67,7 +70,7 @@ public TvSeriesResultsPage getPopular(String language, Integer page) throws Tmdb ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, "popular") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } /** @@ -83,6 +86,6 @@ public TvSeriesResultsPage getTopRated(String language, Integer page) throws Tmd ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_TV, "top_rated") .addLanguage(language) .addPage(page); - return mapJsonResult(apiUrl, TvSeriesResultsPage.class); + return tmdbApiClient.get(apiUrl, TvSeriesResultsPage.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/TmdbWatchProviders.java b/src/main/java/info/movito/themoviedbapi/TmdbWatchProviders.java index ba3374b4..e7022914 100644 --- a/src/main/java/info/movito/themoviedbapi/TmdbWatchProviders.java +++ b/src/main/java/info/movito/themoviedbapi/TmdbWatchProviders.java @@ -3,20 +3,23 @@ import info.movito.themoviedbapi.model.watchproviders.AvailableRegionResults; import info.movito.themoviedbapi.model.watchproviders.ProviderResults; import info.movito.themoviedbapi.tools.ApiUrl; +import info.movito.themoviedbapi.tools.TmdbApiClient; import info.movito.themoviedbapi.tools.TmdbException; /** * The movie database api for watch providers. See the * documentation for more info. */ -public class TmdbWatchProviders extends AbstractTmdbApi { +public class TmdbWatchProviders { protected static final String TMDB_METHOD_WATCH_PROVIDERS = "watch/providers"; + private final TmdbApiClient tmdbApiClient; + /** * Create a new TmdbWatchProviders instance to call the watch providers TMDb API methods. */ - TmdbWatchProviders(TmdbApi tmdbApi) { - super(tmdbApi); + TmdbWatchProviders(TmdbApiClient tmdbApiClient) { + this.tmdbApiClient = tmdbApiClient; } /** @@ -29,7 +32,7 @@ public class TmdbWatchProviders extends AbstractTmdbApi { public AvailableRegionResults getAvailableRegions(String language) throws TmdbException { ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_WATCH_PROVIDERS) .addLanguage(language); - return mapJsonResult(apiUrl, AvailableRegionResults.class); + return tmdbApiClient.get(apiUrl, AvailableRegionResults.class); } /** @@ -44,7 +47,7 @@ public ProviderResults getMovieProviders(String language, String watchRegion) th ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_WATCH_PROVIDERS, "movie") .addLanguage(language) .addQueryParam("watch_region", watchRegion); - return mapJsonResult(apiUrl, ProviderResults.class); + return tmdbApiClient.get(apiUrl, ProviderResults.class); } /** @@ -61,6 +64,6 @@ public ProviderResults getTvProviders(String language, String watchRegion) throw ApiUrl apiUrl = new ApiUrl(TMDB_METHOD_WATCH_PROVIDERS, "tv") .addLanguage(language) .addQueryParam("watch_region", watchRegion); - return mapJsonResult(apiUrl, ProviderResults.class); + return tmdbApiClient.get(apiUrl, ProviderResults.class); } } diff --git a/src/main/java/info/movito/themoviedbapi/tools/ApiUrl.java b/src/main/java/info/movito/themoviedbapi/tools/ApiUrl.java index 2875d780..8d3d9ce8 100644 --- a/src/main/java/info/movito/themoviedbapi/tools/ApiUrl.java +++ b/src/main/java/info/movito/themoviedbapi/tools/ApiUrl.java @@ -7,7 +7,6 @@ import java.util.Map; import java.util.stream.Collectors; -import info.movito.themoviedbapi.AbstractTmdbApi; import info.movito.themoviedbapi.tools.appendtoresponse.AppendToResponse; import info.movito.themoviedbapi.tools.builders.ParamBuilder; import info.movito.themoviedbapi.tools.sortby.SortBy; @@ -18,11 +17,19 @@ /** * Tmdb Api URL Builder. * - * @author Holger Brandl + * @author Holger Brandl, c-eg */ public class ApiUrl { public static final String TMDB_API_BASE_URL = "https://api.themoviedb.org/3/"; + public static final String PARAM_PAGE = "page"; + + public static final String PARAM_LANGUAGE = "language"; + + public static final String PARAM_ADULT = "include_adult"; + + public static final String PARAM_SORT_BY = "sort_by"; + private static final String APPEND_TO_RESPONSE = "append_to_response"; private final String baseUrl; @@ -156,7 +163,7 @@ public ApiUrl addQueryParamCommandSeparated(String key, String... values) { */ public ApiUrl addPage(Integer page) { if (page != null && page > 0) { - addPathParam(AbstractTmdbApi.PARAM_PAGE, page); + addPathParam(PARAM_PAGE, page); } return this; @@ -169,7 +176,7 @@ public ApiUrl addPage(Integer page) { */ public ApiUrl addLanguage(String language) { if (isNotBlank(language)) { - addPathParam(AbstractTmdbApi.PARAM_LANGUAGE, language); + addPathParam(PARAM_LANGUAGE, language); } return this; @@ -198,7 +205,7 @@ public ApiUrl addAppendToResponses(AppendToResponse... appendToResponse) { */ public ApiUrl addSortBy(SortBy sortBy) { if (sortBy != null) { - addQueryParam(AbstractTmdbApi.PARAM_SORT_BY, sortBy.getValue()); + addQueryParam(PARAM_SORT_BY, sortBy.getValue()); } return this; diff --git a/src/main/java/info/movito/themoviedbapi/tools/TmdbApiClient.java b/src/main/java/info/movito/themoviedbapi/tools/TmdbApiClient.java new file mode 100644 index 00000000..f48cc5af --- /dev/null +++ b/src/main/java/info/movito/themoviedbapi/tools/TmdbApiClient.java @@ -0,0 +1,101 @@ +package info.movito.themoviedbapi.tools; + +import java.util.Optional; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectReader; +import info.movito.themoviedbapi.model.core.responses.ResponseStatus; +import info.movito.themoviedbapi.model.core.responses.TmdbResponseException; +import info.movito.themoviedbapi.util.JsonUtil; + +/** + * Executes requests against the TMDB API and maps the json responses to model classes. Shared by the {@code Tmdb*} api classes. + */ +public class TmdbApiClient { + private static final ObjectReader RESPONSE_STATUS_READER = JsonUtil.OBJECT_MAPPER.readerFor(ResponseStatus.class); + + private final TmdbRequestExecutor requestExecutor; + + /** + * Constructor. + * + * @param requestExecutor the request executor to use to make requests to tmdb. + */ + public TmdbApiClient(TmdbRequestExecutor requestExecutor) { + this.requestExecutor = requestExecutor; + } + + /** + * Executes a GET request and maps the json response to the given class. + * + * @param apiUrl the api url to request + * @param clazz the class to map the response to + * @param the type of class to map to + * @return the mapped class + */ + public T get(ApiUrl apiUrl, Class clazz) throws TmdbException { + return request(apiUrl, null, RequestType.GET, JsonUtil.OBJECT_MAPPER.readerFor(clazz)); + } + + /** + * Executes a GET request and maps the json response to the given generic type. + * + * @param apiUrl the api url to request + * @param resultType the type to map the response to + * @param the type to map to + * @return the mapped result + */ + public T get(ApiUrl apiUrl, TypeReference resultType) throws TmdbException { + return request(apiUrl, null, RequestType.GET, JsonUtil.OBJECT_MAPPER.readerFor(resultType)); + } + + /** + * Executes a request and maps the json response to the given class. + * + * @param apiUrl the api url to request + * @param jsonBody the json body to send, may be {@code null} + * @param requestType the type of request + * @param clazz the class to map the response to + * @param the type of class to map to + * @return the mapped class + */ + public T request(ApiUrl apiUrl, String jsonBody, RequestType requestType, Class clazz) throws TmdbException { + return request(apiUrl, jsonBody, requestType, JsonUtil.OBJECT_MAPPER.readerFor(clazz)); + } + + private T request(ApiUrl apiUrl, String jsonBody, RequestType requestType, ObjectReader objectReader) throws TmdbException { + TmdbResponse response = requestExecutor.execute(new TmdbRequest(apiUrl.buildUrl(), requestType, jsonBody)); + String jsonResponse = response.body(); + + if (!response.isSuccessfulHttpStatus()) { + Optional tmdbResponseCode = parseResponseCode(jsonResponse); + if (tmdbResponseCode.isPresent()) { + throw new TmdbResponseException(tmdbResponseCode.get()); + } + + // An HTTP error with no recognisable TMDB status code (e.g. an HTML gateway error) cannot be mapped to the result type, + throw new TmdbResponseException("TMDB API returned HTTP " + response.statusCode() + ": " + jsonResponse); + } + + try { + return objectReader.readValue(jsonResponse); + } + catch (JsonProcessingException exception) { + throw new TmdbException(exception); + } + } + + /** + * Tries to parse the TMDB status code from a response body. + */ + private static Optional parseResponseCode(String jsonResponse) { + try { + ResponseStatus responseStatus = RESPONSE_STATUS_READER.readValue(jsonResponse); + return Optional.of(responseStatus.getStatusCode()); + } + catch (JsonProcessingException exception) { + return Optional.empty(); + } + } +} diff --git a/src/main/java/info/movito/themoviedbapi/tools/TmdbHttpClient.java b/src/main/java/info/movito/themoviedbapi/tools/TmdbHttpClient.java index fff49da6..d85ef568 100644 --- a/src/main/java/info/movito/themoviedbapi/tools/TmdbHttpClient.java +++ b/src/main/java/info/movito/themoviedbapi/tools/TmdbHttpClient.java @@ -7,21 +7,27 @@ import java.net.http.HttpResponse; import java.time.Duration; import java.util.Objects; +import java.util.Optional; import info.movito.themoviedbapi.model.core.responses.TmdbResponseException; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; /** - * Class to make requests to the movie database api. + * Default {@link TmdbRequestExecutor} backed by the JDK {@link HttpClient}. Rate-limited (HTTP 429) requests are retried, + * honoring the {@code Retry-After} response header when present. */ @AllArgsConstructor @Slf4j -public class TmdbHttpClient implements TmdbUrlReader { +public class TmdbHttpClient implements TmdbRequestExecutor { private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10); private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(30); + private static final int RATE_LIMIT_STATUS_CODE = TmdbResponseCode.REQUEST_LIMIT_EXCEEDED.getHttpStatus(); + private static final int MAX_RATE_LIMIT_RETRIES = 3; + private static final Duration DEFAULT_RATE_LIMIT_RETRY_DELAY = Duration.ofSeconds(1); + private final String apiKey; private final HttpClient httpClient; @@ -38,16 +44,34 @@ public TmdbHttpClient(String apiKey) { } @Override - public String readUrl(String url, String jsonBody, RequestType requestType) throws TmdbResponseException { - log.debug("TMDB API: making request, of type: {}, to: {}", requestType, url); + public TmdbResponse execute(TmdbRequest request) throws TmdbException { + log.debug("TMDB API: making request, of type: {}, to: {}", request.requestType(), request.url()); + + HttpRequest httpRequest = buildHttpRequest(request); + + for (int attempt = 0; ; attempt++) { + HttpResponse response = sendRequest(httpRequest); + if (RATE_LIMIT_STATUS_CODE != response.statusCode() || attempt >= MAX_RATE_LIMIT_RETRIES) { + return new TmdbResponse(response.statusCode(), response.body()); + } + + Duration delay = retryAfterSeconds(response).orElse(DEFAULT_RATE_LIMIT_RETRY_DELAY); + log.info("TMDB API: rate limited (HTTP {}). Waiting {} before retry {} of {}.", + RATE_LIMIT_STATUS_CODE, delay, attempt + 1, MAX_RATE_LIMIT_RETRIES); + sleep(delay); + } + } + + private HttpRequest buildHttpRequest(TmdbRequest request) { HttpRequest.Builder httpRequestBuilder = HttpRequest.newBuilder() - .uri(URI.create(url)) + .uri(URI.create(request.url())) .timeout(REQUEST_TIMEOUT) .header("Authorization", "Bearer " + apiKey) .header("Accept", "application/json"); - switch (requestType) { + String jsonBody = request.jsonBody(); + switch (request.requestType()) { case GET -> httpRequestBuilder.GET(); case POST -> { if (Objects.isNull(jsonBody)) { @@ -59,12 +83,15 @@ public String readUrl(String url, String jsonBody, RequestType requestType) thro } } case DELETE -> httpRequestBuilder.DELETE(); - default -> throw new IllegalStateException("Unsupported request type: " + requestType); + default -> throw new IllegalStateException("Unsupported request type: " + request.requestType()); } + return httpRequestBuilder.build(); + } + + private HttpResponse sendRequest(HttpRequest httpRequest) throws TmdbException { try { - return httpClient.send(httpRequestBuilder.build(), HttpResponse.BodyHandlers.ofString()) - .body(); + return httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); @@ -74,4 +101,24 @@ public String readUrl(String url, String jsonBody, RequestType requestType) thro throw new TmdbResponseException(exception); } } + + /** + * Returns the delay requested by the {@code Retry-After} response header, if present and expressed as a number of seconds. + */ + private static Optional retryAfterSeconds(HttpResponse response) { + return response.headers().firstValue("Retry-After") + .map(String::trim) + .filter(value -> !value.isEmpty() && value.chars().allMatch(Character::isDigit)) + .map(value -> Duration.ofSeconds(Long.parseLong(value))); + } + + private static void sleep(Duration delay) throws TmdbException { + try { + Thread.sleep(delay.toMillis()); + } + catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new TmdbResponseException(exception); + } + } } diff --git a/src/main/java/info/movito/themoviedbapi/tools/TmdbRequest.java b/src/main/java/info/movito/themoviedbapi/tools/TmdbRequest.java new file mode 100644 index 00000000..50ab4ac5 --- /dev/null +++ b/src/main/java/info/movito/themoviedbapi/tools/TmdbRequest.java @@ -0,0 +1,30 @@ +package info.movito.themoviedbapi.tools; + +import java.util.Objects; + +/** + * A request to be made against the TMDB API. + * + * @param url the url to make the request to + * @param requestType the type of request to make + * @param jsonBody the json body to send with the request, only used for {@link RequestType#POST} requests, may be {@code null} + */ +public record TmdbRequest(String url, RequestType requestType, String jsonBody) { + /** + * Validates that the required components of the request are present. + */ + public TmdbRequest { + Objects.requireNonNull(url, "url must not be null"); + Objects.requireNonNull(requestType, "requestType must not be null"); + } + + /** + * Creates a request without a body. + * + * @param url the url to make the request to + * @param requestType the type of request to make + */ + public TmdbRequest(String url, RequestType requestType) { + this(url, requestType, null); + } +} diff --git a/src/main/java/info/movito/themoviedbapi/tools/TmdbRequestExecutor.java b/src/main/java/info/movito/themoviedbapi/tools/TmdbRequestExecutor.java new file mode 100644 index 00000000..707b17d2 --- /dev/null +++ b/src/main/java/info/movito/themoviedbapi/tools/TmdbRequestExecutor.java @@ -0,0 +1,15 @@ +package info.movito.themoviedbapi.tools; + +/** + * Interface for executing requests against the TMDB API. + */ +public interface TmdbRequestExecutor { + /** + * Executes the given request and returns the response. + * + * @param request the request to execute + * @return the response from the movie database api + * @throws TmdbException if the request could not be executed + */ + TmdbResponse execute(TmdbRequest request) throws TmdbException; +} diff --git a/src/main/java/info/movito/themoviedbapi/tools/TmdbResponse.java b/src/main/java/info/movito/themoviedbapi/tools/TmdbResponse.java new file mode 100644 index 00000000..6227ff7b --- /dev/null +++ b/src/main/java/info/movito/themoviedbapi/tools/TmdbResponse.java @@ -0,0 +1,16 @@ +package info.movito.themoviedbapi.tools; + +/** + * A response returned from the TMDB API. + * + * @param statusCode the HTTP status code of the response + * @param body the raw response body + */ +public record TmdbResponse(int statusCode, String body) { + /** + * Returns whether the HTTP status code indicates success (2xx). + */ + public boolean isSuccessfulHttpStatus() { + return statusCode >= 200 && statusCode < 300; + } +} diff --git a/src/main/java/info/movito/themoviedbapi/tools/TmdbResponseCode.java b/src/main/java/info/movito/themoviedbapi/tools/TmdbResponseCode.java index 8587f7f0..a68e365a 100644 --- a/src/main/java/info/movito/themoviedbapi/tools/TmdbResponseCode.java +++ b/src/main/java/info/movito/themoviedbapi/tools/TmdbResponseCode.java @@ -1,7 +1,6 @@ package info.movito.themoviedbapi.tools; import java.util.Arrays; -import java.util.Set; import com.fasterxml.jackson.annotation.JsonCreator; import lombok.Getter; @@ -16,60 +15,58 @@ @RequiredArgsConstructor @ToString public enum TmdbResponseCode { - SUCCESS(1, 200, true, "Success."), - INVALID_SERVICE(2, 501, false, "Invalid service: this service does not exist."), - AUTHENTICATION_FAILED(3, 401, false, "Authentication failed: You do not have permissions to access the service."), - INVALID_FORMAT(4, 405, false, "Invalid format: This service doesn't exist in that format."), - INVALID_PARAMETERS(5, 422, false, "Invalid parameters: Your request parameters are incorrect."), - INVALID_PRE_REQUISITE_ID(6, 404, false, "Invalid id: The pre-requisite id is invalid or not found."), - INVALID_API_KEY(7, 401, false, "Invalid API key: You must be granted a valid key."), - DUPLICATE_ENTRY(8, 403, false, "Duplicate entry: The data you tried to submit already exists."), - SERVICE_OFFLINE(9, 503, false, "Service offline: This service is temporarily offline, try again later."), - SUSPENDED_API_KEY(10, 401, false, "Suspended API key: Access to your account has been suspended, contact TMDB."), - INTERNAL_ERROR(11, 500, false, "Internal error: Something went wrong, contact TMDB."), - ITEM_UPDATED(12, 201, true, "The item/record was updated successfully."), - ITEM_DELETED(13, 200, true, "The item/record was deleted successfully."), - AUTHENTICATION_FAILED_2(14, 401, false, "Authentication failed."), - FAILED(15, 500, false, "Failed."), - DEVICE_DENIED(16, 401, false, "Device denied."), - SESSION_DENIED(17, 401, false, "Session denied."), - VALIDATION_FAILED(18, 400, false, "Validation failed."), - INVALID_ACCEPT_HEADER(19, 406, false, "Invalid accept header."), - INVALID_DATE_RANGE(20, 422, false, "Invalid date range: Should be a range no longer than 14 days."), - ENTRY_NOT_FOUND(21, 200, false, "Entry not found: The item you are trying to edit cannot be found."), - INVALID_PAGE(22, 400, false, "Invalid page: Pages start at 1 and max at 500. They are expected to be an integer."), - INVALID_DATE(23, 400, false, "Invalid date: Format needs to be YYYY-MM-DD."), - REQUEST_TIMEOUT(24, 504, false, "Your request to the backend server timed out. Try again."), - REQUEST_LIMIT_EXCEEDED(25, 429, false, "Your request count (#) is over the allowed limit of (40)."), - USERNAME_AND_PASSWORD_REQUIRED(26, 400, false, "You must provide a username and password."), - TOO_MANY_APPEND_TO_RESPONSE_OBJECTS(27, 400, false, "Too many append to response objects: The maximum number of remote calls is 20."), - INVALID_TIMEZONE(28, 400, false, "Invalid timezone: Please consult the documentation for a valid timezone."), - ACTION_CONFIRMATION_REQUIRED(29, 400, false, "You must confirm this action: Please provide a confirm=true parameter."), - INVALID_USERNAME_AND_OR_PASSWORD(30, 401, false, "Invalid username and/or password: You did not provide a valid login."), - ACCOUNT_DISABLED(31, 401, false, "Account disabled: Your account is no longer active. Contact TMDB if this is an error."), - EMAIL_NOT_VERIFIED(32, 401, false, "Email not verified: Your email address has not been verified."), - INVALID_REQUEST_TOKEN(33, 401, false, "Invalid request token: The request token is either expired or invalid."), - RESOURCE_NOT_FOUND(34, 404, false, "The resource you requested could not be found."), - INVALID_TOKEN(35, 401, false, "Invalid token."), - TOKEN_NOT_GRANTED_WRITE_PERMISSION(36, 401, false, "This token hasn't been granted write permission by the user."), - REQUESTED_SESSION_NOT_FOUND(37, 404, false, "The requested session could not be found."), - PERMISSION_DENIED(38, 401, false, "You don't have permission to edit this resource."), - RESOURCE_PRIVATE(39, 401, false, "This resource is private."), - NOTHING_TO_UPDATE(40, 200, false, "Nothing to update."), - REQUEST_TOKEN_NOT_APPROVED(41, 422, false, "This request token hasn't been approved by the user."), - REQUEST_METHOD_NOT_SUPPORTED(42, 405, false, "This request method is not supported for this resource."), - COULD_NOT_CONNECT_TO_BACKEND_SERVER(43, 502, false, "Couldn't connect to the backend server."), - INVALID_ID(44, 500, false, "The ID is invalid."), - USER_SUSPENDED(45, 403, false, "This user has been suspended."), - API_UNDERGOING_MAINTENANCE(46, 503, false, "The API is undergoing maintenance. Try again later."), - INVALID_INPUT(47, 400, false, "The input is not valid."); + SUCCESS(1, 200, "Success."), + INVALID_SERVICE(2, 501, "Invalid service: this service does not exist."), + AUTHENTICATION_FAILED(3, 401, "Authentication failed: You do not have permissions to access the service."), + INVALID_FORMAT(4, 405, "Invalid format: This service doesn't exist in that format."), + INVALID_PARAMETERS(5, 422, "Invalid parameters: Your request parameters are incorrect."), + INVALID_PRE_REQUISITE_ID(6, 404, "Invalid id: The pre-requisite id is invalid or not found."), + INVALID_API_KEY(7, 401, "Invalid API key: You must be granted a valid key."), + DUPLICATE_ENTRY(8, 403, "Duplicate entry: The data you tried to submit already exists."), + SERVICE_OFFLINE(9, 503, "Service offline: This service is temporarily offline, try again later."), + SUSPENDED_API_KEY(10, 401, "Suspended API key: Access to your account has been suspended, contact TMDB."), + INTERNAL_ERROR(11, 500, "Internal error: Something went wrong, contact TMDB."), + ITEM_UPDATED(12, 201, "The item/record was updated successfully."), + ITEM_DELETED(13, 200, "The item/record was deleted successfully."), + AUTHENTICATION_FAILED_2(14, 401, "Authentication failed."), + FAILED(15, 500, "Failed."), + DEVICE_DENIED(16, 401, "Device denied."), + SESSION_DENIED(17, 401, "Session denied."), + VALIDATION_FAILED(18, 400, "Validation failed."), + INVALID_ACCEPT_HEADER(19, 406, "Invalid accept header."), + INVALID_DATE_RANGE(20, 422, "Invalid date range: Should be a range no longer than 14 days."), + ENTRY_NOT_FOUND(21, 200, "Entry not found: The item you are trying to edit cannot be found."), + INVALID_PAGE(22, 400, "Invalid page: Pages start at 1 and max at 500. They are expected to be an integer."), + INVALID_DATE(23, 400, "Invalid date: Format needs to be YYYY-MM-DD."), + REQUEST_TIMEOUT(24, 504, "Your request to the backend server timed out. Try again."), + REQUEST_LIMIT_EXCEEDED(25, 429, "Your request count (#) is over the allowed limit of (40)."), + USERNAME_AND_PASSWORD_REQUIRED(26, 400, "You must provide a username and password."), + TOO_MANY_APPEND_TO_RESPONSE_OBJECTS(27, 400, "Too many append to response objects: The maximum number of remote calls is 20."), + INVALID_TIMEZONE(28, 400, "Invalid timezone: Please consult the documentation for a valid timezone."), + ACTION_CONFIRMATION_REQUIRED(29, 400, "You must confirm this action: Please provide a confirm=true parameter."), + INVALID_USERNAME_AND_OR_PASSWORD(30, 401, "Invalid username and/or password: You did not provide a valid login."), + ACCOUNT_DISABLED(31, 401, "Account disabled: Your account is no longer active. Contact TMDB if this is an error."), + EMAIL_NOT_VERIFIED(32, 401, "Email not verified: Your email address has not been verified."), + INVALID_REQUEST_TOKEN(33, 401, "Invalid request token: The request token is either expired or invalid."), + RESOURCE_NOT_FOUND(34, 404, "The resource you requested could not be found."), + INVALID_TOKEN(35, 401, "Invalid token."), + TOKEN_NOT_GRANTED_WRITE_PERMISSION(36, 401, "This token hasn't been granted write permission by the user."), + REQUESTED_SESSION_NOT_FOUND(37, 404, "The requested session could not be found."), + PERMISSION_DENIED(38, 401, "You don't have permission to edit this resource."), + RESOURCE_PRIVATE(39, 401, "This resource is private."), + NOTHING_TO_UPDATE(40, 200, "Nothing to update."), + REQUEST_TOKEN_NOT_APPROVED(41, 422, "This request token hasn't been approved by the user."), + REQUEST_METHOD_NOT_SUPPORTED(42, 405, "This request method is not supported for this resource."), + COULD_NOT_CONNECT_TO_BACKEND_SERVER(43, 502, "Couldn't connect to the backend server."), + INVALID_ID(44, 500, "The ID is invalid."), + USER_SUSPENDED(45, 403, "This user has been suspended."), + API_UNDERGOING_MAINTENANCE(46, 503, "The API is undergoing maintenance. Try again later."), + INVALID_INPUT(47, 400, "The input is not valid."); private final int tmdbCode; private final int httpStatus; - private final boolean success; - private final String message; /** @@ -84,40 +81,4 @@ public static TmdbResponseCode fromCode(int tmdbCode) { .findFirst() .orElse(null); } - - /** - * Returns all the error responses. - */ - public static Set getErrorResponses() { - return Arrays.stream(TmdbResponseCode.values()) - .filter(responseCode -> !responseCode.isSuccess()) - .collect(java.util.stream.Collectors.toSet()); - } - - /** - * Returns all the successful responses. - */ - public static Set getSuccessResponses() { - return Arrays.stream(TmdbResponseCode.values()) - .filter(TmdbResponseCode::isSuccess) - .collect(java.util.stream.Collectors.toSet()); - } - - /** - * Returns all the error codes. - */ - public static Set getErrorCodes() { - return getErrorResponses().stream() - .map(TmdbResponseCode::getTmdbCode) - .collect(java.util.stream.Collectors.toSet()); - } - - /** - * Returns all the successful codes. - */ - public static Set getSuccessCodes() { - return getSuccessResponses().stream() - .map(TmdbResponseCode::getTmdbCode) - .collect(java.util.stream.Collectors.toSet()); - } } diff --git a/src/main/java/info/movito/themoviedbapi/tools/TmdbUrlReader.java b/src/main/java/info/movito/themoviedbapi/tools/TmdbUrlReader.java deleted file mode 100644 index 40a6a0cd..00000000 --- a/src/main/java/info/movito/themoviedbapi/tools/TmdbUrlReader.java +++ /dev/null @@ -1,19 +0,0 @@ -package info.movito.themoviedbapi.tools; - -import info.movito.themoviedbapi.model.core.responses.TmdbResponseException; - -/** - * Interface for reading URLs from TMDB API. - */ -public interface TmdbUrlReader { - /** - * Reads a url and returns the response. - * - * @param url the url to make the request to - * @param jsonBody the json body to send with the request - * @param requestType the type of request to make - * @return the response from the movie database api - * @throws TmdbResponseException if the response was not successful - */ - String readUrl(String url, String jsonBody, RequestType requestType) throws TmdbResponseException; -} diff --git a/src/main/java/info/movito/themoviedbapi/tools/builders/discover/DiscoverParamBuilder.java b/src/main/java/info/movito/themoviedbapi/tools/builders/discover/DiscoverParamBuilder.java index d971c7e7..cf16229c 100644 --- a/src/main/java/info/movito/themoviedbapi/tools/builders/discover/DiscoverParamBuilder.java +++ b/src/main/java/info/movito/themoviedbapi/tools/builders/discover/DiscoverParamBuilder.java @@ -5,14 +5,12 @@ import java.util.Map; import java.util.stream.Collectors; -import info.movito.themoviedbapi.AbstractTmdbApi; +import info.movito.themoviedbapi.tools.ApiUrl; import info.movito.themoviedbapi.tools.builders.ParamBuilder; import lombok.AccessLevel; import lombok.Getter; import org.apache.commons.lang3.StringUtils; -import static info.movito.themoviedbapi.AbstractTmdbApi.PARAM_ADULT; - /** *

Abstract class for shared parameters to build a 'discover' parameter map. * This allows you to just add the search components you are concerned with.

@@ -62,7 +60,7 @@ public T page(int page) { throw new IllegalArgumentException("Page must be greater than 0"); } - params.put(AbstractTmdbApi.PARAM_PAGE, String.valueOf(page)); + params.put(ApiUrl.PARAM_PAGE, String.valueOf(page)); return me(); } @@ -71,12 +69,12 @@ public T language(String language) { throw new IllegalArgumentException("Language must be set"); } - params.put(AbstractTmdbApi.PARAM_LANGUAGE, language); + params.put(ApiUrl.PARAM_LANGUAGE, language); return me(); } public T includeAdult(boolean includeAdult) { - params.put(PARAM_ADULT, String.valueOf(includeAdult)); + params.put(ApiUrl.PARAM_ADULT, String.valueOf(includeAdult)); return me(); } diff --git a/src/test/java/info/movito/themoviedbapi/AbstractTmdbApiTest.java b/src/test/java/info/movito/themoviedbapi/AbstractTmdbApiTest.java index 799e89b2..a90eec48 100644 --- a/src/test/java/info/movito/themoviedbapi/AbstractTmdbApiTest.java +++ b/src/test/java/info/movito/themoviedbapi/AbstractTmdbApiTest.java @@ -1,10 +1,11 @@ package info.movito.themoviedbapi; -import info.movito.themoviedbapi.tools.TmdbUrlReader; +import info.movito.themoviedbapi.tools.TmdbRequestExecutor; import lombok.Getter; import org.junit.jupiter.api.BeforeEach; - -import static org.mockito.Mockito.mock; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; /** * Abstract test class for TMDB API tests. @@ -12,20 +13,21 @@ * @param the type of TMDB API to test. */ @Getter -public abstract class AbstractTmdbApiTest { +@ExtendWith(MockitoExtension.class) +public abstract class AbstractTmdbApiTest { private TmdbApi tmdbApi; - private TmdbUrlReader tmdbUrlReader; + @Mock + private TmdbRequestExecutor requestExecutor; private T apiToTest; /** - * Sets up TmdbApi class with a mocked TmdbUrlReader. + * Sets up TmdbApi class with a mocked TmdbRequestExecutor. */ @BeforeEach public void setUp() { - tmdbUrlReader = mock(TmdbUrlReader.class); - tmdbApi = new TmdbApi(tmdbUrlReader); + tmdbApi = new TmdbApi(requestExecutor); apiToTest = createApiToTest(); } diff --git a/src/test/java/info/movito/themoviedbapi/TmdbAccountTest.java b/src/test/java/info/movito/themoviedbapi/TmdbAccountTest.java index cea10220..e5cbd529 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbAccountTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbAccountTest.java @@ -16,6 +16,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.TmdbResponseCode; import info.movito.themoviedbapi.tools.sortby.AccountSortBy; import info.movito.themoviedbapi.util.JsonUtil; @@ -43,7 +45,7 @@ public TmdbAccount createApiToTest() { public void testGetAccount() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/account/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234?session_id=testSessionId"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Account account = getApiToTest().getDetails(1234, "testSessionId"); assertNotNull(account); @@ -68,7 +70,7 @@ public void testAddFavourite() throws TmdbException, IOException { String jsonBody = JsonUtil.toJson(requestBody); String body = TestUtils.readTestFile("api_responses/account/add_favourite.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().addFavorite(accountId, sessionId, mediaId, mediaType); assertNotNull(responseStatus); @@ -94,7 +96,7 @@ public void testRemoveFavorite() throws TmdbException, IOException { String jsonBody = JsonUtil.toJson(requestBody); String body = TestUtils.readTestFile("api_responses/account/add_favourite.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().removeFavorite(accountId, sessionId, mediaId, mediaType); assertNotNull(responseStatus); @@ -120,7 +122,7 @@ public void testAddToWatchList() throws IOException, TmdbException { String jsonBody = JsonUtil.toJson(requestBody); String body = TestUtils.readTestFile("api_responses/account/add_to_watchlist.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().addToWatchList(accountId, sessionId, mediaId, mediaType); assertNotNull(responseStatus); @@ -146,7 +148,7 @@ public void testRemoveFromWatchList() throws IOException, TmdbException { String jsonBody = JsonUtil.toJson(requestBody); String body = TestUtils.readTestFile("api_responses/account/add_to_watchlist.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().removeFromWatchList(accountId, sessionId, mediaId, mediaType); assertNotNull(responseStatus); @@ -168,7 +170,7 @@ public void testGetFavouriteMovies() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/favorite/movies?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc"; String body = TestUtils.readTestFile("api_responses/account/favourite_movies.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage movieResultsPage = getApiToTest().getFavoriteMovies(accountId, sessionId, language, page, sortBy); assertNotNull(movieResultsPage); @@ -193,7 +195,7 @@ public void testGetFavouriteTv() throws IOException, TmdbException { String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/favorite/tv?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc"; String body = TestUtils.readTestFile("api_responses/account/favourite_tv.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvSeriesResultsPage = getApiToTest().getFavoriteTv(accountId, sessionId, language, page, sortBy); assertNotNull(tvSeriesResultsPage); @@ -211,7 +213,7 @@ public void testGetLists() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/lists?session_id=testSessionId&page=1"; String body = TestUtils.readTestFile("api_responses/account/lists.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieListResultsPage movieListResultsPage = getApiToTest().getLists(accountId, sessionId, page); assertNotNull(movieListResultsPage); @@ -232,7 +234,7 @@ public void testGetRatedMovies() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/rated/movies?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc"; String body = TestUtils.readTestFile("api_responses/account/rated_movies.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RatedMovieResultsPage ratedMovieResultsPage = getApiToTest().getRatedMovies(accountId, sessionId, language, page, sortBy); assertNotNull(ratedMovieResultsPage); @@ -257,7 +259,7 @@ public void testGetRatedTvSeries() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/rated/tv?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc"; String body = TestUtils.readTestFile("api_responses/account/rated_tv.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RatedTvSeriesResultsPage ratedTvSeriesResultsPage = getApiToTest().getRatedTvSeries(accountId, sessionId, language, page, sortBy); assertNotNull(ratedTvSeriesResultsPage); @@ -278,7 +280,7 @@ public void testGetRatedTvEpisodes() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/rated/tv/episodes?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc"; String body = TestUtils.readTestFile("api_responses/account/rated_tv_episodes.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RatedTvEpisodeResultsPage ratedTvEpisodesResultsPage = getApiToTest().getRatedTvEpisodes(accountId, sessionId, language, page, sortBy); @@ -300,7 +302,7 @@ public void testGetWatchListMovies() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/watchlist/movies?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc"; String body = TestUtils.readTestFile("api_responses/account/watchlist_movies.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage movieResultsPage = getApiToTest().getWatchListMovies(accountId, sessionId, language, page, sortBy); assertNotNull(movieResultsPage); @@ -325,7 +327,7 @@ public void testGetWatchListTvSeries() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/watchlist/tv?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc"; String body = TestUtils.readTestFile("api_responses/account/watchlist_tv.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvSeriesResultsPage = getApiToTest().getWatchListTvSeries(accountId, sessionId, language, page, sortBy); assertNotNull(tvSeriesResultsPage); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbAuthenticationTest.java b/src/test/java/info/movito/themoviedbapi/TmdbAuthenticationTest.java index 44c402d8..b3e8d021 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbAuthenticationTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbAuthenticationTest.java @@ -12,6 +12,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.util.JsonUtil; import org.junit.jupiter.api.Test; @@ -41,7 +43,7 @@ public TmdbAuthentication createApiToTest() { public void testCreateGuestSession() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/authentication/create_guest_session.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH + "/guest_session/new"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); GuestSession guestSession = getApiToTest().createGuestSession(); assertNotNull(guestSession); @@ -55,7 +57,7 @@ public void testCreateGuestSession() throws TmdbException, IOException { public void testCreateRequestToken() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/authentication/create_request_token.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH + "/token/new"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RequestToken requestToken = getApiToTest().createRequestToken(); assertNotNull(requestToken); @@ -69,7 +71,7 @@ public void testCreateRequestToken() throws TmdbException, IOException { public void testGetTmdbAuthenticationUrlForRequestToken() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/authentication/create_request_token.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH + "/token/new"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RequestToken requestToken = getApiToTest().createRequestToken(); String authUrl = TmdbAuthentication.getTmdbAuthenticationUrlForRequestToken(requestToken, "redirectUrl"); @@ -84,7 +86,7 @@ public void testGetTmdbAuthenticationUrlForRequestToken() throws TmdbException, public void testGetTmdbAuthenticationUrlForRequestTokenUnccessfulRequestToken() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/authentication/create_request_token.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH + "/token/new"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RequestToken requestToken = getApiToTest().createRequestToken(); requestToken.setSuccess(false); @@ -106,7 +108,7 @@ public void testCreateSession() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH + "/session/new"; String body = TestUtils.readTestFile("api_responses/authentication/create_session.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); RequestToken requestToken = new RequestToken(); requestToken.setSuccess(true); @@ -143,7 +145,7 @@ public void testCreateAuthenticatedRequestToken() throws TmdbException, IOExcept String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH + "/token/validate_with_login"; String body = TestUtils.readTestFile("api_responses/authentication/create_session_with_login.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); RequestToken authenticatedRequestToken = getApiToTest().createAuthenticatedRequestToken(requestToken, "username", "password"); assertNotNull(authenticatedRequestToken); @@ -173,7 +175,7 @@ public void testDeleteSession() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH + "/session"; String body = TestUtils.readTestFile("api_responses/authentication/delete_session.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.DELETE)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.DELETE, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatusDelete responseStatusDelete = getApiToTest().deleteSession("sessionId"); assertNotNull(responseStatusDelete); @@ -197,7 +199,7 @@ public void testDeleteSessionNullSession() { public void testValidateKey() throws TmdbException, IOException { String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH; String body = TestUtils.readTestFile("api_responses/authentication/validate_key.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ResponseStatusAuthentication responseStatusAuthentication = getApiToTest().validateKey(); assertNotNull(responseStatusAuthentication); @@ -213,7 +215,8 @@ public void testValidateKey() throws TmdbException, IOException { public void testValidateKeyUnsuccessful() throws IOException, TmdbException { String url = TMDB_API_BASE_URL + TMDB_METHOD_AUTH; String body = TestUtils.readTestFile("api_responses/authentication/validate_key_unsuccessful.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))) + .thenReturn(new TmdbResponse(INVALID_API_KEY.getHttpStatus(), body)); TmdbResponseException exception = assertThrowsExactly(TmdbResponseException.class, getApiToTest()::validateKey); assertEquals(INVALID_API_KEY, exception.getResponseCode()); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbCertificationsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbCertificationsTest.java index b0eb378d..798753c7 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbCertificationsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbCertificationsTest.java @@ -6,6 +6,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbCertifications.TMDB_METHOD_CERTIFICATIONS; @@ -31,7 +33,7 @@ public TmdbCertifications createApiToTest() { public void testGetMovieCertifications() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/certifications/movie.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_CERTIFICATIONS + "/" + TMDB_METHOD_MOVIE_CERTIFICATIONS; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); CertificationResults movieCertifications = getApiToTest().getMovieCertifications(); assertNotNull(movieCertifications); @@ -45,7 +47,7 @@ public void testGetMovieCertifications() throws IOException, TmdbException { public void testGetTvCertifications() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/certifications/tv.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_CERTIFICATIONS + "/" + TMDB_METHOD_TV_CERTIFICATIONS; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); CertificationResults tvCertifications = getApiToTest().getTvCertifications(); assertNotNull(tvCertifications); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbChangesTest.java b/src/test/java/info/movito/themoviedbapi/TmdbChangesTest.java index 6ada3e36..d4ab9c52 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbChangesTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbChangesTest.java @@ -6,6 +6,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbChanges.TMDB_METHOD_CHANGES; @@ -37,7 +39,7 @@ public void testGetMovieChangesList() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/changes/movie_list.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/" + TMDB_METHOD_CHANGES + "?start_date=" + startDate + "&end_date=" + endDate + "&page=" + page; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ChangesResultsPage changesResultsPage = getApiToTest().getMovieChangesList(startDate, endDate, page); assertNotNull(changesResultsPage); @@ -56,7 +58,7 @@ public void testGetPeopleChangesList() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/changes/people_list.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/" + TMDB_METHOD_CHANGES + "?start_date=" + startDate + "&end_date=" + endDate + "&page=" + page; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ChangesResultsPage changesResultsPage = getApiToTest().getPeopleChangesList(startDate, endDate, page); assertNotNull(changesResultsPage); @@ -75,7 +77,7 @@ public void testGetTvChangesList() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/changes/tv_list.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/" + TMDB_METHOD_CHANGES + "?start_date=" + startDate + "&end_date=" + endDate + "&page=" + page; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ChangesResultsPage changesResultsPage = getApiToTest().getTvChangesList(startDate, endDate, page); assertNotNull(changesResultsPage); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbCollectionsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbCollectionsTest.java index d85d75d4..d325cf10 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbCollectionsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbCollectionsTest.java @@ -9,6 +9,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbCollections.TMDB_METHOD_COLLECTION; @@ -37,7 +39,7 @@ public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/collections/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_COLLECTION + "/" + collectionId + "?" + "language=" + language; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); CollectionInfo collectionInfo = getApiToTest().getDetails(collectionId, language); assertNotNull(collectionInfo); @@ -56,7 +58,7 @@ public void testGetImages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/collections/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_COLLECTION + "/" + collectionId + "/images?language=" + language; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Images images = getApiToTest().getImages(collectionId, language); assertNotNull(images); @@ -75,7 +77,7 @@ public void testGetImagesMultipleLanguages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/collections/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_COLLECTION + "/" + collectionId + "/images?include_image_language=en%2Cit"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Images images = getApiToTest().getImages(collectionId, null, includeImageLanguage); assertNotNull(images); @@ -91,7 +93,7 @@ public void testGetTranslations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/collections/translations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_COLLECTION + "/" + collectionId + "/translations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); List translations = getApiToTest().getTranslations(collectionId); assertFalse(translations.isEmpty()); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbCompaniesTest.java b/src/test/java/info/movito/themoviedbapi/TmdbCompaniesTest.java index 1d87de58..f9ef30fa 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbCompaniesTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbCompaniesTest.java @@ -8,6 +8,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbCompanies.TMDB_METHOD_COMPANY; @@ -33,7 +35,7 @@ public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/companies/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_COMPANY + "/" + companyId; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Company company = getApiToTest().getDetails(companyId); assertNotNull(company); @@ -49,7 +51,7 @@ public void testGetAlternativeNames() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/companies/alternative_names.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_COMPANY + "/" + companyId + "/alternative_names"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AlternativeNamesResultsPage alternativeNamesResultsPage = getApiToTest().getAlternativeNames(1); assertNotNull(alternativeNamesResultsPage); @@ -65,7 +67,7 @@ public void testGetImages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/companies/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_COMPANY + "/" + companyId + "/images"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ImageResults logoImageResults = getApiToTest().getImages(1); assertNotNull(logoImageResults); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbConfigurationTest.java b/src/test/java/info/movito/themoviedbapi/TmdbConfigurationTest.java index 6ec37379..aae3152d 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbConfigurationTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbConfigurationTest.java @@ -11,6 +11,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbConfiguration.TMDB_METHOD_CONFIGURATION; @@ -35,7 +37,7 @@ public TmdbConfiguration createApiToTest() { public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/configuration/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_CONFIGURATION; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Configuration configuration = getApiToTest().getDetails(); assertNotNull(configuration); @@ -49,7 +51,7 @@ public void testGetDetails() throws IOException, TmdbException { public void testGetCountries() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/configuration/countries.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_CONFIGURATION + "/countries"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); List countries = getApiToTest().getCountries(null); assertNotNull(countries); @@ -67,7 +69,7 @@ public void testGetCountries() throws IOException, TmdbException { public void testGetJobs() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/configuration/jobs.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_CONFIGURATION + "/jobs"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); List jobs = getApiToTest().getJobs(); assertNotNull(jobs); @@ -85,7 +87,7 @@ public void testGetJobs() throws IOException, TmdbException { public void testGetLanguages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/configuration/languages.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_CONFIGURATION + "/languages"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); List languages = getApiToTest().getLanguages(); assertNotNull(languages); @@ -103,7 +105,7 @@ public void testGetLanguages() throws IOException, TmdbException { public void testGetPrimaryTranslations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/configuration/primary_translations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_CONFIGURATION + "/primary_translations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); List primaryTranslations = getApiToTest().getPrimaryTranslations(); assertNotNull(primaryTranslations); @@ -120,7 +122,7 @@ public void testGetPrimaryTranslations() throws IOException, TmdbException { public void testGetTimezones() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/configuration/timezones.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_CONFIGURATION + "/timezones"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); List timezones = getApiToTest().getTimezones(); assertNotNull(timezones); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbDiscoverTest.java b/src/test/java/info/movito/themoviedbapi/TmdbDiscoverTest.java index 6960a90b..2d1ee535 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbDiscoverTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbDiscoverTest.java @@ -9,6 +9,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.builders.discover.DiscoverMovieParamBuilder; import info.movito.themoviedbapi.tools.builders.discover.DiscoverTvParamBuilder; import org.junit.jupiter.api.Test; @@ -36,7 +38,7 @@ public TmdbDiscover createApiToTest() { public void testGetMovie() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/discover/movies.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_DISCOVER + "/" + TMDB_METHOD_MOVIE + "?page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); DiscoverMovieParamBuilder discoverMovieParamBuilder = new DiscoverMovieParamBuilder() .page(1); @@ -57,7 +59,7 @@ public void testGetMovie() throws IOException, TmdbException { public void testGetMovieNullBuilder() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/discover/movies.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_DISCOVER + "/" + TMDB_METHOD_MOVIE; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage movieResultsPage = getApiToTest().getMovie(null); assertNotNull(movieResultsPage); @@ -75,7 +77,7 @@ public void testGetMovieNullBuilder() throws IOException, TmdbException { public void testGetTv() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/discover/tv.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_DISCOVER + "/" + TMDB_METHOD_TV + "?page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); DiscoverTvParamBuilder discoverTvParamBuilder = new DiscoverTvParamBuilder() .page(1); @@ -92,7 +94,7 @@ public void testGetTv() throws IOException, TmdbException { public void testGetTvNullBuilder() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/discover/tv.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_DISCOVER + "/" + TMDB_METHOD_TV; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvSeriesResultsPage = getApiToTest().getTv(null); assertNotNull(tvSeriesResultsPage); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbFindTest.java b/src/test/java/info/movito/themoviedbapi/TmdbFindTest.java index eb63dcd5..cf9c9bdf 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbFindTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbFindTest.java @@ -8,6 +8,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.model.time.ExternalSource; import org.junit.jupiter.api.Test; @@ -32,10 +34,9 @@ public TmdbFind createApiToTest() { public void testFindByIdMovieResults() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/find/movie_results.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_FIND + "/nm0000158?external_source=imdb_id"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); - TmdbFind tmdbFind = new TmdbFind(getTmdbApi()); - FindResults findResults = tmdbFind.findById("nm0000158", ExternalSource.IMDB_ID, null); + FindResults findResults = getApiToTest().findById("nm0000158", ExternalSource.IMDB_ID, null); assertNotNull(findResults); ValidatorConfig validatorConfig = ValidatorConfig.builder() @@ -57,10 +58,9 @@ public void testFindByIdMovieResults() throws IOException, TmdbException { public void testFindByIdPersonResults() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/find/person_results.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_FIND + "/nm0000158?external_source=imdb_id"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); - TmdbFind tmdbFind = new TmdbFind(getTmdbApi()); - FindResults findResults = tmdbFind.findById("nm0000158", ExternalSource.IMDB_ID, null); + FindResults findResults = getApiToTest().findById("nm0000158", ExternalSource.IMDB_ID, null); assertNotNull(findResults); ValidatorConfig validatorConfig = ValidatorConfig.builder() @@ -81,10 +81,9 @@ public void testFindByIdPersonResults() throws IOException, TmdbException { public void testFindByIdTvResults() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/find/tv_results.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_FIND + "/nm0000158?external_source=imdb_id"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); - TmdbFind tmdbFind = new TmdbFind(getTmdbApi()); - FindResults findResults = tmdbFind.findById("nm0000158", ExternalSource.IMDB_ID, null); + FindResults findResults = getApiToTest().findById("nm0000158", ExternalSource.IMDB_ID, null); assertNotNull(findResults); ValidatorConfig validatorConfig = ValidatorConfig.builder() @@ -105,10 +104,9 @@ public void testFindByIdTvResults() throws IOException, TmdbException { public void testFindByIdTvSeasonResults() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/find/tv_season_results.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_FIND + "/nm0000158?external_source=imdb_id"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); - TmdbFind tmdbFind = new TmdbFind(getTmdbApi()); - FindResults findResults = tmdbFind.findById("nm0000158", ExternalSource.IMDB_ID, null); + FindResults findResults = getApiToTest().findById("nm0000158", ExternalSource.IMDB_ID, null); assertNotNull(findResults); ValidatorConfig validatorConfig = ValidatorConfig.builder() @@ -129,10 +127,9 @@ public void testFindByIdTvSeasonResults() throws IOException, TmdbException { public void testFindByIdTvEpisodeResults() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/find/tv_episode_results.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_FIND + "/nm0000158?external_source=imdb_id"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); - TmdbFind tmdbFind = new TmdbFind(getTmdbApi()); - FindResults findResults = tmdbFind.findById("nm0000158", ExternalSource.IMDB_ID, null); + FindResults findResults = getApiToTest().findById("nm0000158", ExternalSource.IMDB_ID, null); assertNotNull(findResults); ValidatorConfig validatorConfig = ValidatorConfig.builder() diff --git a/src/test/java/info/movito/themoviedbapi/TmdbGenresTest.java b/src/test/java/info/movito/themoviedbapi/TmdbGenresTest.java index 280aa1af..a667fe42 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbGenresTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbGenresTest.java @@ -7,6 +7,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbGenre.TMDB_METHOD_GENRE; @@ -31,7 +33,7 @@ public TmdbGenre createApiToTest() { public void testGetMovieList() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/genres/movie_list.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_GENRE + "/movie/list?language=en"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); List genres = getApiToTest().getMovieList("en"); assertNotNull(genres); @@ -49,7 +51,7 @@ public void testGetMovieList() throws IOException, TmdbException { public void testGetTvList() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/genres/tv_list.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_GENRE + "/tv/list?language=en"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); List genres = getApiToTest().getTvList("en"); assertNotNull(genres); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbGuestSessionsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbGuestSessionsTest.java index 06499ba4..6d7c4426 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbGuestSessionsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbGuestSessionsTest.java @@ -10,6 +10,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.sortby.AccountSortBy; import org.junit.jupiter.api.Test; @@ -34,7 +36,7 @@ public TmdbGuestSessions createApiToTest() { public void testGetRatedMovies() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/guest_sessions/rated_movies.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_GUEST_SESSIONS + "/1/rated/movies?language=en&page=1&sort_by=created_at.desc"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RatedMovieResultsPage ratedMovieResultsPage = getApiToTest().getRatedMovies(1, "en", 1, AccountSortBy.CREATED_AT_DESC); assertNotNull(ratedMovieResultsPage); @@ -52,7 +54,7 @@ public void testGetRatedMovies() throws IOException, TmdbException { public void testGetRatedTvSeries() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/guest_sessions/rated_tv.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_GUEST_SESSIONS + "/1/rated/tv?language=en&page=1&sort_by=created_at.desc"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RatedTvSeriesResultsPage ratedTvSeriesResultsPage = getApiToTest().getRatedTvSeries(1, "en", 1, AccountSortBy.CREATED_AT_DESC); assertNotNull(ratedTvSeriesResultsPage); @@ -67,7 +69,7 @@ public void testGetRatedTvEpisodes() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/guest_sessions/rated_tv_episodes.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_GUEST_SESSIONS + "/1/rated/tv/episodes?language=en&page=1&sort_by=created_at.desc"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); RatedTvEpisodeResultsPage ratedTvEpisodesResultsPage = getApiToTest().getRatedTvEpisodes(1, "en", 1, AccountSortBy.CREATED_AT_DESC); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbKeywordsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbKeywordsTest.java index a59f255f..7131284d 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbKeywordsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbKeywordsTest.java @@ -6,6 +6,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbKeywords.TMDB_METHOD_KEYWORD; @@ -29,7 +31,7 @@ public TmdbKeywords createApiToTest() { public void testGetDetails() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/keywords/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_KEYWORD + "/1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Keyword keyword = getApiToTest().getDetails(1); assertNotNull(keyword); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbListsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbListsTest.java index 78e19a36..add2aa68 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbListsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbListsTest.java @@ -12,6 +12,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.TmdbResponseCode; import info.movito.themoviedbapi.util.JsonUtil; import org.junit.jupiter.api.Test; @@ -43,7 +45,7 @@ public void testAddMovie() throws IOException, TmdbException { requestBody.put("media_id", 456); String jsonBody = JsonUtil.toJson(requestBody); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().addMovie(123, "testSessionId", 456); assertNotNull(responseStatus); @@ -58,7 +60,7 @@ public void testAddMovie() throws IOException, TmdbException { public void testCheckItemStatus() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/lists/check_item_status.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_LIST + "/123/item_status?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ListItemStatus listItemStatus = getApiToTest().checkItemStatus(123, "en-US", null); assertNotNull(listItemStatus); @@ -72,7 +74,7 @@ public void testCheckItemStatus() throws IOException, TmdbException { public void testClear() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/lists/clear.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_LIST + "/123/clear?session_id=testSessionId&confirm=true"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().clear(123, "testSessionId", true); assertNotNull(responseStatus); @@ -94,7 +96,7 @@ public void testCreate() throws IOException, TmdbException { requestBody.put("language", "en-US"); String jsonBody = JsonUtil.toJson(requestBody); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); MovieListCreationStatus responseStatus = getApiToTest().create("testSessionId", "testName", "testDescription", "en-US"); assertNotNull(responseStatus); @@ -108,7 +110,7 @@ public void testCreate() throws IOException, TmdbException { public void testDelete() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/lists/delete.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_LIST + "/123?session_id=testSessionId"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.DELETE)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.DELETE))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().delete(123, "testSessionId"); assertNotNull(responseStatus); @@ -123,7 +125,7 @@ public void testDelete() throws IOException, TmdbException { public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/lists/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_LIST + "/123?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ListDetails listDetails = getApiToTest().getDetails(123, "en-US", null); assertNotNull(listDetails); @@ -146,7 +148,7 @@ public void testRemoveMovie() throws IOException, TmdbException { requestBody.put("media_id", 456); String jsonBody = JsonUtil.toJson(requestBody); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().removeMovie(123, "testSessionId", 456); assertNotNull(responseStatus); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbMovieListsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbMovieListsTest.java index 5f6c8d53..420c35a4 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbMovieListsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbMovieListsTest.java @@ -9,6 +9,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbMovieLists.TMDB_METHOD_MOVIE_LISTS; @@ -32,7 +34,7 @@ public TmdbMovieLists createApiToTest() { public void testGetNowPlaying() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movie_lists/now_playing.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE_LISTS + "/now_playing?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPageWithDates movieResultsPageWithDates = getApiToTest().getNowPlaying("en-US", 1, null); assertNotNull(movieResultsPageWithDates); @@ -52,7 +54,7 @@ public void testGetNowPlaying() throws IOException, TmdbException { public void testGetPopular() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movie_lists/popular.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE_LISTS + "/popular?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage movieResultsPage = getApiToTest().getPopular("en-US", 1, null); assertNotNull(movieResultsPage); @@ -70,7 +72,7 @@ public void testGetPopular() throws IOException, TmdbException { public void testGetTopRated() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movie_lists/top_rated.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE_LISTS + "/top_rated?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage movieResultsPage = getApiToTest().getTopRated("en-US", 1, null); assertNotNull(movieResultsPage); @@ -88,7 +90,7 @@ public void testGetTopRated() throws IOException, TmdbException { public void testGetUpcoming() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movie_lists/upcoming.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE_LISTS + "/upcoming?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPageWithDates movieResultsPageWithDates = getApiToTest().getUpcoming("en-US", 1, null); assertNotNull(movieResultsPageWithDates); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbMoviesTest.java b/src/test/java/info/movito/themoviedbapi/TmdbMoviesTest.java index 02e1df2a..e5e55437 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbMoviesTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbMoviesTest.java @@ -24,6 +24,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.TmdbResponseCode; import info.movito.themoviedbapi.tools.appendtoresponse.MovieAppendToResponse; import info.movito.themoviedbapi.util.JsonUtil; @@ -51,7 +53,7 @@ public TmdbMovies createApiToTest() { public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieDb movie = getApiToTest().getDetails(123, "en-US"); assertNotNull(movie); @@ -87,7 +89,7 @@ public void testGetDetailsWithAppendToResponse() throws IOException, TmdbExcepti String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123?language=en-US&append_to_response=account_states%2C" + "alternative_titles%2Ccredits%2Cchanges%2Cexternal_ids%2Cimages%2Ckeywords%2Clists%2Crecommendations%2Crelease_dates%2C" + "reviews%2Csimilar%2Ctranslations%2Cvideos%2Cwatch%2Fproviders"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieDb movie = getApiToTest().getDetails(123, "en-US", MovieAppendToResponse.values()); assertNotNull(movie); @@ -109,7 +111,7 @@ public void testGetDetailsWithAppendToResponse() throws IOException, TmdbExcepti public void testGetAccountStates() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/account_states.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/account_states?session_id=123"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AccountStates accountStates = getApiToTest().getAccountStates(123, "123", null); assertNotNull(accountStates); @@ -123,7 +125,7 @@ public void testGetAccountStates() throws IOException, TmdbException { public void testGetAlternativeTitles() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/alternative_titles.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/alternative_titles?country=US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AlternativeTitles alternativeTitles = getApiToTest().getAlternativeTitles(123, "US"); assertNotNull(alternativeTitles); @@ -137,7 +139,7 @@ public void testGetAlternativeTitles() throws IOException, TmdbException { public void testGetChanges() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/changes.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/changes"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ChangeResults changeResults = getApiToTest().getChanges(123, null, null, null); assertNotNull(changeResults); @@ -151,7 +153,7 @@ public void testGetChanges() throws IOException, TmdbException { public void testGetCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Credits credits = getApiToTest().getCredits(123, "en-US"); assertNotNull(credits); @@ -165,7 +167,7 @@ public void testGetCredits() throws IOException, TmdbException { public void testGetExternalIds() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/external_ids.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/external_ids"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ExternalIds externalIds = getApiToTest().getExternalIds(123); assertNotNull(externalIds); @@ -179,7 +181,7 @@ public void testGetExternalIds() throws IOException, TmdbException { public void testGetImages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/images?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Images images = getApiToTest().getImages(123, "en-US"); assertNotNull(images); @@ -193,7 +195,7 @@ public void testGetImages() throws IOException, TmdbException { public void testGetKeywords() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/keywords.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/keywords"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); KeywordResults keywords = getApiToTest().getKeywords(123); assertNotNull(keywords); @@ -207,7 +209,7 @@ public void testGetKeywords() throws IOException, TmdbException { public void testGetLatest() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/latest.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/latest"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieDb movie = getApiToTest().getLatest(); assertNotNull(movie); @@ -245,7 +247,7 @@ public void testGetLatest() throws IOException, TmdbException { public void testGetLists() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/lists.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/lists?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieListResultsPage lists = getApiToTest().getLists(123, "en-US", null); assertNotNull(lists); @@ -259,7 +261,7 @@ public void testGetLists() throws IOException, TmdbException { public void testGetRecommendations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/recommendations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/recommendations?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage recommendations = getApiToTest().getRecommendations(123, "en-US", 1); assertNotNull(recommendations); @@ -280,7 +282,7 @@ public void testGetRecommendations() throws IOException, TmdbException { public void testGetReleaseDates() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/release_dates.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/release_dates"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ReleaseDateResults releaseDates = getApiToTest().getReleaseDates(123); assertNotNull(releaseDates); @@ -294,7 +296,7 @@ public void testGetReleaseDates() throws IOException, TmdbException { public void testGetReviews() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/reviews.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/reviews?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ReviewResultsPage reviews = getApiToTest().getReviews(123, "en-US", null); assertNotNull(reviews); @@ -308,7 +310,7 @@ public void testGetReviews() throws IOException, TmdbException { public void testGetSimilar() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/similar.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/similar?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage similar = getApiToTest().getSimilar(123, "en-US", null); assertNotNull(similar); @@ -329,7 +331,7 @@ public void testGetSimilar() throws IOException, TmdbException { public void testGetTranslations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/translations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/translations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Translations translations = getApiToTest().getTranslations(123); assertNotNull(translations); @@ -343,7 +345,7 @@ public void testGetTranslations() throws IOException, TmdbException { public void testGetVideos() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/videos.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/videos?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); VideoResults videos = getApiToTest().getVideos(123, "en-US"); assertNotNull(videos); @@ -357,7 +359,7 @@ public void testGetVideos() throws IOException, TmdbException { public void testGetWatchProviders() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/movies/watch_providers.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/watch/providers"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ProviderResults watchProviders = getApiToTest().getWatchProviders(123); assertNotNull(watchProviders); @@ -376,7 +378,7 @@ public void testAddRating() throws IOException, TmdbException { String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/rating"; String body = TestUtils.readTestFile("api_responses/movies/add_rating.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().addRating(123, null, null, 2.1); assertNotNull(responseStatus); @@ -391,7 +393,7 @@ public void testAddRating() throws IOException, TmdbException { public void testDeleteRating() throws IOException, TmdbException { String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE + "/123/rating"; String body = TestUtils.readTestFile("api_responses/movies/delete_rating.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.DELETE)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.DELETE))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().deleteRating(123, null, null); assertNotNull(responseStatus); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbNetworksTest.java b/src/test/java/info/movito/themoviedbapi/TmdbNetworksTest.java index d2cbabda..10220b49 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbNetworksTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbNetworksTest.java @@ -8,6 +8,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbNetworks.TMDB_METHOD_NETWORK; @@ -31,7 +33,7 @@ public TmdbNetworks createApiToTest() { public void testGetMovieChangesList() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/networks/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_NETWORK + "/1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Network network = getApiToTest().getDetails(1); assertNotNull(network); @@ -45,7 +47,7 @@ public void testGetMovieChangesList() throws TmdbException, IOException { public void testGetAlternativeNames() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/networks/alternative_names.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_NETWORK + "/1/alternative_names"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AlternativeNamesResults alternativeNamesResults = getApiToTest().getAlternativeNames(1); assertNotNull(alternativeNamesResults); @@ -59,7 +61,7 @@ public void testGetAlternativeNames() throws TmdbException, IOException { public void testGetImages() throws TmdbException, IOException { String body = TestUtils.readTestFile("api_responses/networks/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_NETWORK + "/1/images"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ImageResults imageResults = getApiToTest().getImages(1); assertNotNull(imageResults); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbPeopleListsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbPeopleListsTest.java index ba2a4db1..ac815c15 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbPeopleListsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbPeopleListsTest.java @@ -6,6 +6,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbPeopleLists.TMDB_METHOD_PEOPLE_LISTS; @@ -29,7 +31,7 @@ public TmdbPeopleLists createApiToTest() { public void testGetPopular() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people_lists/popular.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PEOPLE_LISTS + "?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); PopularPersonResultsPage popularPersonResultsPage = getApiToTest().getPopular("en-US", 1); assertNotNull(popularPersonResultsPage); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbPeopleTest.java b/src/test/java/info/movito/themoviedbapi/TmdbPeopleTest.java index 3ae3ffe8..6d035810 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbPeopleTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbPeopleTest.java @@ -22,6 +22,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.appendtoresponse.PersonAppendToResponse; import org.junit.jupiter.api.Test; @@ -48,7 +50,7 @@ public TmdbPeople createApiToTest() { public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); PersonDb details = getApiToTest().getDetails(123, "en-US"); assertNotNull(details); @@ -76,7 +78,7 @@ public void testGetDetailsWithAppendToResponse() throws IOException, TmdbExcepti String body = TestUtils.readTestFile("api_responses/people/details_with_append_to_response.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123?language=en-US&" + "append_to_response=changes%2Ccombined_credits%2Cexternal_ids%2Cimages%2Clatest%2Cmovie_credits%2Ctv_credits%2Ctranslations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); PersonDb details = getApiToTest().getDetails(123, "en-US", PersonAppendToResponse.values()); assertNotNull(details); @@ -95,7 +97,7 @@ public void testGetChanges() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/changes.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123/changes?start_date=" + startDate + "&end_date=" + endDate + "&page=" + page; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ChangeResults changes = getApiToTest().getChanges(123, startDate, endDate, page); assertNotNull(changes); @@ -109,7 +111,7 @@ public void testGetChanges() throws IOException, TmdbException { public void testGetCombinedCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/combined_credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123/combined_credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); CombinedPersonCredits personCredits = getApiToTest().getCombinedCredits(123, "en-US"); assertNotNull(personCredits); @@ -144,7 +146,7 @@ public void testGetCombinedCredits() throws IOException, TmdbException { public void testExternalIds() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/external_ids.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123/external_ids"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ExternalIds externalIds = getApiToTest().getExternalIds(123); assertNotNull(externalIds); @@ -158,7 +160,7 @@ public void testExternalIds() throws IOException, TmdbException { public void testGetImages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123/images"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); PersonImages images = getApiToTest().getImages(123); assertNotNull(images); @@ -172,7 +174,7 @@ public void testGetImages() throws IOException, TmdbException { public void testGetLatest() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/latest.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/latest"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); PersonDb latest = getApiToTest().getLatest(); assertNotNull(latest); @@ -199,7 +201,7 @@ public void testGetLatest() throws IOException, TmdbException { public void testGetMovieCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/movie_credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123/movie_credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieCredits movieCredits = getApiToTest().getMovieCredits(123, "en-US"); assertNotNull(movieCredits); @@ -232,7 +234,7 @@ public void testGetMovieCredits() throws IOException, TmdbException { public void testGetTvCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/tv_credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123/tv_credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvCredits tvCredits = getApiToTest().getTvCredits(123, "en-US"); assertNotNull(tvCredits); @@ -265,7 +267,7 @@ public void testGetTvCredits() throws IOException, TmdbException { public void testGetTranslations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/people/translations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_PERSON + "/123/translations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Translations translations = getApiToTest().getTranslations(123); assertNotNull(translations); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbReviewsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbReviewsTest.java index 1f128dc7..b0456fc2 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbReviewsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbReviewsTest.java @@ -6,6 +6,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbReviews.TMDB_METHOD_MOVIE_REVIEW; @@ -31,7 +33,7 @@ public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/reviews/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_MOVIE_REVIEW + "/" + reviewId; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Review review = getApiToTest().getDetails(reviewId); assertNotNull(review); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbSearchTest.java b/src/test/java/info/movito/themoviedbapi/TmdbSearchTest.java index ece22f25..743f32f6 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbSearchTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbSearchTest.java @@ -19,6 +19,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.tools.ApiUrl.TMDB_API_BASE_URL; @@ -42,7 +44,7 @@ public TmdbSearch createApiToTest() { public void testSearchCollection() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/search/collection.json"); String url = TMDB_API_BASE_URL + "search/collection?query=batman&language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); CollectionResultsPage collectionResultsPage = getApiToTest().searchCollection("batman", "en-US", null, null, null); assertNotNull(collectionResultsPage); @@ -56,7 +58,7 @@ public void testSearchCollection() throws IOException, TmdbException { public void testSearchCompany() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/search/company.json"); String url = TMDB_API_BASE_URL + "search/company?query=amici+films"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); CompanyResultsPage companyResultsPage = getApiToTest().searchCompany("amici films", null); assertNotNull(companyResultsPage); @@ -70,7 +72,7 @@ public void testSearchCompany() throws IOException, TmdbException { public void testSearchKeyword() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/search/keyword.json"); String url = TMDB_API_BASE_URL + "search/keyword?query=autograph"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); KeywordResultsPage keywordResultsPage = getApiToTest().searchKeyword("autograph", null); assertNotNull(keywordResultsPage); @@ -84,7 +86,7 @@ public void testSearchKeyword() throws IOException, TmdbException { public void testSearchMovie() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/search/movie.json"); String url = TMDB_API_BASE_URL + "search/movie?query=batman&language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage movieResultsPage = getApiToTest().searchMovie("batman", null, "en-US", null, null, null, null); assertNotNull(movieResultsPage); @@ -102,7 +104,7 @@ public void testSearchMovie() throws IOException, TmdbException { public void testSearchMulti() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/search/multi.json"); String url = TMDB_API_BASE_URL + "search/multi?query=batman&language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MultiResultsPage multiResultsPage = getApiToTest().searchMulti("batman", null, "en-US", null); assertNotNull(multiResultsPage); @@ -150,7 +152,7 @@ public void testSearchMulti() throws IOException, TmdbException { public void testSearchPerson() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/search/person.json"); String url = TMDB_API_BASE_URL + "search/person?query=vin&language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); PopularPersonResultsPage personResultsPage = getApiToTest().searchPerson("vin", null, "en-US", null); assertNotNull(personResultsPage); @@ -164,7 +166,7 @@ public void testSearchPerson() throws IOException, TmdbException { public void testSearchTv() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/search/tv.json"); String url = TMDB_API_BASE_URL + "search/tv?query=batman&language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvSeriesResultsPage = getApiToTest().searchTv("batman", null, null, "en-US", null, null); assertNotNull(tvSeriesResultsPage); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbTrendingTest.java b/src/test/java/info/movito/themoviedbapi/TmdbTrendingTest.java index 8b2d45f3..ea2a044e 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbTrendingTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbTrendingTest.java @@ -11,6 +11,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.model.time.TimeWindow; import org.junit.jupiter.api.Test; @@ -35,7 +37,7 @@ public TmdbTrending createApiToTest() { public void testGetAll() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/trending/all.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TRENDING + "/all/week?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MultiResultsPage allResults = getApiToTest().getAll(TimeWindow.WEEK, "en-US"); assertNotNull(allResults); @@ -55,7 +57,7 @@ public void testGetAll() throws IOException, TmdbException { public void testGetMovies() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/trending/movies.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TRENDING + "/movie/week?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); MovieResultsPage movieResults = getApiToTest().getMovies(TimeWindow.WEEK, "en-US"); assertNotNull(movieResults); @@ -73,7 +75,7 @@ public void testGetMovies() throws IOException, TmdbException { public void testGetPeople() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/trending/people.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TRENDING + "/person/week?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); PopularPersonResultsPage peopleResults = getApiToTest().getPeople(TimeWindow.WEEK, "en-US"); assertNotNull(peopleResults); @@ -87,7 +89,7 @@ public void testGetPeople() throws IOException, TmdbException { public void testGetTv() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/trending/tv.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TRENDING + "/tv/week?language=en-US&page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvResults = getApiToTest().getTv(TimeWindow.WEEK, "en-US"); assertNotNull(tvResults); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbTvEpisodeGroupsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbTvEpisodeGroupsTest.java index 766270a4..e6cbd762 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbTvEpisodeGroupsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbTvEpisodeGroupsTest.java @@ -7,6 +7,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbTvEpisodeGroups.TMDB_METHOD_TV_EPISODE_GROUPS; @@ -31,7 +33,7 @@ public TmdbTvEpisodeGroups createApiToTest() { public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episode_groups/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV_EPISODE_GROUPS + "/5acfef37c3a36842e400333f"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvEpisodeGroups tvEpisodeGroups = getApiToTest().getDetails("5acfef37c3a36842e400333f"); assertNotNull(tvEpisodeGroups); @@ -45,7 +47,7 @@ public void testGetDetails() throws IOException, TmdbException { public void testEpisodeGroupType() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episode_groups/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV_EPISODE_GROUPS + "/5acfef37c3a36842e400333f"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvEpisodeGroups tvEpisodeGroups = getApiToTest().getDetails("5acfef37c3a36842e400333f"); assertEquals(EpisodeGroupType.DIGITAL, tvEpisodeGroups.getType()); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbTvEpisodesTest.java b/src/test/java/info/movito/themoviedbapi/TmdbTvEpisodesTest.java index b1539f15..b6c885c0 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbTvEpisodesTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbTvEpisodesTest.java @@ -17,6 +17,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.TmdbResponseCode; import info.movito.themoviedbapi.tools.appendtoresponse.TvEpisodesAppendToResponse; import info.movito.themoviedbapi.util.JsonUtil; @@ -47,7 +49,7 @@ public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episodes/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvEpisodeDb tvEpisode = getApiToTest().getDetails(123, 1, 1, "en-US"); assertNotNull(tvEpisode); @@ -75,7 +77,7 @@ public void testGetDetailsWithAppendToResponse() throws IOException, TmdbExcepti String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1?language=en-US&append_to_response=account_states%2Ccredits%2Cexternal_ids%2Cimages%2Ctranslations%2Cvideos"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvEpisodeDb tvEpisode = getApiToTest().getDetails(123, 1, 1, "en-US", TvEpisodesAppendToResponse.values()); assertNotNull(tvEpisode); @@ -90,7 +92,7 @@ public void testGetAccountStates() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episodes/account_states.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1/account_states"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AccountStates accountStates = getApiToTest().getAccountStates(123, 1, 1, null, null); assertNotNull(accountStates); @@ -104,7 +106,7 @@ public void testGetAccountStates() throws IOException, TmdbException { public void testGetChanges() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episodes/changes.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/" + TMDB_METHOD_TV_EPISODE + "/1/changes"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ChangeResults changeResults = getApiToTest().getChanges(1); assertNotNull(changeResults); @@ -119,7 +121,7 @@ public void testGetCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episodes/credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1/credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); EpisodeCredits credits = getApiToTest().getCredits(123, 1, 1, "en-US"); assertNotNull(credits); @@ -134,7 +136,7 @@ public void testGetExternalIds() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episodes/external_ids.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1/external_ids"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ExternalIds externalIds = getApiToTest().getExternalIds(123, 1, 1); assertNotNull(externalIds); @@ -149,7 +151,7 @@ public void testGetImages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episodes/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1/images?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Images images = getApiToTest().getImages(123, 1, 1, "en-US"); assertNotNull(images); @@ -164,7 +166,7 @@ public void testGetTranslations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episodes/translations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1/translations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Translations translations = getApiToTest().getTranslations(123, 1, 1); assertNotNull(translations); @@ -179,7 +181,7 @@ public void testGetVideos() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_episodes/videos.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1/videos?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); VideoResults videoResults = getApiToTest().getVideos(123, 1, 1, "en-US"); assertNotNull(videoResults); @@ -198,7 +200,7 @@ public void testAddRating() throws IOException, TmdbException { String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1/rating"; String body = TestUtils.readTestFile("api_responses/tv_episodes/add_rating.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().addRating(123, 1, 1, null, null, 2.1); assertNotNull(responseStatus); @@ -214,7 +216,7 @@ public void testDeleteRating() throws IOException, TmdbException { String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/" + TMDB_METHOD_TV_EPISODE + "/1/rating"; String body = TestUtils.readTestFile("api_responses/tv_episodes/delete_rating.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.DELETE)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.DELETE))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().deleteRating(123, 1, 1, null, null); assertNotNull(responseStatus); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbTvSeasonsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbTvSeasonsTest.java index d6859548..a4d83098 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbTvSeasonsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbTvSeasonsTest.java @@ -17,6 +17,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.appendtoresponse.TvSeasonsAppendToResponse; import org.junit.jupiter.api.Test; @@ -42,7 +44,7 @@ public TmdbTvSeasons createApiToTest() { public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeasonDb tvSeason = getApiToTest().getDetails(123, 1, "en-US"); assertNotNull(tvSeason); @@ -73,7 +75,7 @@ public void testGetDetailsWithAppendToResponse() throws IOException, TmdbExcepti String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1?language=en-US&" + "append_to_response=account_states%2Caggregate_credits%2Ccredits%2Cexternal_ids%2Cimages%2Ctranslations%2C" + "videos%2Cwatch%2Fproviders"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeasonDb tvSeason = getApiToTest().getDetails(123, 1, "en-US", TvSeasonsAppendToResponse.values()); assertNotNull(tvSeason); @@ -88,7 +90,7 @@ public void testGetDetailsWithAppendToResponse() throws IOException, TmdbExcepti public void testGetAccountStates() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/account_states.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/account_states?session_id=123"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AccountStateResults accountStates = getApiToTest().getAccountStates(123, 1, "123", null); assertNotNull(accountStates); @@ -102,7 +104,7 @@ public void testGetAccountStates() throws IOException, TmdbException { public void testGetAggregateCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/aggregate_credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/aggregate_credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AggregateCredits aggregateCredits = getApiToTest().getAggregateCredits(123, 1, "en-US"); assertNotNull(aggregateCredits); @@ -116,7 +118,7 @@ public void testGetAggregateCredits() throws IOException, TmdbException { public void testGetChanges() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/changes.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/" + TMDB_METHOD_TV_SEASON + "/123/changes?page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ChangeResults changes = getApiToTest().getChanges(123, null, null, 1); assertNotNull(changes); @@ -130,7 +132,7 @@ public void testGetChanges() throws IOException, TmdbException { public void testGetCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Credits credits = getApiToTest().getCredits(123, 1, "en-US"); assertNotNull(credits); @@ -144,7 +146,7 @@ public void testGetCredits() throws IOException, TmdbException { public void testGetExternalIds() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/external_ids.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/external_ids"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ExternalIds externalIds = getApiToTest().getExternalIds(123, 1); assertNotNull(externalIds); @@ -158,7 +160,7 @@ public void testGetExternalIds() throws IOException, TmdbException { public void testGetImages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/images?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Images images = getApiToTest().getImages(123, 1, "en-US"); assertNotNull(images); @@ -172,7 +174,7 @@ public void testGetImages() throws IOException, TmdbException { public void testGetTranslations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/translations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/translations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Translations translations = getApiToTest().getTranslations(123, 1); assertNotNull(translations); @@ -186,7 +188,7 @@ public void testGetTranslations() throws IOException, TmdbException { public void testGetVideos() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/videos.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/videos?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); VideoResults videos = getApiToTest().getVideos(123, 1, "en-US"); assertNotNull(videos); @@ -200,7 +202,7 @@ public void testGetVideos() throws IOException, TmdbException { public void testGetWatchProviders() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_seasons/watch_providers.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/" + TMDB_METHOD_TV_SEASON + "/1/watch/providers?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ProviderResults watchProviders = getApiToTest().getWatchProviders(123, 1, "en-US"); assertNotNull(watchProviders); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbTvSeriesListsTest.java b/src/test/java/info/movito/themoviedbapi/TmdbTvSeriesListsTest.java index 4b4dd746..eb03b35f 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbTvSeriesListsTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbTvSeriesListsTest.java @@ -6,6 +6,8 @@ import info.movito.themoviedbapi.testutil.TestUtils; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import org.junit.jupiter.api.Test; import static info.movito.themoviedbapi.TmdbTvSeries.TMDB_METHOD_TV; @@ -29,7 +31,7 @@ public TmdbTvSeriesLists createApiToTest() { public void testGetAiringToday() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series_lists/airing_today.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/airing_today?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvSeriesResultsPage = getApiToTest().getAiringToday("en-US", null, null); assertNotNull(tvSeriesResultsPage); @@ -43,7 +45,7 @@ public void testGetAiringToday() throws IOException, TmdbException { public void testGetOnTheAir() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series_lists/on_the_air.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/on_the_air?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvSeriesResultsPage = getApiToTest().getOnTheAir("en-US", null, null); assertNotNull(tvSeriesResultsPage); @@ -57,7 +59,7 @@ public void testGetOnTheAir() throws IOException, TmdbException { public void testGetPopular() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series_lists/popular.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/popular?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvSeriesResultsPage = getApiToTest().getPopular("en-US", null); assertNotNull(tvSeriesResultsPage); @@ -71,7 +73,7 @@ public void testGetPopular() throws IOException, TmdbException { public void testGetTopRated() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series_lists/top_rated.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/top_rated?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage tvSeriesResultsPage = getApiToTest().getTopRated("en-US", null); assertNotNull(tvSeriesResultsPage); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbTvSeriesTest.java b/src/test/java/info/movito/themoviedbapi/TmdbTvSeriesTest.java index e32006c1..32446115 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbTvSeriesTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbTvSeriesTest.java @@ -27,6 +27,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.tools.TmdbResponseCode; import info.movito.themoviedbapi.tools.appendtoresponse.TvSeriesAppendToResponse; import info.movito.themoviedbapi.util.JsonUtil; @@ -54,7 +56,7 @@ public TmdbTvSeries createApiToTest() { public void testGetDetails() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/details.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesDb tvSeries = getApiToTest().getDetails(123, "en-US"); assertNotNull(tvSeries); @@ -93,7 +95,7 @@ public void testGetDetailsWithAppendToResponse() throws IOException, TmdbExcepti String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123?language=en-US&append_to_response=account_states%2Caggregate_credits" + "%2Calternative_titles%2Cchanges%2Ccontent_ratings%2Ccredits%2Cepisode_groups%2Cexternal_ids%2Cimages%2Ckeywords%2Clists" + "%2Crecommendations%2Creviews%2Cscreened_theatrically%2Csimilar%2Ctranslations%2Cvideos%2Cwatch%2Fproviders"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesDb tvSeries = getApiToTest().getDetails(123, "en-US", TvSeriesAppendToResponse.values()); assertNotNull(tvSeries); @@ -108,7 +110,7 @@ public void testGetDetailsWithAppendToResponse() throws IOException, TmdbExcepti public void testGetAccountStates() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/account_states.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/account_states?session_id=123"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AccountStates accountStates = getApiToTest().getAccountStates(123, "123", null); assertNotNull(accountStates); @@ -122,7 +124,7 @@ public void testGetAccountStates() throws IOException, TmdbException { public void testGetAggregateCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/aggregate_credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/aggregate_credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AggregateCredits aggregateCredits = getApiToTest().getAggregateCredits(123, "en-US"); assertNotNull(aggregateCredits); @@ -136,7 +138,7 @@ public void testGetAggregateCredits() throws IOException, TmdbException { public void testGetAlternativeTitles() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/alternative_titles.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/alternative_titles"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AlternativeTitleResults alternativeTitles = getApiToTest().getAlternativeTitles(123); assertNotNull(alternativeTitles); @@ -150,7 +152,7 @@ public void testGetAlternativeTitles() throws IOException, TmdbException { public void testGetChanges() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/changes.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/changes?page=1"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ChangeResults changes = getApiToTest().getChanges(123, null, null, 1); assertNotNull(changes); @@ -164,7 +166,7 @@ public void testGetChanges() throws IOException, TmdbException { public void testGetContentRatings() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/content_ratings.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/content_ratings"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ContentRatingResults contentRatings = getApiToTest().getContentRatings(123); assertNotNull(contentRatings); @@ -178,7 +180,7 @@ public void testGetContentRatings() throws IOException, TmdbException { public void testGetCredits() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/credits.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/credits?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Credits credits = getApiToTest().getCredits(123, "en-US"); assertNotNull(credits); @@ -192,7 +194,7 @@ public void testGetCredits() throws IOException, TmdbException { public void testGetEpisodeGroups() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/episode_groups.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/episode_groups"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); EpisodeGroupResults episodeGroups = getApiToTest().getEpisodeGroups(123); assertNotNull(episodeGroups); @@ -206,7 +208,7 @@ public void testGetEpisodeGroups() throws IOException, TmdbException { public void testGetExternalIds() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/external_ids.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/external_ids"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ExternalIds externalIds = getApiToTest().getExternalIds(123); assertNotNull(externalIds); @@ -220,7 +222,7 @@ public void testGetExternalIds() throws IOException, TmdbException { public void testGetImages() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/images.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/images"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Images images = getApiToTest().getImages(123, null); assertNotNull(images); @@ -234,7 +236,7 @@ public void testGetImages() throws IOException, TmdbException { public void testGetKeywords() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/keywords.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/keywords"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvKeywords keywords = getApiToTest().getKeywords(123); assertNotNull(keywords); @@ -248,7 +250,7 @@ public void testGetKeywords() throws IOException, TmdbException { public void testGetLatest() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/latest.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/latest"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesDb latest = getApiToTest().getLatest(); assertNotNull(latest); @@ -285,7 +287,7 @@ public void testGetLatest() throws IOException, TmdbException { public void testGetLists() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/lists.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/lists"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesListResultsPage lists = getApiToTest().getLists(123, null, null); assertNotNull(lists); @@ -299,7 +301,7 @@ public void testGetLists() throws IOException, TmdbException { public void testGetRecommendations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/recommendations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/recommendations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage recommendations = getApiToTest().getRecommendations(123, null, null); assertNotNull(recommendations); @@ -313,7 +315,7 @@ public void testGetRecommendations() throws IOException, TmdbException { public void testGetReviews() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/reviews.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/reviews"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ReviewResultsPage reviews = getApiToTest().getReviews(123, null, null); assertNotNull(reviews); @@ -327,7 +329,7 @@ public void testGetReviews() throws IOException, TmdbException { public void testGetScreenedTheatrically() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/screened_theatrically.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/screened_theatrically"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ScreenedTheatricallyResults screenedTheatrically = getApiToTest().getScreenedTheatrically(123); assertNotNull(screenedTheatrically); @@ -341,7 +343,7 @@ public void testGetScreenedTheatrically() throws IOException, TmdbException { public void testGetSimilar() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/similar.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/similar"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); TvSeriesResultsPage similar = getApiToTest().getSimilar(123, null, null); assertNotNull(similar); @@ -355,7 +357,7 @@ public void testGetSimilar() throws IOException, TmdbException { public void testGetTranslations() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/translations.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/translations"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); Translations translations = getApiToTest().getTranslations(123); assertNotNull(translations); @@ -369,7 +371,7 @@ public void testGetTranslations() throws IOException, TmdbException { public void testGetVideos() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/videos.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/videos"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); VideoResults videos = getApiToTest().getVideos(123, null); assertNotNull(videos); @@ -383,7 +385,7 @@ public void testGetVideos() throws IOException, TmdbException { public void testGetWatchProviders() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/tv_series/watch_providers.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/watch/providers"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ProviderResults watchProviders = getApiToTest().getWatchProviders(123); assertNotNull(watchProviders); @@ -402,7 +404,7 @@ public void testAddRating() throws IOException, TmdbException { String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/rating"; String body = TestUtils.readTestFile("api_responses/tv_series/add_rating.json"); - when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.POST, jsonBody))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().addRating(123, null, null, 2.1); assertNotNull(responseStatus); @@ -417,7 +419,7 @@ public void testAddRating() throws IOException, TmdbException { public void testDeleteRating() throws IOException, TmdbException { String url = TMDB_API_BASE_URL + TMDB_METHOD_TV + "/123/rating"; String body = TestUtils.readTestFile("api_responses/tv_series/delete_rating.json"); - when(getTmdbUrlReader().readUrl(url, null, RequestType.DELETE)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.DELETE))).thenReturn(new TmdbResponse(200, body)); ResponseStatus responseStatus = getApiToTest().deleteRating(123, null, null); assertNotNull(responseStatus); diff --git a/src/test/java/info/movito/themoviedbapi/TmdbWatchProvidersTest.java b/src/test/java/info/movito/themoviedbapi/TmdbWatchProvidersTest.java index 8934c01a..7ea6b924 100644 --- a/src/test/java/info/movito/themoviedbapi/TmdbWatchProvidersTest.java +++ b/src/test/java/info/movito/themoviedbapi/TmdbWatchProvidersTest.java @@ -12,6 +12,8 @@ import info.movito.themoviedbapi.testutil.ValidatorConfig; import info.movito.themoviedbapi.tools.RequestType; import info.movito.themoviedbapi.tools.TmdbException; +import info.movito.themoviedbapi.tools.TmdbRequest; +import info.movito.themoviedbapi.tools.TmdbResponse; import info.movito.themoviedbapi.util.JsonUtil; import org.junit.jupiter.api.Test; @@ -36,7 +38,7 @@ public TmdbWatchProviders createApiToTest() { public void testGetAvailableRegions() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/watch_providers/available_regions.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_WATCH_PROVIDERS + "?language=en-US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); AvailableRegionResults availableRegionResults = getApiToTest().getAvailableRegions("en-US"); assertNotNull(availableRegionResults); @@ -50,7 +52,7 @@ public void testGetAvailableRegions() throws IOException, TmdbException { public void testGetMovieProviders() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/watch_providers/movie_providers.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_WATCH_PROVIDERS + "/movie?language=en-US&watch_region=US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ProviderResults providerResults = getApiToTest().getMovieProviders("en-US", "US"); assertNotNull(providerResults); @@ -72,7 +74,7 @@ public void testGetMovieProviders() throws IOException, TmdbException { public void testGetTvProviders() throws IOException, TmdbException { String body = TestUtils.readTestFile("api_responses/watch_providers/tv_providers.json"); String url = TMDB_API_BASE_URL + TMDB_METHOD_WATCH_PROVIDERS + "/tv?language=en-US&watch_region=US"; - when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body); + when(getRequestExecutor().execute(new TmdbRequest(url, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); ProviderResults providerResults = getApiToTest().getTvProviders("en-US", "US"); assertNotNull(providerResults); diff --git a/src/test/java/info/movito/themoviedbapi/testutil/IntegrationTest.java b/src/test/java/info/movito/themoviedbapi/testutil/IntegrationTest.java new file mode 100644 index 00000000..04da3388 --- /dev/null +++ b/src/test/java/info/movito/themoviedbapi/testutil/IntegrationTest.java @@ -0,0 +1,19 @@ +package info.movito.themoviedbapi.testutil; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.junit.jupiter.api.Tag; + +/** + * Marks a test as an integration test by tagging it with {@code "integration"}. + * The Gradle {@code integrationTest} task includes this tag. + * See JUnit docs. + */ +@Target({ElementType.TYPE, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Tag("integration") +public @interface IntegrationTest { +} diff --git a/src/test/java/info/movito/themoviedbapi/tools/TmdbApiClientTest.java b/src/test/java/info/movito/themoviedbapi/tools/TmdbApiClientTest.java new file mode 100644 index 00000000..da3491e2 --- /dev/null +++ b/src/test/java/info/movito/themoviedbapi/tools/TmdbApiClientTest.java @@ -0,0 +1,150 @@ +package info.movito.themoviedbapi.tools; + +import java.util.List; + +import com.fasterxml.jackson.core.type.TypeReference; +import info.movito.themoviedbapi.model.core.responses.ResponseStatus; +import info.movito.themoviedbapi.model.core.responses.TmdbResponseException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Tests for {@link TmdbApiClient}. + */ +@ExtendWith(MockitoExtension.class) +class TmdbApiClientTest { + + private static final ApiUrl API_URL = new ApiUrl("movie", 123); + private static final String URL = API_URL.buildUrl(); + + private TmdbApiClient tmdbApiClient; + + @Mock + private TmdbRequestExecutor requestExecutor; + + @Captor + private ArgumentCaptor requestCaptor; + + @BeforeEach + void setUp() { + tmdbApiClient = new TmdbApiClient(requestExecutor); + } + + /** + * Test that a GET request maps a successful response body to the requested class. + */ + @Test + void testGet_class() throws TmdbException { + String body = "{\"status_code\":1,\"status_message\":\"Success.\"}"; + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); + + ResponseStatus result = tmdbApiClient.get(API_URL, ResponseStatus.class); + assertEquals("Success.", result.getStatusMessage()); + } + + /** + * Test that a GET request maps a successful response body to the requested generic type. + */ + @Test + void testGet_typeReference() throws TmdbException { + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))).thenReturn(new TmdbResponse(200, "[\"a\",\"b\"]")); + + List result = tmdbApiClient.get(API_URL, new TypeReference<>() { + }); + + assertEquals(List.of("a", "b"), result); + } + + /** + * Test that the executor is called with a request carrying the url, request type and json body. + */ + @Test + void testRequest() throws TmdbException { + String jsonBody = "{\"value\":true}"; + when(requestExecutor.execute(any())).thenReturn(new TmdbResponse(200, "{\"status_message\":\"ok\"}")); + + ResponseStatus result = tmdbApiClient.request(API_URL, jsonBody, RequestType.POST, ResponseStatus.class); + assertEquals("ok", result.getStatusMessage()); + + verify(requestExecutor).execute(requestCaptor.capture()); + TmdbRequest request = requestCaptor.getValue(); + + assertEquals(URL, request.url()); + assertEquals(RequestType.POST, request.requestType()); + assertEquals(jsonBody, request.jsonBody()); + } + + /** + * Test that an unsuccessful HTTP status with a recognisable TMDB status code throws with that code. + */ + @Test + void testRequest_unsuccessfulHttpStatusWithResponseCode_throws() throws TmdbException { + String body = "{\"status_code\":7,\"status_message\":\"Invalid API key.\"}"; + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))).thenReturn(new TmdbResponse(401, body)); + + TmdbResponseException exception = assertThrows(TmdbResponseException.class, () -> tmdbApiClient.get(API_URL, ResponseStatus.class)); + assertEquals(TmdbResponseCode.INVALID_API_KEY, exception.getResponseCode()); + } + + /** + * Test that an unsuccessful HTTP status with no recognisable TMDB status code throws with the http status surfaced. + */ + @Test + void testRequest_unsuccessfulHttpStatusWithoutResponseCode_throws() throws TmdbException { + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))) + .thenReturn(new TmdbResponse(502, "Bad Gateway")); + + TmdbResponseException exception = assertThrows(TmdbResponseException.class, () -> tmdbApiClient.get(API_URL, ResponseStatus.class)); + assertNull(exception.getResponseCode()); + assertTrue(exception.getMessage().contains("502")); + } + + /** + * Test that a successful (2xx) response is mapped even when the body carries a non-successful TMDB status code. + */ + @Test + void testRequest_successfulHttpStatusWithFailureBodyCode_isMapped() throws TmdbException { + String body = "{\"status_code\":21,\"status_message\":\"Entry not found.\"}"; + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))).thenReturn(new TmdbResponse(200, body)); + + ResponseStatus result = tmdbApiClient.get(API_URL, ResponseStatus.class); + assertEquals(TmdbResponseCode.ENTRY_NOT_FOUND, result.getStatusCode()); + } + + /** + * Test that a body that cannot be mapped to the result type on a successful response throws a {@link TmdbException}. + */ + @Test + void testRequest_unmappableSuccessfulBody_throws() throws TmdbException { + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))).thenReturn(new TmdbResponse(200, "[1, 2, 3]")); + + assertThrowsExactly(TmdbException.class, () -> tmdbApiClient.get(API_URL, ResponseStatus.class)); + } + + /** + * Test that an exception thrown by the executor is propagated unchanged. + */ + @Test + void testRequest_propagatesExecutorException() throws TmdbException { + TmdbException executorException = new TmdbException("boom"); + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))).thenThrow(executorException); + + TmdbException exception = assertThrows(TmdbException.class, () -> tmdbApiClient.get(API_URL, ResponseStatus.class)); + assertSame(executorException, exception); + } +} diff --git a/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientIT.java b/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientIT.java new file mode 100644 index 00000000..83dc0bef --- /dev/null +++ b/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientIT.java @@ -0,0 +1,158 @@ +package info.movito.themoviedbapi.tools; + +import java.io.IOException; + +import com.github.tomakehurst.wiremock.http.Fault; +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; +import com.github.tomakehurst.wiremock.junit5.WireMockTest; +import com.github.tomakehurst.wiremock.stubbing.Scenario; +import info.movito.themoviedbapi.model.core.responses.TmdbResponseException; +import info.movito.themoviedbapi.testutil.IntegrationTest; +import org.junit.jupiter.api.Test; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.absent; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.notFound; +import static com.github.tomakehurst.wiremock.client.WireMock.okJson; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.status; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@IntegrationTest +@WireMockTest +class TmdbHttpClientIT { + + private static final String API_KEY = "test-api-key"; + + private final TmdbHttpClient tmdbHttpClient = new TmdbHttpClient(API_KEY); + + @Test + void testExecute_getRequest(WireMockRuntimeInfo wireMock) throws TmdbException { + String body = "{\"id\":123}"; + stubFor(get("/movie/123") + .willReturn(okJson(body))); + + TmdbRequest request = new TmdbRequest(wireMock.getHttpBaseUrl() + "/movie/123", RequestType.GET); + TmdbResponse result = tmdbHttpClient.execute(request); + + assertEquals(200, result.statusCode()); + assertEquals(body, result.body()); + verify(getRequestedFor(urlEqualTo("/movie/123")) + .withHeader("Authorization", equalTo("Bearer " + API_KEY)) + .withHeader("Accept", equalTo("application/json"))); + } + + @Test + void testExecute_postRequestWithBody(WireMockRuntimeInfo wireMock) throws TmdbException { + String jsonBody = "{\"value\":true}"; + stubFor(post(urlEqualTo("/list")) + .willReturn(okJson("{}"))); + + TmdbRequest request = new TmdbRequest(wireMock.getHttpBaseUrl() + "/list", RequestType.POST, jsonBody); + tmdbHttpClient.execute(request); + + verify(postRequestedFor(urlEqualTo("/list")) + .withHeader("Content-Type", equalTo("application/json")) + .withRequestBody(equalToJson(jsonBody))); + } + + @Test + void testExecute_postRequestWithNullBody(WireMockRuntimeInfo wireMock) throws TmdbException { + stubFor(post("/list") + .willReturn(okJson("{}"))); + + TmdbRequest request = new TmdbRequest(wireMock.getHttpBaseUrl() + "/list", RequestType.POST); + tmdbHttpClient.execute(request); + + verify(postRequestedFor(urlEqualTo("/list")) + .withHeader("Content-Type", absent()) + .withRequestBody(absent())); + } + + @Test + void testExecute_deleteRequest(WireMockRuntimeInfo wireMock) throws TmdbException { + stubFor(delete("/list/1") + .willReturn(okJson("{}"))); + + TmdbRequest request = new TmdbRequest(wireMock.getHttpBaseUrl() + "/list/1", RequestType.DELETE); + tmdbHttpClient.execute(request); + + verify(deleteRequestedFor(urlEqualTo("/list/1"))); + } + + @Test + void testExecute_errorStatusIsReturned(WireMockRuntimeInfo wireMock) throws TmdbException { + String body = "{\"status_code\":34,\"status_message\":\"The resource you requested could not be found.\"}"; + stubFor(get("/movie/0") + .willReturn(notFound() + .withBody(body))); + + TmdbRequest request = new TmdbRequest(wireMock.getHttpBaseUrl() + "/movie/0", RequestType.GET); + TmdbResponse result = tmdbHttpClient.execute(request); + + assertEquals(404, result.statusCode()); + assertEquals(body, result.body()); + } + + @Test + void testExecute_retriesOnRateLimitThenSucceeds(WireMockRuntimeInfo wireMock) throws TmdbException { + String body = "{\"id\":123}"; + stubFor(get("/movie/123") + .inScenario("rate limit success") + .whenScenarioStateIs(Scenario.STARTED) + .willReturn(status(429) + .withHeader("Retry-After", "0")) + .willSetStateTo("retrying")); + stubFor(get("/movie/123") + .inScenario("rate limit success") + .whenScenarioStateIs("retrying") + .willReturn(okJson(body))); + + TmdbRequest request = new TmdbRequest(wireMock.getHttpBaseUrl() + "/movie/123", RequestType.GET); + TmdbResponse result = tmdbHttpClient.execute(request); + + assertEquals(200, result.statusCode()); + assertEquals(body, result.body()); + // initial attempt + 1 successful retry + verify(2, getRequestedFor(urlEqualTo("/movie/123"))); + } + + @Test + void testExecute_returnsLastResponseAfterExhaustingRetries(WireMockRuntimeInfo wireMock) throws TmdbException { + stubFor(get("/movie/123") + .willReturn(status(TmdbResponseCode.REQUEST_LIMIT_EXCEEDED.getHttpStatus()) + .withHeader("Retry-After", "0") + .withBody("{\"status_code\":%s}".formatted(TmdbResponseCode.REQUEST_LIMIT_EXCEEDED.getTmdbCode())))); + + TmdbRequest request = new TmdbRequest(wireMock.getHttpBaseUrl() + "/movie/123", RequestType.GET); + TmdbResponse result = tmdbHttpClient.execute(request); + + assertEquals(429, result.statusCode()); + // initial attempt + 3 rate limited retries + verify(4, getRequestedFor(urlEqualTo("/movie/123"))); + } + + @Test + void testExecute_connectionFailureIsWrapped(WireMockRuntimeInfo wireMock) { + stubFor(get("/movie/123") + .willReturn(aResponse() + .withFault(Fault.CONNECTION_RESET_BY_PEER))); + + TmdbRequest request = new TmdbRequest(wireMock.getHttpBaseUrl() + "/movie/123", RequestType.GET); + + TmdbResponseException exception = assertThrows(TmdbResponseException.class, () -> tmdbHttpClient.execute(request)); + assertInstanceOf(IOException.class, exception.getCause()); + } +} diff --git a/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientTest.java b/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientTest.java index 38a87410..83b0fc62 100644 --- a/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientTest.java +++ b/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientTest.java @@ -3,9 +3,12 @@ import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; +import java.net.http.HttpHeaders; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; import info.movito.themoviedbapi.model.core.responses.TmdbResponseException; import org.junit.jupiter.api.BeforeEach; @@ -22,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -42,6 +46,9 @@ class TmdbHttpClientTest { @Mock private HttpResponse httpResponse; + @Mock + private HttpResponse rateLimitedResponse; + @Captor private ArgumentCaptor requestCaptor; @@ -54,14 +61,16 @@ void setUp() { * Test that a GET request returns the response body and is built with the correct uri, method and headers. */ @Test - void testReadUrl_getRequest() throws IOException, InterruptedException, TmdbResponseException { + void testExecute_getRequest() throws IOException, InterruptedException, TmdbException { String body = "{\"id\":123}"; + when(httpResponse.statusCode()).thenReturn(200); when(httpResponse.body()).thenReturn(body); doReturn(httpResponse).when(httpClient).send(any(), any()); - String result = tmdbHttpClient.readUrl(URL, null, RequestType.GET); + TmdbResponse result = tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.GET)); - assertEquals(body, result); + assertEquals(200, result.statusCode()); + assertEquals(body, result.body()); verify(httpClient).send(requestCaptor.capture(), any()); HttpRequest request = requestCaptor.getValue(); @@ -77,11 +86,11 @@ void testReadUrl_getRequest() throws IOException, InterruptedException, TmdbResp * Test that a POST request with a json body is built with the POST method and a body publisher containing the body. */ @Test - void testReadUrl_postRequestWithBody() throws IOException, InterruptedException, TmdbResponseException { + void testExecute_postRequestWithBody() throws IOException, InterruptedException, TmdbException { String jsonBody = "{\"value\":true}"; doReturn(httpResponse).when(httpClient).send(any(), any()); - tmdbHttpClient.readUrl(URL, jsonBody, RequestType.POST); + tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.POST, jsonBody)); verify(httpClient).send(requestCaptor.capture(), any()); HttpRequest request = requestCaptor.getValue(); @@ -97,10 +106,10 @@ void testReadUrl_postRequestWithBody() throws IOException, InterruptedException, * Test that a POST request with a null body is built with the POST method and an empty body publisher. */ @Test - void testReadUrl_postRequestWithNullBody() throws IOException, InterruptedException, TmdbResponseException { + void testExecute_postRequestWithNullBody() throws IOException, InterruptedException, TmdbException { doReturn(httpResponse).when(httpClient).send(any(), any()); - tmdbHttpClient.readUrl(URL, null, RequestType.POST); + tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.POST)); verify(httpClient).send(requestCaptor.capture(), any()); HttpRequest request = requestCaptor.getValue(); @@ -116,10 +125,10 @@ void testReadUrl_postRequestWithNullBody() throws IOException, InterruptedExcept * Test that a DELETE request is built with the DELETE method. */ @Test - void testReadUrl_deleteRequest() throws IOException, InterruptedException, TmdbResponseException { + void testExecute_deleteRequest() throws IOException, InterruptedException, TmdbException { doReturn(httpResponse).when(httpClient).send(any(), any()); - tmdbHttpClient.readUrl(URL, null, RequestType.DELETE); + tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.DELETE)); verify(httpClient).send(requestCaptor.capture(), any()); HttpRequest request = requestCaptor.getValue(); @@ -133,12 +142,12 @@ void testReadUrl_deleteRequest() throws IOException, InterruptedException, TmdbR * Test that an {@link IOException} thrown while sending is wrapped in a {@link TmdbResponseException}. */ @Test - void testReadUrl_ioExceptionIsWrapped() throws IOException, InterruptedException { + void testExecute_ioExceptionIsWrapped() throws IOException, InterruptedException { IOException ioException = new IOException("boom"); when(httpClient.send(any(), any())).thenThrow(ioException); TmdbResponseException exception = assertThrows(TmdbResponseException.class, - () -> tmdbHttpClient.readUrl(URL, null, RequestType.GET)); + () -> tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.GET))); assertSame(ioException, exception.getCause()); } @@ -146,17 +155,52 @@ void testReadUrl_ioExceptionIsWrapped() throws IOException, InterruptedException * Test that an {@link InterruptedException} thrown while sending is wrapped and the thread interrupt flag is restored. */ @Test - void testReadUrl_interruptedExceptionIsWrappedAndInterruptFlagRestored() throws IOException, InterruptedException { + void testExecute_interruptedExceptionIsWrappedAndInterruptFlagRestored() throws IOException, InterruptedException { InterruptedException interruptedException = new InterruptedException(); when(httpClient.send(any(), any())).thenThrow(interruptedException); TmdbResponseException exception = assertThrows(TmdbResponseException.class, - () -> tmdbHttpClient.readUrl(URL, null, RequestType.GET)); + () -> tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.GET))); assertSame(interruptedException, exception.getCause()); // Thread.interrupted() returns the flag and clears it so it does not leak to other tests. assertTrue(Thread.interrupted()); } + /** + * Test that a rate-limited (HTTP 429) response is retried, honoring the {@code Retry-After} header, until it succeeds. + */ + @Test + void testExecute_retriesOnRateLimitThenSucceeds() throws IOException, InterruptedException, TmdbException { + when(rateLimitedResponse.statusCode()).thenReturn(429); + when(rateLimitedResponse.headers()).thenReturn(HttpHeaders.of(Map.of("Retry-After", List.of("0")), (name, value) -> true)); + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{\"id\":123}"); + doReturn(rateLimitedResponse, httpResponse).when(httpClient).send(any(), any()); + + TmdbResponse result = tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.GET)); + + assertEquals(200, result.statusCode()); + assertEquals("{\"id\":123}", result.body()); + verify(httpClient, times(2)).send(any(), any()); + } + + /** + * Test that retries stop once the maximum is reached and the last rate-limited response is returned. + */ + @Test + void testExecute_returnsLastResponseAfterExhaustingRetries() throws IOException, InterruptedException, TmdbException { + when(rateLimitedResponse.statusCode()).thenReturn(429); + when(rateLimitedResponse.body()).thenReturn("{\"status_code\":25}"); + when(rateLimitedResponse.headers()).thenReturn(HttpHeaders.of(Map.of("Retry-After", List.of("0")), (name, value) -> true)); + doReturn(rateLimitedResponse).when(httpClient).send(any(), any()); + + TmdbResponse result = tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.GET)); + + assertEquals(429, result.statusCode()); + // initial attempt + 3 retries + verify(httpClient, times(4)).send(any(), any()); + } + /** * Asserts the authentication and accept headers that should be present on every request, regardless of type. */ diff --git a/src/test/java/info/movito/themoviedbapi/tools/TmdbRequestTest.java b/src/test/java/info/movito/themoviedbapi/tools/TmdbRequestTest.java new file mode 100644 index 00000000..753cecb4 --- /dev/null +++ b/src/test/java/info/movito/themoviedbapi/tools/TmdbRequestTest.java @@ -0,0 +1,75 @@ +package info.movito.themoviedbapi.tools; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests for {@link TmdbRequest}. + */ +class TmdbRequestTest { + + private static final String URL = "https://api.themoviedb.org/3/movie/123"; + + /** + * Test that the full constructor exposes the url, request type and json body it was created with. + */ + @Test + void testAccessors() { + TmdbRequest request = new TmdbRequest(URL, RequestType.POST, "{\"value\":true}"); + + assertEquals(URL, request.url()); + assertEquals(RequestType.POST, request.requestType()); + assertEquals("{\"value\":true}", request.jsonBody()); + } + + /** + * Test that the convenience constructor leaves the json body null. + */ + @Test + void testConstructorWithoutBody() { + TmdbRequest request = new TmdbRequest(URL, RequestType.GET); + + assertEquals(URL, request.url()); + assertEquals(RequestType.GET, request.requestType()); + assertNull(request.jsonBody()); + } + + /** + * Test that a null json body is permitted. + */ + @Test + void testNullBodyIsAllowed() { + TmdbRequest request = new TmdbRequest(URL, RequestType.GET, null); + assertNull(request.jsonBody()); + } + + /** + * Test that a null url is rejected by the full constructor. + */ + @Test + void testNullUrlThrows() { + NullPointerException exception = assertThrows(NullPointerException.class, () -> new TmdbRequest(null, RequestType.GET, null)); + assertEquals("url must not be null", exception.getMessage()); + } + + /** + * Test that a null request type is rejected. + */ + @Test + void testNullRequestTypeThrows() { + NullPointerException exception = assertThrows(NullPointerException.class, () -> new TmdbRequest(URL, null, null)); + assertEquals("requestType must not be null", exception.getMessage()); + } + + /** + * Test that the convenience constructor also rejects a null url. + */ + @Test + void testNullUrlThrows_convenienceConstructor() { + NullPointerException exception = assertThrows(NullPointerException.class, () -> new TmdbRequest(null, RequestType.GET)); + assertEquals("url must not be null", exception.getMessage()); + } +} diff --git a/src/test/java/info/movito/themoviedbapi/tools/TmdbResponseTest.java b/src/test/java/info/movito/themoviedbapi/tools/TmdbResponseTest.java new file mode 100644 index 00000000..91d61631 --- /dev/null +++ b/src/test/java/info/movito/themoviedbapi/tools/TmdbResponseTest.java @@ -0,0 +1,55 @@ +package info.movito.themoviedbapi.tools; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for {@link TmdbResponse}. + */ +class TmdbResponseTest { + + /** + * Test that the record exposes the status code and body it was created with. + */ + @Test + void testAccessors() { + TmdbResponse response = new TmdbResponse(200, "{\"id\":1}"); + + assertEquals(200, response.statusCode()); + assertEquals("{\"id\":1}", response.body()); + } + + /** + * Test that a null body is permitted. + */ + @Test + void testNullBody() { + TmdbResponse response = new TmdbResponse(204, null); + + assertNull(response.body()); + } + + /** + * Test that 2xx status codes are reported as successful, including the boundaries. + */ + @ParameterizedTest + @ValueSource(ints = {200, 201, 204, 250, 299}) + void testIsSuccessfulHttpStatus_successful(int statusCode) { + assertTrue(new TmdbResponse(statusCode, "body").isSuccessfulHttpStatus()); + } + + /** + * Test that non-2xx status codes are reported as unsuccessful, including the boundaries. + */ + @ParameterizedTest + @ValueSource(ints = {0, 100, 199, 300, 301, 400, 404, 429, 500, 503}) + void testIsSuccessfulHttpStatus_unsuccessful(int statusCode) { + assertFalse(new TmdbResponse(statusCode, "body").isSuccessfulHttpStatus()); + } +} From fd7bbb2fe4c1caa71a17446710e7881b09faf2d3 Mon Sep 17 00:00:00 2001 From: Conor Egan <68134729+c-eg@users.noreply.github.com> Date: Sat, 13 Jun 2026 11:22:50 +0100 Subject: [PATCH 2/4] Add github actions for releases + cleanup (#338) * refactor request logic * move the retry logic to the http client * small cleanup + tests * remove invalid comment * add integration test support + IT for TmdbHttpClient * add github actions for releases + cleanup # Conflicts: # build.gradle.kts --- .github/workflows/{gradle.yml => ci.yml} | 9 ++- .github/workflows/release.yml | 46 +++++++++++++ .github/workflows/snapshot.yml | 32 +++++++++ build.gradle.kts | 47 +++++++------ devel_notes.md | 87 ++++++++++++++---------- 5 files changed, 162 insertions(+), 59 deletions(-) rename .github/workflows/{gradle.yml => ci.yml} (70%) create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/snapshot.yml diff --git a/.github/workflows/gradle.yml b/.github/workflows/ci.yml similarity index 70% rename from .github/workflows/gradle.yml rename to .github/workflows/ci.yml index f1e65ee3..65031f93 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: build +name: CI on: push: @@ -9,6 +9,11 @@ on: permissions: contents: read +# Cancel superseded runs on the same ref (e.g. rapid pushes or PR updates). +concurrency: + group: build-${{ github.ref }} + cancel-in-progress: true + jobs: build: runs-on: ubuntu-latest @@ -27,4 +32,4 @@ jobs: uses: gradle/actions/setup-gradle@v5 - name: Execute Gradle Build - run: ./gradlew clean build --scan + run: ./gradlew clean build diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..f42ee5b8 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,46 @@ +name: Release to Maven Central + +on: + push: + tags: + - 'v*' + - '!v*-SNAPSHOT' # snapshot tags are handled by the snapshot workflow + workflow_dispatch: + +permissions: + contents: write # required to create the GitHub release + +jobs: + release: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Setup Java + uses: actions/setup-java@v5 + with: + java-version: 17 + distribution: corretto + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v5 + + - name: Publish to local staging repository + run: ./gradlew clean publishMavenJavaPublicationToStagingRepository + + - name: Deploy to Maven Central + run: ./gradlew jreleaserDeploy + env: + JRELEASER_GPG_PUBLIC_KEY: ${{ secrets.GPG_PUBLIC_KEY }} + JRELEASER_GPG_SECRET_KEY: ${{ secrets.GPG_SECRET_KEY }} + JRELEASER_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + JRELEASER_MAVENCENTRAL_USERNAME: ${{ secrets.MAVENCENTRAL_USERNAME }} + JRELEASER_MAVENCENTRAL_PASSWORD: ${{ secrets.MAVENCENTRAL_PASSWORD }} + + - name: Create GitHub release + if: startsWith(github.ref, 'refs/tags/') # skip when running the workflow manually + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh release create "${GITHUB_REF_NAME}" --generate-notes --verify-tag diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml new file mode 100644 index 00000000..0ecd6ab3 --- /dev/null +++ b/.github/workflows/snapshot.yml @@ -0,0 +1,32 @@ +name: Publish Snapshot to Maven Central + +on: + push: + tags: [ 'v*-SNAPSHOT' ] + workflow_dispatch: + +permissions: + contents: read + +jobs: + snapshot: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Setup Java + uses: actions/setup-java@v5 + with: + java-version: 17 + distribution: corretto + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v5 + + - name: Publish snapshot to Central Portal + run: ./gradlew clean publishMavenJavaPublicationToCentralSnapshotsRepository + env: + MAVENCENTRAL_USERNAME: ${{ secrets.MAVENCENTRAL_USERNAME }} + MAVENCENTRAL_PASSWORD: ${{ secrets.MAVENCENTRAL_PASSWORD }} diff --git a/build.gradle.kts b/build.gradle.kts index 4e44ac35..2c0b1061 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -2,7 +2,6 @@ plugins { `java-library` checkstyle `maven-publish` - signing id("io.github.gradle-nexus.publish-plugin") version "2.0.0" id("org.jreleaser") version "1.25.0" } @@ -22,7 +21,7 @@ dependencies { // testing testImplementation(platform("org.junit:junit-bom:6.1.1")) testImplementation("org.junit.jupiter:junit-jupiter") - testRuntimeOnly("org.junit.platform:junit-platform-launcher") // gradle bundled version is incompatible with 5.12 + testRuntimeOnly("org.junit.platform:junit-platform-launcher") // pin launcher to junit-bom; Gradle's bundled one lags the JUnit version testImplementation(platform("org.mockito:mockito-bom:5.23.0")) testImplementation("org.mockito:mockito-core") @@ -42,10 +41,14 @@ dependencies { implementation("com.fasterxml.jackson.core:jackson-databind") implementation("org.apache.commons:commons-lang3:3.20.0") + testImplementation("commons-io:commons-io:2.22.0") } java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } withJavadocJar() withSourcesJar() } @@ -99,14 +102,15 @@ publishing { licenses { license { - name = "BSD" + name = "BSD-2-Clause" url = "https://github.com/c-eg/themoviedbapi/blob/master/LICENCE.txt" } } scm { - connection = "scm:git:github.com/c-eg/themoviedbapi.git" - url = "https://github.com/c-eg/themoviedbapi.git" + connection = "scm:git:https://github.com/c-eg/themoviedbapi.git" + developerConnection = "scm:git:ssh://git@github.com/c-eg/themoviedbapi.git" + url = "https://github.com/c-eg/themoviedbapi" } developers { @@ -126,9 +130,21 @@ publishing { } } repositories { + // Local staging dir that JReleaser reads from for the signed release deploy. maven { + name = "staging" url = uri(layout.buildDirectory.dir("staging-deploy")) } + + // Central Portal snapshot repository. + maven { + name = "centralSnapshots" + url = uri("https://central.sonatype.com/repository/maven-snapshots/") + credentials { + username = providers.environmentVariable("MAVENCENTRAL_USERNAME").orNull + password = providers.environmentVariable("MAVENCENTRAL_PASSWORD").orNull + } + } } } @@ -137,9 +153,7 @@ jreleaser { pgp { active = org.jreleaser.model.Active.ALWAYS armored = true - mode = org.jreleaser.model.Signing.Mode.FILE - publicKey = "C:/gpg/public.pgp" - secretKey = "C:/gpg/private.pgp" + mode = org.jreleaser.model.Signing.Mode.MEMORY } } deploy { @@ -155,20 +169,11 @@ jreleaser { } } -if (project.hasProperty("signing.keyId") && project.hasProperty("signing.password") && project.hasProperty("signing.secretKeyRingFile")) signing { - sign(publishing.publications["mavenJava"]) -} - tasks.javadoc { - if (JavaVersion.current().isJava9Compatible) { - (options as StandardJavadocDocletOptions).addBooleanOption("html5", true) - } -} - -tasks { - javadoc { - options { - (this as CoreJavadocOptions).addBooleanOption("Xdoclint:none", true) + options { + (this as StandardJavadocDocletOptions).apply { + addBooleanOption("Xdoclint:none", true) + addBooleanOption("html5", true) } } } diff --git a/devel_notes.md b/devel_notes.md index 7125cbed..1273fe59 100644 --- a/devel_notes.md +++ b/devel_notes.md @@ -1,52 +1,67 @@ # Developer Notes + +Releases and snapshots are published automatically via GitHub Actions. The +manual/local process is still possible and documented at the end as a fallback. + ## How to do a release? -1. Make sure to increase version number in [build.gradle.kts](build.gradle.kts), commit and push the version to the `master` branch +Releases are handled by the [Release to Maven Central](.github/workflows/release.yml) +workflow, triggered by pushing a version tag. + +1. Bump the version in [build.gradle.kts](build.gradle.kts) to the release value + (e.g. `2.7.0`, **no** `-SNAPSHOT` suffix). Commit and push to `master`. + +2. Create and push a matching `v` tag: + ```bash + git tag v2.7.0 + git push origin v2.7.0 + ``` -2. Do the release on GitHub +3. The workflow then automatically: + - stages the artifacts, + - GPG-signs them and deploys to Maven Central via JReleaser, + - creates a GitHub release with auto-generated changelog notes. -3. Make sure the prerequisites are met that are listed below +4. Verify the deployment at the + [Maven Central Repository](https://central.sonatype.com/publishing/deployments). -4. Clean, publish and deploy -```bash -./gradlew clean && ./gradlew publish && ./gradlew jreleaserDeploy -``` +> The git tag should match the version in `build.gradle.kts`. Snapshot-suffixed +> tags (`v*-SNAPSHOT`) are ignored by this workflow and handled by the snapshot +> workflow instead. -5. Go to [Maven Central Repository](https://central.sonatype.com/publishing/deployments) and verify the deployment was successful +## How to publish a snapshot? +Snapshots are handled by the +[Publish Snapshot to Maven Central](.github/workflows/snapshot.yml) workflow. +They are deployed directly via `maven-publish` (no signing, no validation) to the +[Central Portal snapshot repository](https://central.sonatype.com/repository/maven-snapshots/). -## Prerequisites -### GPG & PGP Keys -Make sure you have the following keys exist: +1. Set the version in [build.gradle.kts](build.gradle.kts) to a `-SNAPSHOT` value + (e.g. `2.7.0-SNAPSHOT`). Commit and push to `master`. -- `C:/gpg/private.pgp` -- `C:/gpg/public.pgp` -- `C:/gpg/secring.gpg` +2. Trigger the workflow either by: + - pushing a `v*-SNAPSHOT` tag (e.g. `v2.7.0-SNAPSHOT`), or + - running it manually from the GitHub **Actions** tab (Run workflow). -### Gradle Properties -Make sure you have the following in your global gradle.properties file `C:\Users\\.gradle\gradle.properties`: -```properties -signing.keyId = -signing.password = -signing.secretKeyRingFile = C:/gpg/secring.gpg -``` +## Required GitHub repository secrets -### JReleaser Properties -Make sure you have the following in your jreleaser.properties file `C:\Users\\.jreleaser\config.properties`: +The release and snapshot workflows read credentials from repository secrets +(**Settings → Secrets and variables → Actions**): -```properties -JRELEASER_GPG_PUBLIC_KEY = C:/gpg/public.pgp -JRELEASER_GPG_SECRET_KEY = C:/gpg/private.pgp -JRELEASER_GPG_PASSPHRASE = -JRELEASER_GITHUB_TOKEN = -JRELEASER_MAVENCENTRAL_SONATYPE_USERNAME = -JRELEASER_MAVENCENTRAL_SONATYPE_PASSWORD = -``` +| Secret | Used by | Description | +|-------------------------|--------------------|------------------------------------------------------| +| `GPG_PUBLIC_KEY` | release | ASCII-armored public key **contents** | +| `GPG_SECRET_KEY` | release | ASCII-armored private key **contents** | +| `GPG_PASSPHRASE` | release | Passphrase for the private key | +| `MAVENCENTRAL_USERNAME` | release + snapshot | Sonatype Central Portal token username | +| `MAVENCENTRAL_PASSWORD` | release + snapshot | Sonatype Central Portal token password | -Note: `JRELEASER_GITHUB_TOKEN` does not need a valid value, it just needs a non-empty value set. +`GITHUB_TOKEN` is provided automatically by GitHub Actions; no secret needed. -If you are setting this up for the first time, you can verify your config is configured correctly with: -```bash -./gradlew jreleaserConfig -``` \ No newline at end of file +> Signing uses JReleaser **MEMORY** mode, so `GPG_PUBLIC_KEY` / `GPG_SECRET_KEY` +> hold the armored key *contents*, not file paths. Export them with: +> ```bash +> gpg --armor --export # -> GPG_PUBLIC_KEY +> gpg --armor --export-secret-keys # -> GPG_SECRET_KEY +> ``` From 2e1eb4d6f973605f5dc1e4464620c3c24dda7c7e Mon Sep 17 00:00:00 2001 From: Conor Egan <17conoregan@gmail.com> Date: Sat, 11 Jul 2026 11:50:51 +0100 Subject: [PATCH 3/4] bump actions/checkout to v7 --- .github/workflows/release.yml | 2 +- .github/workflows/snapshot.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f42ee5b8..9eb4192d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,7 +16,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@v7 - name: Setup Java uses: actions/setup-java@v5 diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml index 0ecd6ab3..fa799259 100644 --- a/.github/workflows/snapshot.yml +++ b/.github/workflows/snapshot.yml @@ -14,7 +14,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@v7 - name: Setup Java uses: actions/setup-java@v5 From 20d2d571a8c3bb51f9f3b0fbdc90c0db73e3d326 Mon Sep 17 00:00:00 2001 From: Conor Egan <17conoregan@gmail.com> Date: Sat, 11 Jul 2026 16:19:12 +0100 Subject: [PATCH 4/4] prevent npe and improve tests --- .../themoviedbapi/tools/TmdbApiClient.java | 2 +- .../tools/TmdbApiClientTest.java | 26 +++++++++ .../tools/TmdbHttpClientTest.java | 57 +++++++++++++++++++ 3 files changed, 84 insertions(+), 1 deletion(-) diff --git a/src/main/java/info/movito/themoviedbapi/tools/TmdbApiClient.java b/src/main/java/info/movito/themoviedbapi/tools/TmdbApiClient.java index f48cc5af..5842ae28 100644 --- a/src/main/java/info/movito/themoviedbapi/tools/TmdbApiClient.java +++ b/src/main/java/info/movito/themoviedbapi/tools/TmdbApiClient.java @@ -92,7 +92,7 @@ private T request(ApiUrl apiUrl, String jsonBody, RequestType requestType, O private static Optional parseResponseCode(String jsonResponse) { try { ResponseStatus responseStatus = RESPONSE_STATUS_READER.readValue(jsonResponse); - return Optional.of(responseStatus.getStatusCode()); + return Optional.ofNullable(responseStatus.getStatusCode()); } catch (JsonProcessingException exception) { return Optional.empty(); diff --git a/src/test/java/info/movito/themoviedbapi/tools/TmdbApiClientTest.java b/src/test/java/info/movito/themoviedbapi/tools/TmdbApiClientTest.java index da3491e2..41a4198f 100644 --- a/src/test/java/info/movito/themoviedbapi/tools/TmdbApiClientTest.java +++ b/src/test/java/info/movito/themoviedbapi/tools/TmdbApiClientTest.java @@ -114,6 +114,32 @@ void testRequest_unsuccessfulHttpStatusWithoutResponseCode_throws() throws TmdbE assertTrue(exception.getMessage().contains("502")); } + /** + * Test that an unsuccessful HTTP status with a JSON body lacking a status code field throws with the http status surfaced. + */ + @Test + void testRequest_unsuccessfulHttpStatusWithJsonBodyWithoutStatusCode_throws() throws TmdbException { + String body = "{\"some_field\":\"some_value\"}"; + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))).thenReturn(new TmdbResponse(400, body)); + + TmdbResponseException exception = assertThrows(TmdbResponseException.class, () -> tmdbApiClient.get(API_URL, ResponseStatus.class)); + assertNull(exception.getResponseCode()); + assertTrue(exception.getMessage().contains("400")); + } + + /** + * Test that an unsuccessful HTTP status with an unknown status code to {@link TmdbResponseCode} throws with the http status surfaced. + */ + @Test + void testRequest_unsuccessfulHttpStatusWithUnknownStatusCode_throws() throws TmdbException { + String body = "{\"status_code\":999,\"status_message\":\"Some new error.\"}"; + when(requestExecutor.execute(new TmdbRequest(URL, RequestType.GET))).thenReturn(new TmdbResponse(400, body)); + + TmdbResponseException exception = assertThrows(TmdbResponseException.class, () -> tmdbApiClient.get(API_URL, ResponseStatus.class)); + assertNull(exception.getResponseCode()); + assertTrue(exception.getMessage().contains("400")); + } + /** * Test that a successful (2xx) response is mapped even when the body carries a non-successful TMDB status code. */ diff --git a/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientTest.java b/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientTest.java index 83b0fc62..4669e797 100644 --- a/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientTest.java +++ b/src/test/java/info/movito/themoviedbapi/tools/TmdbHttpClientTest.java @@ -20,6 +20,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -201,6 +202,62 @@ void testExecute_returnsLastResponseAfterExhaustingRetries() throws IOException, verify(httpClient, times(4)).send(any(), any()); } + /** + * Test that a rate-limited response without a {@code Retry-After} header is retried after the default delay. + */ + @Test + void testExecute_retriesWithDefaultDelayWhenRetryAfterHeaderAbsent() throws IOException, InterruptedException, TmdbException { + when(rateLimitedResponse.statusCode()).thenReturn(429); + when(rateLimitedResponse.headers()).thenReturn(HttpHeaders.of(Map.of(), (name, value) -> true)); + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{\"id\":123}"); + doReturn(rateLimitedResponse, httpResponse).when(httpClient).send(any(), any()); + + TmdbResponse result = tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.GET)); + + assertEquals(200, result.statusCode()); + verify(httpClient, times(2)).send(any(), any()); + } + + /** + * Test that a {@code Retry-After} header that is not a plain number of seconds (e.g. the HTTP-date form) falls back to the + * default delay instead of failing. + */ + @Test + void testExecute_retriesWithDefaultDelayWhenRetryAfterHeaderNotNumeric() throws IOException, InterruptedException, TmdbException { + when(rateLimitedResponse.statusCode()).thenReturn(429); + when(rateLimitedResponse.headers()) + .thenReturn(HttpHeaders.of(Map.of("Retry-After", List.of("Wed, 21 Oct 2015 07:28:00 GMT")), (name, value) -> true)); + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{\"id\":123}"); + doReturn(rateLimitedResponse, httpResponse).when(httpClient).send(any(), any()); + + TmdbResponse result = tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.GET)); + + assertEquals(200, result.statusCode()); + verify(httpClient, times(2)).send(any(), any()); + } + + /** + * Test that an interruption during the rate-limit delay is wrapped and the thread interrupt flag is restored. + */ + @Test + void testExecute_interruptedDuringRateLimitDelayIsWrappedAndInterruptFlagRestored() throws IOException, InterruptedException { + when(rateLimitedResponse.statusCode()).thenReturn(429); + when(rateLimitedResponse.headers()).thenReturn(HttpHeaders.of(Map.of("Retry-After", List.of("30")), (name, value) -> true)); + doReturn(rateLimitedResponse).when(httpClient).send(any(), any()); + + // interrupt the current thread so the rate-limit sleep throws immediately instead of waiting + Thread.currentThread().interrupt(); + TmdbResponseException exception = assertThrows(TmdbResponseException.class, + () -> tmdbHttpClient.execute(new TmdbRequest(URL, RequestType.GET))); + + assertInstanceOf(InterruptedException.class, exception.getCause()); + // Thread.interrupted() returns the flag and clears it so it does not leak to other tests + assertTrue(Thread.interrupted()); + verify(httpClient, times(1)).send(any(), any()); + } + /** * Asserts the authentication and accept headers that should be present on every request, regardless of type. */