From c6e9c3fcf55bf2bdbf1fff6cbb26bf93150f83d4 Mon Sep 17 00:00:00 2001 From: Stuart Boston Date: Fri, 13 Feb 2015 15:41:01 +0000 Subject: [PATCH] Use Parameters class --- .../omertron/themoviedbapi/TheMovieDbApi.java | 854 ++++++++---------- .../themoviedbapi/model/Discover.java | 89 +- .../omertron/themoviedbapi/tools/ApiUrl.java | 183 ++-- .../omertron/themoviedbapi/tools/Param.java | 99 ++ .../themoviedbapi/tools/TmdbParameters.java | 173 ++++ 5 files changed, 718 insertions(+), 680 deletions(-) create mode 100644 src/main/java/com/omertron/themoviedbapi/tools/Param.java create mode 100644 src/main/java/com/omertron/themoviedbapi/tools/TmdbParameters.java diff --git a/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java b/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java index 5948116ac..8b8afeb7c 100644 --- a/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java +++ b/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java @@ -54,21 +54,9 @@ import com.omertron.themoviedbapi.model.Video; import com.omertron.themoviedbapi.results.TmdbResultsList; import com.omertron.themoviedbapi.results.TmdbResultsMap; import com.omertron.themoviedbapi.tools.ApiUrl; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_ADULT; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_COUNTRY; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_END_DATE; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_ID; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_INCLUDE_ALL_MOVIES; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_LANGUAGE; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_PAGE; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_PASSWORD; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_QUERY; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_SESSION; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_START_DATE; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_TOKEN; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_USERNAME; -import static com.omertron.themoviedbapi.tools.ApiUrl.PARAM_YEAR; import com.omertron.themoviedbapi.tools.HttpTools; +import com.omertron.themoviedbapi.tools.Param; +import com.omertron.themoviedbapi.tools.TmdbParameters; import com.omertron.themoviedbapi.wrapper.WrapperAlternativeTitles; import com.omertron.themoviedbapi.wrapper.WrapperChanges; import com.omertron.themoviedbapi.wrapper.WrapperCollection; @@ -110,7 +98,8 @@ import org.yamj.api.common.http.SimpleHttpClientBuilder; /** * The MovieDb API *

- * This is for version 3 of the API as specified here: http://help.themoviedb.org/kb/api/about-3 + * This is for version 3 of the API as specified here: + * http://help.themoviedb.org/kb/api/about-3 * * @author stuart.boston */ @@ -164,8 +153,7 @@ public class TheMovieDbApi { this.apiKey = apiKey; this.httpTools = new HttpTools(httpClient); - ApiUrl apiUrl = new ApiUrl(apiKey, "configuration"); - URL configUrl = apiUrl.buildUrl(); + URL configUrl = new ApiUrl(apiKey, "configuration").buildUrl(); String webpage = httpTools.getRequest(configUrl); try { @@ -194,7 +182,8 @@ public class TheMovieDbApi { * @param moviedb The moviedb object to compare too * @param title The title of the movie to compare * @param year The year of the movie to compare - * @param maxDistance The Levenshtein Distance between the two titles. 0 = exact match + * @param maxDistance The Levenshtein Distance between the two titles. 0 = + * exact match * @param caseSensitive true if the comparison is to be case sensitive * @return True if there is a match, False otherwise. */ @@ -310,21 +299,24 @@ public class TheMovieDbApi { // /** - * This method is used to generate a valid request token for user based authentication. + * This method is used to generate a valid request token for user based + * authentication. * * A request token is required in order to request a session id. * - * You can generate any number of request tokens but they will expire after 60 minutes. + * You can generate any number of request tokens but they will expire after + * 60 minutes. * - * As soon as a valid session id has been created the token will be destroyed. + * As soon as a valid session id has been created the token will be + * destroyed. * * @return * @throws MovieDbException */ public TokenAuthorisation getAuthorisationToken() throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_AUTH, "token/new"); + TmdbParameters parameters = new TmdbParameters(); + URL url = new ApiUrl(apiKey, BASE_AUTH).setSubMethod("token/new").buildUrl(parameters); - URL url = apiUrl.buildUrl(); String webpage = httpTools.getRequest(url); try { @@ -336,7 +328,8 @@ public class TheMovieDbApi { } /** - * This method is used to generate a session id for user based authentication. + * This method is used to generate a session id for user based + * authentication. * * A session id is required in order to use any of the write methods. * @@ -345,15 +338,15 @@ public class TheMovieDbApi { * @throws MovieDbException */ public TokenSession getSessionToken(TokenAuthorisation token) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_AUTH, "session/new"); + TmdbParameters parameters = new TmdbParameters(); if (!token.getSuccess()) { LOG.warn("Session token was not successful!"); - throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Authorisation token was not successful!", apiUrl.buildUrl()); + throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Authorisation token was not successful!"); } - apiUrl.addArgument(PARAM_TOKEN, token.getRequestToken()); - URL url = apiUrl.buildUrl(); + parameters.add(Param.TOKEN, token.getRequestToken()); + URL url = new ApiUrl(apiKey, BASE_AUTH).setSubMethod("session/new").buildUrl(parameters); String webpage = httpTools.getRequest(url); try { @@ -365,7 +358,8 @@ public class TheMovieDbApi { } /** - * This method is used to generate a session id for user based authentication. User must provide their username and password + * This method is used to generate a session id for user based + * authentication. User must provide their username and password * * A session id is required in order to use any of the write methods. * @@ -376,18 +370,18 @@ public class TheMovieDbApi { * @throws MovieDbException */ public TokenAuthorisation getSessionTokenLogin(TokenAuthorisation token, String username, String password) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_AUTH, "token/validate_with_login"); + TmdbParameters parameters = new TmdbParameters(); if (!token.getSuccess()) { LOG.warn("Session token was not successful!"); - throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Authorisation token was not successful!", apiUrl.buildUrl()); + throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Authorisation token was not successful!"); } - apiUrl.addArgument(PARAM_TOKEN, token.getRequestToken()); - apiUrl.addArgument(PARAM_USERNAME, username); - apiUrl.addArgument(PARAM_PASSWORD, password); + parameters.add(Param.TOKEN, token.getRequestToken()); + parameters.add(Param.USERNAME, username); + parameters.add(Param.PASSWORD, password); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_AUTH).setSubMethod("token/validate_with_login").buildUrl(parameters); String webpage = httpTools.getRequest(url); try { @@ -401,22 +395,24 @@ public class TheMovieDbApi { /** * This method is used to generate a guest session id. * - * A guest session can be used to rate movies without having a registered TMDb user account. + * A guest session can be used to rate movies without having a registered + * TMDb user account. * - * You should only generate a single guest session per user (or device) as you will be able to attach the ratings to a TMDb user - * account in the future. + * You should only generate a single guest session per user (or device) as + * you will be able to attach the ratings to a TMDb user account in the + * future. * - * There are also IP limits in place so you should always make sure it's the end user doing the guest session actions. + * There are also IP limits in place so you should always make sure it's the + * end user doing the guest session actions. * - * If a guest session is not used for the first time within 24 hours, it will be automatically discarded. + * If a guest session is not used for the first time within 24 hours, it + * will be automatically discarded. * * @return * @throws MovieDbException */ public TokenSession getGuestSessionToken() throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_AUTH, "guest_session/new"); - - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_AUTH).setSubMethod("guest_session/new").buildUrl(); String webpage = httpTools.getRequest(url); try { @@ -428,18 +424,18 @@ public class TheMovieDbApi { } /** - * Get the basic information for an account. You will need to have a valid session id. + * Get the basic information for an account. You will need to have a valid + * session id. * * @param sessionId * @return * @throws MovieDbException */ public Account getAccount(String sessionId) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_ACCOUNT.replace("/", "")); - - apiUrl.addArgument(PARAM_SESSION, sessionId); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.SESSION, sessionId); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_ACCOUNT.replace("/", "")).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { @@ -450,11 +446,19 @@ public class TheMovieDbApi { } } + /** + * Get the account favourite movies + * + * @param sessionId + * @param accountId + * @return + * @throws MovieDbException + */ public List getFavoriteMovies(String sessionId, int accountId) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_ACCOUNT, accountId + "/favorite_movies"); - apiUrl.addArgument(PARAM_SESSION, sessionId); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.SESSION, sessionId); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "/favorite_movies").buildUrl(parameters); String webpage = httpTools.getRequest(url); try { @@ -466,16 +470,15 @@ public class TheMovieDbApi { } public StatusCode changeFavoriteStatus(String sessionId, int accountId, Integer movieId, boolean isFavorite) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_ACCOUNT, accountId + "/favorite"); - - apiUrl.addArgument(PARAM_SESSION, sessionId); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.SESSION, sessionId); Map body = new HashMap(); body.put(MOVIE_ID, movieId); body.put("favorite", isFavorite); String jsonBody = convertToJson(body); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "/favorite").buildUrl(parameters); String webpage = httpTools.postRequest(url, jsonBody); try { @@ -513,16 +516,15 @@ public class TheMovieDbApi { } private StatusCode modifyWatchList(String sessionId, int accountId, Integer movieId, boolean add) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_ACCOUNT, accountId + "/movie_watchlist"); - - apiUrl.addArgument(PARAM_SESSION, sessionId); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.SESSION, sessionId); Map body = new HashMap(); body.put(MOVIE_ID, movieId); body.put("movie_watchlist", add); String jsonBody = convertToJson(body); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "/movie_watchlist").buildUrl(parameters); String webpage = httpTools.postRequest(url, jsonBody); try { @@ -540,7 +542,8 @@ public class TheMovieDbApi { * * It will return the single highest rated poster and backdrop. * - * ApiExceptionType.MOVIE_ID_NOT_FOUND will be thrown if there are no movies found. + * ApiExceptionType.MOVIE_ID_NOT_FOUND will be thrown if there are no movies + * found. * * @param movieId * @param language @@ -549,17 +552,12 @@ public class TheMovieDbApi { * @throws MovieDbException */ public MovieDb getMovieInfo(int movieId, String language, String... appendToResponse) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_MOVIE); - - apiUrl.addArgument(PARAM_ID, movieId); - - if (StringUtils.isNotBlank(language)) { - apiUrl.addArgument(PARAM_LANGUAGE, language); - } - - apiUrl.appendToResponse(appendToResponse); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.ID, movieId); + parameters.add(Param.LANGUAGE, language); + parameters.add(Param.APPEND, appendToResponse); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_MOVIE).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { MovieDb movie = mapper.readValue(webpage, MovieDb.class); @@ -579,7 +577,8 @@ public class TheMovieDbApi { * * It will return the single highest rated poster and backdrop. * - * ApiExceptionType.MOVIE_ID_NOT_FOUND will be thrown if there are no movies found. + * ApiExceptionType.MOVIE_ID_NOT_FOUND will be thrown if there are no movies + * found. * * @param imdbId * @param language @@ -588,18 +587,14 @@ public class TheMovieDbApi { * @throws MovieDbException */ public MovieDb getMovieInfoImdb(String imdbId, String language, String... appendToResponse) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_MOVIE); - - apiUrl.addArgument(PARAM_ID, imdbId); - - if (StringUtils.isNotBlank(language)) { - apiUrl.addArgument(PARAM_LANGUAGE, language); - } - - apiUrl.appendToResponse(appendToResponse); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.ID, imdbId); + parameters.add(Param.LANGUAGE, language); + parameters.add(Param.APPEND, appendToResponse); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_MOVIE).buildUrl(parameters); String webpage = httpTools.getRequest(url); + try { MovieDb movie = mapper.readValue(webpage, MovieDb.class); if (movie == null || movie.getId() == 0) { @@ -614,7 +609,8 @@ public class TheMovieDbApi { } /** - * This method is used to retrieve all of the alternative titles we have for a particular movie. + * This method is used to retrieve all of the alternative titles we have for + * a particular movie. * * @param movieId * @param country @@ -623,16 +619,12 @@ public class TheMovieDbApi { * @throws MovieDbException */ public TmdbResultsList getMovieAlternativeTitles(int movieId, String country, String... appendToResponse) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_MOVIE, "/alternative_titles"); - apiUrl.addArgument(PARAM_ID, movieId); - - if (StringUtils.isNotBlank(country)) { - apiUrl.addArgument(PARAM_COUNTRY, country); - } + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.ID, movieId); + parameters.add(Param.COUNTRY, country); + parameters.add(Param.APPEND, appendToResponse); - apiUrl.appendToResponse(appendToResponse); - - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod("/alternative_titles").buildUrl(parameters); String webpage = httpTools.getRequest(url); try { WrapperAlternativeTitles wrapper = mapper.readValue(webpage, WrapperAlternativeTitles.class); @@ -656,12 +648,11 @@ public class TheMovieDbApi { * @throws MovieDbException */ public TmdbResultsList getMovieCasts(int movieId, String... appendToResponse) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_MOVIE, "/casts"); - apiUrl.addArgument(PARAM_ID, movieId); - - apiUrl.appendToResponse(appendToResponse); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.ID, movieId); + parameters.add(Param.APPEND, appendToResponse); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod("casts").buildUrl(parameters); String webpage = httpTools.getRequest(url); try { @@ -676,7 +667,8 @@ public class TheMovieDbApi { } /** - * This method should be used when you’re wanting to retrieve all of the images for a particular movie. + * This method should be used when you’re wanting to retrieve all of the + * images for a particular movie. * * @param movieId * @param language @@ -685,16 +677,12 @@ public class TheMovieDbApi { * @throws MovieDbException */ public TmdbResultsList getMovieImages(int movieId, String language, String... appendToResponse) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_MOVIE, URL_IMAGES); - apiUrl.addArgument(PARAM_ID, movieId); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.ID, movieId); + parameters.add(Param.LANGUAGE, language); + parameters.add(Param.APPEND, appendToResponse); - if (StringUtils.isNotBlank(language)) { - apiUrl.addArgument(PARAM_LANGUAGE, language); - } - - apiUrl.appendToResponse(appendToResponse); - - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod(URL_IMAGES).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { @@ -709,7 +697,8 @@ public class TheMovieDbApi { } /** - * This method is used to retrieve all of the keywords that have been added to a particular movie. + * This method is used to retrieve all of the keywords that have been added + * to a particular movie. * * Currently, only English keywords exist. * @@ -719,12 +708,11 @@ public class TheMovieDbApi { * @throws MovieDbException */ public TmdbResultsList getMovieKeywords(int movieId, String... appendToResponse) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_MOVIE, "/keywords"); - apiUrl.addArgument(PARAM_ID, movieId); - - apiUrl.appendToResponse(appendToResponse); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.ID, movieId); + parameters.add(Param.APPEND, appendToResponse); - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod("keywords").buildUrl(parameters); String webpage = httpTools.getRequest(url); try { @@ -739,7 +727,8 @@ public class TheMovieDbApi { } /** - * This method is used to retrieve all of the release and certification data we have for a specific movie. + * This method is used to retrieve all of the release and certification data + * we have for a specific movie. * * @param movieId * @param language @@ -748,13 +737,12 @@ public class TheMovieDbApi { * @throws MovieDbException */ public TmdbResultsList getMovieReleaseInfo(int movieId, String language, String... appendToResponse) throws MovieDbException { - ApiUrl apiUrl = new ApiUrl(apiKey, BASE_MOVIE, "/releases"); - apiUrl.addArgument(PARAM_ID, movieId); - apiUrl.addArgument(PARAM_LANGUAGE, language); + TmdbParameters parameters = new TmdbParameters(); + parameters.add(Param.ID, movieId); + parameters.add(Param.LANGUAGE, language); + parameters.add(Param.APPEND, appendToResponse); - apiUrl.appendToResponse(appendToResponse); - - URL url = apiUrl.buildUrl(); + URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod("releases").buildUrl(parameters); String webpage = httpTools.getRequest(url); try { @@ -769,7 +757,8 @@ public class TheMovieDbApi { } /** - * This method is used to retrieve all of the trailers for a particular movie. + * This method is used to retrieve all of the trailers for a particular + * movie. * * Supported sites are YouTube and QuickTime. * @@ -780,16 +769,12 @@ public class TheMovieDbApi { * @throws MovieDbException */ public TmdbResultsList

* Multiple values can be specified. *

- * Comma separated indicates an 'AND' query, while a pipe (|) separated value indicates an 'OR' + * Comma separated indicates an 'AND' query, while a pipe (|) separated + * value indicates an 'OR' * * @param withGenres * @return */ public Discover withGenres(String withGenres) { - if (StringUtils.isNotBlank(withGenres)) { - params.put(PARAM_WITH_GENRES, withGenres); - } + params.add(Param.WITH_GENRES, withGenres); return this; } @@ -197,9 +175,7 @@ public class Discover { * @return */ public Discover releaseDateGte(String releaseDateGte) { - if (StringUtils.isNotBlank(releaseDateGte)) { - params.put(PARAM_RELEASE_DATE_GTE, releaseDateGte); - } + params.add(Param.RELEASE_DATE_GTE, releaseDateGte); return this; } @@ -212,9 +188,7 @@ public class Discover { * @return */ public Discover releaseDateLte(String releaseDateLte) { - if (StringUtils.isNotBlank(releaseDateLte)) { - params.put(PARAM_RELEASE_DATE_LTE, releaseDateLte); - } + params.add(Param.RELEASE_DATE_LTE, releaseDateLte); return this; } @@ -229,24 +203,21 @@ public class Discover { * @return */ public Discover certificationCountry(String certificationCountry) { - if (StringUtils.isNotBlank(certificationCountry)) { - params.put(PARAM_CERTIFICATION_COUNTRY, certificationCountry); - } + params.add(Param.CERTIFICATION_COUNTRY, certificationCountry); return this; } /** * Only include movies with this certification and lower. *

- * Expected value is a valid certification for the specified 'certificationCountry'. + * Expected value is a valid certification for the specified + * 'certificationCountry'. * * @param certificationLte * @return */ public Discover certificationLte(String certificationLte) { - if (StringUtils.isNotBlank(certificationLte)) { - params.put(PARAM_CERTIFICATION_LTE, certificationLte); - } + params.add(Param.CERTIFICATION_LTE, certificationLte); return this; } @@ -261,9 +232,7 @@ public class Discover { * @return */ public Discover withCompanies(String withCompanies) { - if (StringUtils.isNotBlank(withCompanies)) { - params.put(PARAM_WITH_COMPANIES, withCompanies); - } + params.add(Param.WITH_COMPANIES, withCompanies); return this; } diff --git a/src/main/java/com/omertron/themoviedbapi/tools/ApiUrl.java b/src/main/java/com/omertron/themoviedbapi/tools/ApiUrl.java index 322e757db..8bff9328e 100644 --- a/src/main/java/com/omertron/themoviedbapi/tools/ApiUrl.java +++ b/src/main/java/com/omertron/themoviedbapi/tools/ApiUrl.java @@ -36,51 +36,19 @@ import org.slf4j.LoggerFactory; */ public class ApiUrl { - /* - * Logger - */ private static final Logger LOG = LoggerFactory.getLogger(ApiUrl.class); - /* - * TheMovieDbApi API Base URL - */ + // TheMovieDbApi API Base URL private static final String TMDB_API_BASE = "http://api.themoviedb.org/3/"; - /* - * Parameter configuration - */ + // Parameter configuration private static final String DELIMITER_FIRST = "?"; private static final String DELIMITER_SUBSEQUENT = "&"; private static final String DEFAULT_STRING = ""; - /* - * Properties - */ + // Properties private final String apiKey; private final String method; - private final String submethod; + private String submethod; private final Map arguments = new HashMap(); - /* - * API Parameters - */ - public static final String PARAM_ADULT = "include_adult="; - public static final String PARAM_API_KEY = "api_key="; - public static final String PARAM_COUNTRY = "country="; - public static final String PARAM_FAVORITE = "favorite="; - public static final String PARAM_ID = "id="; - public static final String PARAM_LANGUAGE = "language="; - public static final String PARAM_INCLUDE_ALL_MOVIES = "include_all_movies="; - public static final String PARAM_MOVIE_WATCHLIST = "movie_watchlist="; - public static final String PARAM_PAGE = "page="; - public static final String PARAM_QUERY = "query="; - public static final String PARAM_SESSION = "session_id="; - public static final String PARAM_TOKEN = "request_token="; - public static final String PARAM_VALUE = "value="; - public static final String PARAM_YEAR = "year="; - public static final String PARAM_START_DATE = "start_date="; - public static final String PARAM_END_DATE = "end_date="; - public static final String PARAM_USERNAME = "username="; - public static final String PARAM_PASSWORD = "password="; - private static final String APPEND_TO_RESPONSE = "append_to_response="; - // /** * Constructor for the simple API URL method without a sub-method * @@ -90,36 +58,66 @@ public class ApiUrl { public ApiUrl(String apiKey, String method) { this.apiKey = apiKey; this.method = method; - this.submethod = DEFAULT_STRING; } /** - * Constructor for the API URL with a sub-method + * Add a sub-methods * - * @param apiKey - * @param method * @param submethod + * @return */ - public ApiUrl(String apiKey, String method, String submethod) { - this.apiKey = apiKey; - this.method = method; + public ApiUrl setSubMethod(String submethod) { this.submethod = submethod; + return this; } - // /** - * Build the URL from the pre-created arguments. + * Add a sub-method that has an ID at the start + * + * @param someId + * @param submethod + * @return + */ + public ApiUrl setSubMethod(int someId, String submethod) { + this.submethod = someId + submethod; + return this; + } + + /** + * Add a sub-method that has an ID at the start + * + * @param someId + * @param submethod + * @return + */ + public ApiUrl setSubMethod(String someId, String submethod) { + this.submethod = someId + submethod; + return this; + } + + /** + * Build the URL with the default parameters * * @return */ public URL buildUrl() { + return buildUrl(new TmdbParameters()); + } + + /** + * Build the URL from the pre-created parameters. + * + * @param params + * @return + */ + public URL buildUrl(TmdbParameters params) { StringBuilder urlString = new StringBuilder(TMDB_API_BASE); // Get the start of the URL urlString.append(method); // We have either a queury, or a direct request - if (arguments.containsKey(PARAM_QUERY)) { + if (params.has(Param.QUERY)) { // Append the suffix of the API URL if (StringUtils.endsWith(urlString, "/") && submethod.startsWith("/")) { urlString.deleteCharAt(urlString.length() - 1); @@ -127,14 +125,14 @@ public class ApiUrl { urlString.append(submethod); // Append the key information - urlString.append(DELIMITER_FIRST).append(PARAM_API_KEY); + urlString.append(DELIMITER_FIRST).append(Param.API_KEY.getValue()); urlString.append(apiKey); // Append the search term urlString.append(DELIMITER_SUBSEQUENT); - urlString.append(PARAM_QUERY); + urlString.append(Param.QUERY.getValue()); - String query = arguments.get(PARAM_QUERY); + String query = (String) params.get(Param.QUERY); try { urlString.append(URLEncoder.encode(query, "UTF-8")); @@ -145,12 +143,12 @@ public class ApiUrl { } // Remove the query from the arguments so it is not added later - arguments.remove(PARAM_QUERY); + params.remove(Param.QUERY); } else { // Append the ID if provided - if (arguments.containsKey(PARAM_ID)) { - urlString.append(arguments.get(PARAM_ID)); - arguments.remove(PARAM_ID); + if (params.has(Param.ID)) { + urlString.append(params.get(Param.ID)); + params.remove(Param.ID); } // Append the suffix of the API URL @@ -160,7 +158,7 @@ public class ApiUrl { urlString.append(submethod); // Append the key information - urlString.append(DELIMITER_FIRST).append(PARAM_API_KEY); + urlString.append(DELIMITER_FIRST).append(Param.API_KEY); urlString.append(apiKey); } @@ -179,81 +177,4 @@ public class ApiUrl { arguments.clear(); } } - - /** - * Add arguments individually - * - * @param key - * @param value - */ - public void addArgument(String key, String value) { - arguments.put(key, value); - } - - /** - * Add arguments individually - * - * @param key - * @param value - */ - public void addArgument(String key, int value) { - arguments.put(key, Integer.toString(value)); - } - - /** - * Add arguments individually - * - * @param key - * @param value - */ - public void addArgument(String key, boolean value) { - arguments.put(key, Boolean.toString(value)); - } - - /** - * Add arguments individually - * - * @param key - * @param value - */ - public void addArgument(String key, float value) { - arguments.put(key, Float.toString(value)); - } - - /** - * Clear the arguments - */ - public void clearArguments() { - arguments.clear(); - } - - /** - * Set the arguments directly - * - * @param args - */ - public void setArguments(Map args) { - arguments.putAll(args); - } - - /** - * Append any optional parameters to the URL - * - * @param appendToResponse - */ - public void appendToResponse(String[] appendToResponse) { - if (appendToResponse.length > 0) { - StringBuilder sb = new StringBuilder(); - boolean first = Boolean.TRUE; - for (String append : appendToResponse) { - if (first) { - first = Boolean.FALSE; - } else { - sb.append(","); - } - sb.append(append); - } - addArgument(APPEND_TO_RESPONSE, sb.toString()); - } - } } diff --git a/src/main/java/com/omertron/themoviedbapi/tools/Param.java b/src/main/java/com/omertron/themoviedbapi/tools/Param.java new file mode 100644 index 000000000..fb46d3e69 --- /dev/null +++ b/src/main/java/com/omertron/themoviedbapi/tools/Param.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2004-2015 Stuart Boston + * + * This file is part of TheMovieDB API. + * + * TheMovieDB API is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * TheMovieDB API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with TheMovieDB API. If not, see . + * + */ +package com.omertron.themoviedbapi.tools; + +import java.util.EnumSet; +import org.apache.commons.lang3.StringUtils; + +/** + * Parameters for use in the URL + * + * @author Stuart + */ +public enum Param { + + ADULT("include_adult="), + API_KEY("api_key="), + APPEND("append_to_response="), + COUNTRY("country="), + END_DATE("end_date="), + FAVORITE("favorite="), + ID("id="), + INCLUDE_ALL_MOVIES("include_all_movies="), + LANGUAGE("language="), + MOVIE_WATCHLIST("movie_watchlist="), + PAGE("page="), + PASSWORD("password="), + QUERY("query="), + SESSION("session_id="), + START_DATE("start_date="), + TOKEN("request_token="), + USERNAME("username="), + VALUE("value="), + YEAR("year="), + /* + * Discover parameters + */ + CERTIFICATION_COUNTRY("certification_country="), + CERTIFICATION_LTE("certification.lte="), + PRIMARY_RELEASE_YEAR("primary_release_year="), + RELEASE_DATE_GTE("release_date.gte="), + RELEASE_DATE_LTE("release_date.lte="), + SORT_BY("sort_by="), + VOTE_AVERAGE_GTE("vote_average.gte="), + VOTE_COUNT_GTE("vote_count.gte="), + WITH_COMPANIES("with_companies="), + WITH_GENRES("with_genres="); + + private final String value; + + private Param(String value) { + this.value = value; + } + + /** + * Get the URL parameter to use + * + * @return + */ + public String getValue() { + return this.value; + } + + /** + * Convert a string into an Enum type + * + * @param value + * @return + */ + public static Param fromString(String value) { + if (StringUtils.isNotBlank(value)) { + for (final Param param : EnumSet.allOf(Param.class)) { + if (value.equalsIgnoreCase(param.value)) { + return param; + } + } + } + + // We've not found the type! + throw new IllegalArgumentException("Value '" + value + "' not recognised"); + } + +} diff --git a/src/main/java/com/omertron/themoviedbapi/tools/TmdbParameters.java b/src/main/java/com/omertron/themoviedbapi/tools/TmdbParameters.java new file mode 100644 index 000000000..eea019e2a --- /dev/null +++ b/src/main/java/com/omertron/themoviedbapi/tools/TmdbParameters.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2004-2015 Stuart Boston + * + * This file is part of TheMovieDB API. + * + * TheMovieDB API is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * TheMovieDB API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with TheMovieDB API. If not, see . + * + */ +package com.omertron.themoviedbapi.tools; + +import java.util.EnumMap; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * Parameters for the TMDB API + * + * @author Stuart + */ +public class TmdbParameters { + + private final Map parameters = new EnumMap(Param.class); + + /** + * Construct an empty set of parameters + */ + public TmdbParameters() { + } + + /** + * Add a parameter to the collection + * + * @param key Parameter to add + * @param value The array value to use (will be converted into a comma + * separated list) + */ + public void add(Param key, String[] value) { + parameters.put(key, toList(value)); + } + + /** + * Add a string parameter to the collection + * + * @param key Parameter to add + * @param value The value to add (will be checked to ensure it's valid) + */ + public void add(Param key, String value) { + if (StringUtils.isNotBlank(value)) { + parameters.put(key, value); + } + } + + /** + * Add an integer parameter to the collection + * + * @param key Parameter to add + * @param value The value to add (will be checked to ensure >0) + */ + public void add(Param key, int value) { + if (value > 0) { + parameters.put(key, String.valueOf(value)); + } + } + + /** + * Add a float parameter to the collection + * + * @param key Parameter to add + * @param value The value to add (will be checked to ensure >0) + */ + public void add(Param key, float value) { + if (value > 0) { + parameters.put(key, String.valueOf(value)); + } + } + + /** + * Add a boolean parameter to the collection + * + * @param key Parameter to add + * @param value The value to add (will be checked to ensure >0) + */ + public void add(Param key, boolean value) { + parameters.put(key, String.valueOf(value)); + } + + /** + * Check to see if the collection has a certain parameter + * + * @param key The Parameter to check + * @return + */ + public boolean has(Param key) { + return parameters.containsKey(key); + } + + /** + * Get a parameter from the collection + * + * @param key The parameter to get + * @return + */ + public Object get(Param key) { + return parameters.get(key); + } + + /** + * Remove a parameter from the collection + * + * @param key + */ + public void remove(Param key) { + parameters.remove(key); + } + + /** + * Check to see if the collection has no items + * + * @return + */ + public boolean isEmpty() { + return parameters.isEmpty(); + } + + /** + * Check to see if the collection has items + * + * @return + */ + public boolean isNotEmpty() { + return !isEmpty(); + } + + /** + * Append any optional parameters to the URL + * + * @param appendToResponse + * @return + */ + public String toList(String[] appendToResponse) { + StringBuilder sb = new StringBuilder(); + if (appendToResponse.length > 0) { + boolean first = Boolean.TRUE; + for (String append : appendToResponse) { + if (first) { + first = Boolean.FALSE; + } else { + sb.append(","); + } + sb.append(append); + } + } + return sb.toString(); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(parameters, ToStringStyle.SHORT_PREFIX_STYLE); + } +}