Skip to content

Commit

Permalink
Utility functionality and refactor (#254)
Browse files Browse the repository at this point in the history
* add private

* create json utils class

* refactor object mapper to be in json util class

* test package rename "util" --> "testutil"

* add utility functions for base model classes

* make string required type for keys

* tests
  • Loading branch information
c-eg authored Nov 26, 2024
1 parent a56679f commit 952ca94
Show file tree
Hide file tree
Showing 44 changed files with 305 additions and 157 deletions.
19 changes: 6 additions & 13 deletions src/main/java/info/movito/themoviedbapi/AbstractTmdbApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
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 lombok.AccessLevel;
import lombok.Getter;
import info.movito.themoviedbapi.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -32,11 +29,7 @@ public abstract class AbstractTmdbApi {

public static final String PARAM_SORT_BY = "sort_by";

@Getter(AccessLevel.PROTECTED)
private static final ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

private static final ObjectReader responseStatusReader = objectMapper.readerFor(ResponseStatus.class);
private static final ObjectReader RESPONSE_STATUS_READER = JsonUtil.OBJECT_MAPPER.readerFor(ResponseStatus.class);

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

Expand Down Expand Up @@ -107,7 +100,7 @@ protected <T> T mapJsonResult(ApiUrl apiUrl, String jsonBody, TypeReference<T> r
* @return the mapped class.
*/
protected <T> T mapJsonResult(ApiUrl apiUrl, String jsonBody, RequestType requestType, Class<T> clazz) throws TmdbException {
return mapJsonResult(apiUrl, jsonBody, requestType, objectMapper.readerFor(clazz));
return mapJsonResult(apiUrl, jsonBody, requestType, JsonUtil.OBJECT_MAPPER.readerFor(clazz));
}

/**
Expand All @@ -122,7 +115,7 @@ protected <T> T mapJsonResult(ApiUrl apiUrl, String jsonBody, RequestType reques
*/
protected <T> T mapJsonResult(ApiUrl apiUrl, String jsonBody, RequestType requestType, TypeReference<T> resultClass)
throws TmdbException {
return mapJsonResult(apiUrl, jsonBody, requestType, objectMapper.readerFor(resultClass));
return mapJsonResult(apiUrl, jsonBody, requestType, JsonUtil.OBJECT_MAPPER.readerFor(resultClass));
}

/**
Expand All @@ -141,7 +134,7 @@ private <T> T mapJsonResult(ApiUrl apiUrl, String jsonBody, RequestType requestT
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 = responseStatusReader.readValue(jsonResponse);
ResponseStatus responseStatus = RESPONSE_STATUS_READER.readValue(jsonResponse);
TmdbResponseCode tmdbResponseCode = responseStatus.getStatusCode();

if (tmdbResponseCode != null) {
Expand All @@ -156,7 +149,7 @@ else if (!tmdbResponseCode.isSuccess()) {
}
}
catch (JsonProcessingException exception) {
// ignore, not an error - caused by responseStatusReader.readValue(jsonResponse);
// 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) {
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/info/movito/themoviedbapi/TmdbAccount.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import info.movito.themoviedbapi.tools.RequestType;
import info.movito.themoviedbapi.tools.TmdbException;
import info.movito.themoviedbapi.tools.sortby.AccountSortBy;
import info.movito.themoviedbapi.util.Utils;
import info.movito.themoviedbapi.util.JsonUtil;

/**
* The movie database api for accounts. See the
Expand Down Expand Up @@ -89,7 +89,7 @@ private ResponseStatus changeFavoriteStatus(Integer accountId, String sessionId,
body.put("media_id", mediaId);
body.put("favorite", isFavorite);

String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);
return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class);
}

Expand Down Expand Up @@ -135,7 +135,7 @@ private ResponseStatus changeWatchListStatus(Integer accountId, String sessionId
body.put("media_id", mediaId);
body.put("watchlist", isWatchList);

String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);
return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import info.movito.themoviedbapi.tools.ApiUrl;
import info.movito.themoviedbapi.tools.RequestType;
import info.movito.themoviedbapi.tools.TmdbException;
import info.movito.themoviedbapi.util.Utils;
import info.movito.themoviedbapi.util.JsonUtil;

/**
* The movie database api for authentication. See the
Expand Down Expand Up @@ -105,7 +105,7 @@ public RequestToken createAuthenticatedRequestToken(RequestToken token, String u
body.put("username", username);
body.put("password", password);
body.put(PARAM_REQUEST_TOKEN, token.getRequestToken());
String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);

return mapJsonResult(apiUrl, jsonBody, RequestType.POST, RequestToken.class);
}
Expand All @@ -128,7 +128,7 @@ public Session createSession(RequestToken token) throws TmdbException {

HashMap<String, Object> body = new HashMap<>();
body.put(PARAM_REQUEST_TOKEN, token.getRequestToken());
String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);

return mapJsonResult(apiUrl, jsonBody, RequestType.POST, Session.class);
}
Expand All @@ -151,7 +151,7 @@ public ResponseStatusDelete deleteSession(String sessionId) throws TmdbException

HashMap<String, Object> body = new HashMap<>();
body.put("session_id", sessionId);
String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);

return mapJsonResult(apiUrl, jsonBody, RequestType.DELETE, ResponseStatusDelete.class);
}
Expand Down
21 changes: 19 additions & 2 deletions src/main/java/info/movito/themoviedbapi/TmdbChanges.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package info.movito.themoviedbapi;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

import info.movito.themoviedbapi.model.changes.ChangesResultsPage;
import info.movito.themoviedbapi.tools.ApiUrl;
import info.movito.themoviedbapi.tools.TmdbException;

import static info.movito.themoviedbapi.util.Utils.calculateDaysDifference;

/**
* The movie database api for changes. See the
* <a href="https://developer.themoviedb.org/reference/changes-movie-list">documentation</a> for more info.
Expand Down Expand Up @@ -94,4 +96,19 @@ public ChangesResultsPage getTvChangesList(String startDate, String endDate, Int

return mapJsonResult(apiUrl, ChangesResultsPage.class);
}

/**
* Calculate the difference in days between two date strings.
*
* @param startDateString the start date string, in format: YYYY-MM-DD.
* @param endDateString the end date string, in format: YYYY-MM-DD.
* @return the difference in days.
*/
private static long calculateDaysDifference(String startDateString, String endDateString) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(startDateString, formatter);
LocalDate endDate = LocalDate.parse(endDateString, formatter);

return ChronoUnit.DAYS.between(startDate, endDate);
}
}
8 changes: 4 additions & 4 deletions src/main/java/info/movito/themoviedbapi/TmdbLists.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import info.movito.themoviedbapi.tools.ApiUrl;
import info.movito.themoviedbapi.tools.RequestType;
import info.movito.themoviedbapi.tools.TmdbException;
import info.movito.themoviedbapi.util.Utils;
import info.movito.themoviedbapi.util.JsonUtil;

/**
* The movie database api for lists. See the
Expand Down Expand Up @@ -42,7 +42,7 @@ public ResponseStatus addMovie(Integer listId, String sessionId, Integer movieId
HashMap<String, Object> body = new HashMap<>();
body.put("media_id", movieId);

String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);
return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class);
}

Expand Down Expand Up @@ -100,7 +100,7 @@ public MovieListCreationStatus create(String sessionId, String name, String desc
body.put("description", description);
body.put("language", language);

String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);
return mapJsonResult(apiUrl, jsonBody, RequestType.POST, MovieListCreationStatus.class);
}

Expand Down Expand Up @@ -153,7 +153,7 @@ public ResponseStatus removeMovie(Integer listId, String sessionId, Integer movi
HashMap<String, Object> body = new HashMap<>();
body.put("media_id", movieId);

String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);
return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class);
}
}
4 changes: 2 additions & 2 deletions src/main/java/info/movito/themoviedbapi/TmdbMovies.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import info.movito.themoviedbapi.tools.RequestType;
import info.movito.themoviedbapi.tools.TmdbException;
import info.movito.themoviedbapi.tools.appendtoresponse.MovieAppendToResponse;
import info.movito.themoviedbapi.util.Utils;
import info.movito.themoviedbapi.util.JsonUtil;

/**
* The movie database api for movies. See the
Expand Down Expand Up @@ -325,7 +325,7 @@ public ResponseStatus addRating(int movieId, String guestSessionId, String sessi
HashMap<String, Object> body = new HashMap<>();
body.put("value", rating);

String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);
return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class);
}

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/info/movito/themoviedbapi/TmdbTvEpisodes.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import info.movito.themoviedbapi.tools.RequestType;
import info.movito.themoviedbapi.tools.TmdbException;
import info.movito.themoviedbapi.tools.appendtoresponse.TvEpisodesAppendToResponse;
import info.movito.themoviedbapi.util.Utils;
import info.movito.themoviedbapi.util.JsonUtil;

import static info.movito.themoviedbapi.TmdbTvSeasons.TMDB_METHOD_TV_SEASON;
import static info.movito.themoviedbapi.TmdbTvSeries.TMDB_METHOD_TV;
Expand Down Expand Up @@ -213,7 +213,7 @@ public ResponseStatus addRating(int seriesId, int seasonNumber, int episodeNumbe
HashMap<String, Object> body = new HashMap<>();
body.put("value", rating);

String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);
return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class);
}

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/info/movito/themoviedbapi/TmdbTvSeries.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import info.movito.themoviedbapi.tools.RequestType;
import info.movito.themoviedbapi.tools.TmdbException;
import info.movito.themoviedbapi.tools.appendtoresponse.TvSeriesAppendToResponse;
import info.movito.themoviedbapi.util.Utils;
import info.movito.themoviedbapi.util.JsonUtil;

/**
* The movie database api for tv series. See the
Expand Down Expand Up @@ -368,7 +368,7 @@ public ResponseStatus addRating(int seriesId, String guestSessionId, String sess
HashMap<String, Object> body = new HashMap<>();
body.put("value", rating);

String jsonBody = Utils.convertToJson(getObjectMapper(), body);
String jsonBody = JsonUtil.toJson(body);
return mapJsonResult(apiUrl, jsonBody, RequestType.POST, ResponseStatus.class);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@
@EqualsAndHashCode(callSuper = true)
public class KeywordResults extends IdElement {
@JsonProperty("keywords")
List<Keyword> keywords;
private List<Keyword> keywords;
}
36 changes: 36 additions & 0 deletions src/main/java/info/movito/themoviedbapi/util/JsonUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package info.movito.themoviedbapi.util;

import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

/**
* JSON Utility.
*/
public final class JsonUtil {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

private static final ObjectWriter MAP_WRITER = OBJECT_MAPPER.writerFor(Map.class);

private JsonUtil() {
}

/**
* Converts a Map to a JSON String.
*
* @param map the map to convert.
* @return the json.
*/
public static String toJson(Map<String, ?> map) {
try {
return MAP_WRITER.writeValueAsString(map);
}
catch (JsonProcessingException jpe) {
throw new RuntimeException("json conversion failed", jpe);
}
}
}
37 changes: 37 additions & 0 deletions src/main/java/info/movito/themoviedbapi/util/ModelUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package info.movito.themoviedbapi.util;

import java.util.Collection;
import java.util.List;

import info.movito.themoviedbapi.model.core.NamedIdElement;
import info.movito.themoviedbapi.model.core.NamedStringIdElement;

/**
* TMDB API Model Utility.
*/
public final class ModelUtil {
private ModelUtil() {
}

/**
* Gets a list of names (from the name field) from the items in the collection provided.
* For model classes extending {@link NamedIdElement}.
*
* @param collection the collection.
* @return the list of names.
*/
public static List<String> getNames(Collection<? extends NamedIdElement> collection) {
return collection.stream().map(NamedIdElement::getName).toList();
}

/**
* Gets a list of names (from the name field) from the items in the collection provided.
* For model classes extending {@link NamedStringIdElement}.
*
* @param collection the collection.
* @return the list of names.
*/
public static List<String> getNamesString(Collection<? extends NamedStringIdElement> collection) {
return collection.stream().map(NamedStringIdElement::getName).toList();
}
}
44 changes: 0 additions & 44 deletions src/main/java/info/movito/themoviedbapi/util/Utils.java

This file was deleted.

1 change: 1 addition & 0 deletions src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,5 @@
exports info.movito.themoviedbapi.tools.builders.discover;
exports info.movito.themoviedbapi.tools.sortby;
exports info.movito.themoviedbapi.tools.model.time;
exports info.movito.themoviedbapi.util;
}
Loading

0 comments on commit 952ca94

Please sign in to comment.