Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace okhttp3 with Java standard library #224

Merged
merged 4 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ dependencies {
testCompileOnly 'org.projectlombok:lombok:1.18.32'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.32'

implementation 'com.squareup.okhttp3:okhttp:4.12.0'

implementation 'com.fasterxml.jackson.core:jackson-annotations:2.17.1'
implementation 'com.fasterxml.jackson.core:jackson-core:2.17.1'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.1'
Expand Down
21 changes: 7 additions & 14 deletions src/main/java/info/movito/themoviedbapi/tools/ApiUrl.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package info.movito.themoviedbapi.tools;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
Expand Down Expand Up @@ -59,20 +57,15 @@ public ApiUrl(Object... urlElements) {
*
* @return the URL.
*/
public URL buildUrl() {
public String buildUrl() {
StringBuilder urlBuilder = new StringBuilder(baseUrl);

try {
for (Map.Entry<String, String> entry : params.entrySet()) {
urlBuilder.append(urlBuilder.toString().contains("?") ? "&" : "?")
.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}

return new URL(urlBuilder.toString());
}
catch (MalformedURLException e) {
throw new RuntimeException(e);
for (Map.Entry<String, String> entry : params.entrySet()) {
urlBuilder.append(urlBuilder.toString().contains("?") ? "&" : "?")
.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}

return urlBuilder.toString();
}

/**
Expand All @@ -93,7 +86,7 @@ public void addPathParam(String name, Object value) {
*/
public void addPathParam(String name, String value) {
if (params.containsKey(name)) {
throw new RuntimeException("paramater '" + name + "' already defined");
throw new RuntimeException("parameter '" + name + "' already defined");
}

name = StringUtils.trimToEmpty(name);
Expand Down
46 changes: 23 additions & 23 deletions src/main/java/info/movito/themoviedbapi/tools/TmdbHttpClient.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package info.movito.themoviedbapi.tools;

import java.io.IOException;
import java.net.URL;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import info.movito.themoviedbapi.model.core.responses.TmdbResponseException;
import lombok.AllArgsConstructor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -17,38 +16,39 @@
*/
@AllArgsConstructor
public class TmdbHttpClient implements TmdbUrlReader {
private static final OkHttpClient okHttpClient = new OkHttpClient();

private static final Logger LOGGER = LoggerFactory.getLogger(TmdbHttpClient.class);

private static final HttpClient httpClient = HttpClient.newHttpClient();

private final String apiKey;

@Override
public String readUrl(URL url, String jsonBody, RequestType requestType) throws TmdbResponseException {
LOGGER.debug(String.format("TMDB API: making request, of type: %s, to: %s", requestType.toString(), url.toString()));
public String readUrl(String url, String jsonBody, RequestType requestType) throws TmdbResponseException {
LOGGER.debug("TMDB API: making request, of type: {}, to: {}", requestType.toString(), url);

Request.Builder requestBuilder = new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Accept", "application/json")
.addHeader("Content-type", "application/json");
URI uri = URI.create(url);
HttpRequest.Builder httpRequestBuilder = HttpRequest.newBuilder()
.uri(uri)
.header("Authorization", "Bearer " + apiKey)
.header("Accept", "application/json")
.header("Content-type", "application/json");

switch (requestType) {
case GET -> requestBuilder.get();
case POST -> requestBuilder.post(okhttp3.RequestBody.create(jsonBody, okhttp3.MediaType.parse("application/json")));
case DELETE -> requestBuilder.delete();
case GET -> httpRequestBuilder.GET();
case POST -> httpRequestBuilder.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
case DELETE -> httpRequestBuilder.DELETE();
default -> throw new RuntimeException("Invalid request type: " + requestType);
}

try (Response response = okHttpClient.newCall(requestBuilder.build()).execute()) {
ResponseBody responseBody = response.body();
try {
HttpResponse<String> httpResponse = httpClient.send(httpRequestBuilder.build(), HttpResponse.BodyHandlers.ofString());
String responseBody = httpResponse.body();
if (responseBody == null) {
throw new TmdbResponseException("Response body was null: " + response);
throw new TmdbResponseException("Response body was null: " + httpResponse);
}

return responseBody.string();
return responseBody;
}
catch (IOException exception) {
catch (IOException | InterruptedException exception) {
throw new TmdbResponseException(exception);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package info.movito.themoviedbapi.tools;

import java.net.URL;

import info.movito.themoviedbapi.model.core.responses.TmdbResponseException;

/**
Expand All @@ -17,5 +15,5 @@ public interface TmdbUrlReader {
* @return the response from the movie database api
* @throws TmdbResponseException if the response was not successful
*/
String readUrl(URL url, String jsonBody, RequestType requestType) throws TmdbResponseException;
String readUrl(String url, String jsonBody, RequestType requestType) throws TmdbResponseException;
}
3 changes: 1 addition & 2 deletions src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
requires com.fasterxml.jackson.annotation;
requires com.fasterxml.jackson.core;
requires com.fasterxml.jackson.databind;
requires okhttp3;
requires kotlin.stdlib;
requires java.net.http;

opens info.movito.themoviedbapi.model.account to com.fasterxml.jackson.databind;
opens info.movito.themoviedbapi.model.authentication to com.fasterxml.jackson.databind;
Expand Down
50 changes: 24 additions & 26 deletions src/test/java/info/movito/themoviedbapi/TmdbAccountTest.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package info.movito.themoviedbapi;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import info.movito.themoviedbapi.model.account.Account;
Expand All @@ -20,7 +19,6 @@
import info.movito.themoviedbapi.util.Utils;
import org.junit.jupiter.api.Test;

import static info.movito.themoviedbapi.AbstractTmdbApi.getObjectMapper;
import static info.movito.themoviedbapi.TmdbAccount.TMDB_METHOD_ACCOUNT;
import static info.movito.themoviedbapi.tools.ApiUrl.TMDB_API_BASE_URL;
import static info.movito.themoviedbapi.util.TestUtils.validateAbstractJsonMappingFields;
Expand All @@ -43,7 +41,7 @@ public TmdbAccount createApiToTest() {
@Test
public void testGetAccount() throws IOException, TmdbException {
String body = TestUtils.readTestFile("api_responses/account/details.json");
URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234?session_id=testSessionId");
String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234?session_id=testSessionId";
when(getTmdbUrlReader().readUrl(url, null, RequestType.GET)).thenReturn(body);

Account account = getApiToTest().getDetails(1234, "testSessionId");
Expand All @@ -61,12 +59,12 @@ public void testAddFavourite() throws TmdbException, IOException {
Integer mediaId = 1234;
TmdbAccount.MediaType mediaType = TmdbAccount.MediaType.MOVIE;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/favorite?session_id=testSessionId");
String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/favorite?session_id=testSessionId";
HashMap<String, Object> requestBody = new HashMap<>();
requestBody.put("media_type", mediaType.toString());
requestBody.put("media_id", mediaId);
requestBody.put("favorite", true);
String jsonBody = Utils.convertToJson(getObjectMapper(), requestBody);
String jsonBody = Utils.convertToJson(AbstractTmdbApi.getObjectMapper(), requestBody);

String body = TestUtils.readTestFile("api_responses/account/add_favourite.json");
when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body);
Expand All @@ -87,12 +85,12 @@ public void testRemoveFavorite() throws TmdbException, IOException {
Integer mediaId = 1234;
TmdbAccount.MediaType mediaType = TmdbAccount.MediaType.MOVIE;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/favorite?session_id=testSessionId");
String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/favorite?session_id=testSessionId";
HashMap<String, Object> requestBody = new HashMap<>();
requestBody.put("media_type", mediaType.toString());
requestBody.put("media_id", mediaId);
requestBody.put("favorite", false);
String jsonBody = Utils.convertToJson(getObjectMapper(), requestBody);
String jsonBody = Utils.convertToJson(AbstractTmdbApi.getObjectMapper(), requestBody);

String body = TestUtils.readTestFile("api_responses/account/add_favourite.json");
when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body);
Expand All @@ -113,12 +111,12 @@ public void testAddToWatchList() throws IOException, TmdbException {
Integer mediaId = 1234;
TmdbAccount.MediaType mediaType = TmdbAccount.MediaType.MOVIE;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/watchlist?session_id=testSessionId");
String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/watchlist?session_id=testSessionId";
HashMap<String, Object> requestBody = new HashMap<>();
requestBody.put("media_type", mediaType.toString());
requestBody.put("media_id", mediaId);
requestBody.put("watchlist", true);
String jsonBody = Utils.convertToJson(getObjectMapper(), requestBody);
String jsonBody = Utils.convertToJson(AbstractTmdbApi.getObjectMapper(), requestBody);

String body = TestUtils.readTestFile("api_responses/account/add_to_watchlist.json");
when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body);
Expand All @@ -139,12 +137,12 @@ public void testRemoveFromWatchList() throws IOException, TmdbException {
Integer mediaId = 1234;
TmdbAccount.MediaType mediaType = TmdbAccount.MediaType.MOVIE;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/watchlist?session_id=testSessionId");
String url = TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/watchlist?session_id=testSessionId";
HashMap<String, Object> requestBody = new HashMap<>();
requestBody.put("media_type", mediaType.toString());
requestBody.put("media_id", mediaId);
requestBody.put("watchlist", false);
String jsonBody = Utils.convertToJson(getObjectMapper(), requestBody);
String jsonBody = Utils.convertToJson(AbstractTmdbApi.getObjectMapper(), requestBody);

String body = TestUtils.readTestFile("api_responses/account/add_to_watchlist.json");
when(getTmdbUrlReader().readUrl(url, jsonBody, RequestType.POST)).thenReturn(body);
Expand All @@ -166,8 +164,8 @@ public void testGetFavouriteMovies() throws TmdbException, IOException {
Integer page = 1;
AccountSortBy sortBy = AccountSortBy.CREATED_AT_ASC;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT +
"/1234/favorite/movies?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc");
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);

Expand All @@ -187,8 +185,8 @@ public void testGetFavouriteTv() throws IOException, TmdbException {
Integer page = 1;
AccountSortBy sortBy = AccountSortBy.CREATED_AT_ASC;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT +
"/1234/favorite/tv?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc");
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);

Expand All @@ -206,7 +204,7 @@ public void testGetLists() throws TmdbException, IOException {
String sessionId = "testSessionId";
Integer page = 1;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT + "/1234/lists?session_id=testSessionId&page=1");
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);

Expand All @@ -226,8 +224,8 @@ public void testGetRatedMovies() throws TmdbException, IOException {
Integer page = 1;
AccountSortBy sortBy = AccountSortBy.CREATED_AT_ASC;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT +
"/1234/rated/movies?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc");
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);

Expand All @@ -247,8 +245,8 @@ public void testGetRatedTvSeries() throws TmdbException, IOException {
Integer page = 1;
AccountSortBy sortBy = AccountSortBy.CREATED_AT_ASC;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT +
"/1234/rated/tv?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc");
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);

Expand All @@ -268,8 +266,8 @@ public void testGetRatedTvEpisodes() throws TmdbException, IOException {
Integer page = 1;
AccountSortBy sortBy = AccountSortBy.CREATED_AT_ASC;

URL url = new 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 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);

Expand All @@ -290,8 +288,8 @@ public void testGetWatchListMovies() throws TmdbException, IOException {
Integer page = 1;
AccountSortBy sortBy = AccountSortBy.CREATED_AT_ASC;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT +
"/1234/watchlist/movies?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc");
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);

Expand All @@ -311,8 +309,8 @@ public void testGetWatchListTvSeries() throws TmdbException, IOException {
Integer page = 1;
AccountSortBy sortBy = AccountSortBy.CREATED_AT_ASC;

URL url = new URL(TMDB_API_BASE_URL + TMDB_METHOD_ACCOUNT +
"/1234/watchlist/tv?session_id=testSessionId&language=en&page=1&sort_by=created_at.asc");
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);

Expand Down
Loading