Update API URL Builder

master
Stuart Boston 11 years ago
parent c6e9c3fcf5
commit dd2a35b54c

@ -110,20 +110,20 @@ public class TheMovieDbApi {
private TmdbConfiguration tmdbConfig; private TmdbConfiguration tmdbConfig;
private HttpTools httpTools; private HttpTools httpTools;
// API Methods // API Methods
private static final String BASE_MOVIE = "movie/"; private static final String BASE_MOVIE = "movie";
private static final String BASE_PERSON = "person/"; private static final String BASE_PERSON = "person";
private static final String BASE_COMPANY = "company/"; private static final String BASE_COMPANY = "company";
private static final String BASE_GENRE = "genre/"; private static final String BASE_GENRE = "genre";
private static final String BASE_AUTH = "authentication/"; private static final String BASE_AUTH = "authentication";
private static final String BASE_COLLECTION = "collection/"; private static final String BASE_COLLECTION = "collection";
private static final String BASE_ACCOUNT = "account/"; private static final String BASE_ACCOUNT = "account";
private static final String BASE_SEARCH = "search/"; private static final String BASE_SEARCH = "search";
private static final String BASE_LIST = "list/"; private static final String BASE_LIST = "list";
private static final String BASE_KEYWORD = "keyword/"; private static final String BASE_KEYWORD = "keyword";
private static final String BASE_JOB = "job/"; private static final String BASE_JOB = "job";
private static final String BASE_DISCOVER = "discover/"; private static final String BASE_DISCOVER = "discover";
private static final String URL_MOVIES = "/movies"; private static final String URL_MOVIES = "movies";
private static final String URL_IMAGES = "/images"; private static final String URL_IMAGES = "images";
// Jackson JSON configuration // Jackson JSON configuration
private static ObjectMapper mapper = new ObjectMapper(); private static ObjectMapper mapper = new ObjectMapper();
// Constants // Constants
@ -435,7 +435,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.SESSION, sessionId); parameters.add(Param.SESSION, sessionId);
URL url = new ApiUrl(apiKey, BASE_ACCOUNT.replace("/", "")).buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_ACCOUNT).buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
try { try {
@ -458,7 +458,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.SESSION, sessionId); parameters.add(Param.SESSION, sessionId);
URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "/favorite_movies").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "favorite_movies").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
try { try {
@ -478,7 +478,7 @@ public class TheMovieDbApi {
body.put("favorite", isFavorite); body.put("favorite", isFavorite);
String jsonBody = convertToJson(body); String jsonBody = convertToJson(body);
URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "/favorite").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "favorite").buildUrl(parameters);
String webpage = httpTools.postRequest(url, jsonBody); String webpage = httpTools.postRequest(url, jsonBody);
try { try {
@ -524,7 +524,7 @@ public class TheMovieDbApi {
body.put("movie_watchlist", add); body.put("movie_watchlist", add);
String jsonBody = convertToJson(body); String jsonBody = convertToJson(body);
URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "/movie_watchlist").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "movie_watchlist").buildUrl(parameters);
String webpage = httpTools.postRequest(url, jsonBody); String webpage = httpTools.postRequest(url, jsonBody);
try { try {
@ -624,7 +624,7 @@ public class TheMovieDbApi {
parameters.add(Param.COUNTRY, country); parameters.add(Param.COUNTRY, country);
parameters.add(Param.APPEND, appendToResponse); parameters.add(Param.APPEND, appendToResponse);
URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod("/alternative_titles").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod("alternative_titles").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
try { try {
WrapperAlternativeTitles wrapper = mapper.readValue(webpage, WrapperAlternativeTitles.class); WrapperAlternativeTitles wrapper = mapper.readValue(webpage, WrapperAlternativeTitles.class);
@ -1107,7 +1107,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.SESSION, sessionId); parameters.add(Param.SESSION, sessionId);
URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "/rated/movies").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "rated/movies").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
try { try {
@ -1137,7 +1137,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.SESSION, sessionId); parameters.add(Param.SESSION, sessionId);
URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod(movieId, "/rating").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod(movieId, "rating").buildUrl(parameters);
String jsonBody = convertToJson(Collections.singletonMap("value", rating)); String jsonBody = convertToJson(Collections.singletonMap("value", rating));
String webpage = httpTools.postRequest(url, jsonBody); String webpage = httpTools.postRequest(url, jsonBody);
@ -1518,8 +1518,8 @@ public class TheMovieDbApi {
parameters.add(Param.QUERY, movieName); parameters.add(Param.QUERY, movieName);
parameters.add(Param.YEAR, searchYear); parameters.add(Param.YEAR, searchYear);
parameters.add(Param.LANGUAGE, language); parameters.add(Param.LANGUAGE, language);
parameters.add(Param.ADULT, Boolean.toString(includeAdult)); parameters.add(Param.ADULT, includeAdult);
parameters.add(Param.PAGE, Integer.toString(page)); parameters.add(Param.PAGE, page);
URL url = new ApiUrl(apiKey, BASE_SEARCH).setSubMethod("movie").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_SEARCH).setSubMethod("movie").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
@ -1549,7 +1549,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.QUERY, query); parameters.add(Param.QUERY, query);
parameters.add(Param.LANGUAGE, language); parameters.add(Param.LANGUAGE, language);
parameters.add(Param.PAGE, Integer.toString(page)); parameters.add(Param.PAGE, page);
URL url = new ApiUrl(apiKey, BASE_SEARCH).setSubMethod("collection").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_SEARCH).setSubMethod("collection").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
@ -1610,7 +1610,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.QUERY, query); parameters.add(Param.QUERY, query);
parameters.add(Param.LANGUAGE, language); parameters.add(Param.LANGUAGE, language);
parameters.add(Param.PAGE, Integer.toString(page)); parameters.add(Param.PAGE, page);
URL url = new ApiUrl(apiKey, BASE_SEARCH).setSubMethod("list").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_SEARCH).setSubMethod("list").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
@ -1669,7 +1669,7 @@ public class TheMovieDbApi {
public TmdbResultsList<Keyword> searchKeyword(String query, int page) throws MovieDbException { public TmdbResultsList<Keyword> searchKeyword(String query, int page) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.QUERY, query); parameters.add(Param.QUERY, query);
parameters.add(Param.PAGE, Integer.toString(page)); parameters.add(Param.PAGE, page);
URL url = new ApiUrl(apiKey, BASE_SEARCH).setSubMethod("keyword").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_SEARCH).setSubMethod("keyword").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
@ -1721,7 +1721,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.SESSION, sessionId); parameters.add(Param.SESSION, sessionId);
URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountID, "/lists").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountID, "lists").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
try { try {
@ -1773,7 +1773,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, movieId); parameters.add(Param.ID, movieId);
URL url = new ApiUrl(apiKey, BASE_LIST).setSubMethod(listId, "/item_status").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_LIST).setSubMethod(listId, "item_status").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
try { try {
@ -1795,7 +1795,7 @@ public class TheMovieDbApi {
* @throws MovieDbException * @throws MovieDbException
*/ */
public StatusCode addMovieToList(String sessionId, String listId, Integer movieId) throws MovieDbException { public StatusCode addMovieToList(String sessionId, String listId, Integer movieId) throws MovieDbException {
return modifyMovieList(sessionId, listId, movieId, "/add_item"); return modifyMovieList(sessionId, listId, movieId, "add_item");
} }
/** /**
@ -1809,7 +1809,7 @@ public class TheMovieDbApi {
* @throws MovieDbException * @throws MovieDbException
*/ */
public StatusCode removeMovieFromList(String sessionId, String listId, Integer movieId) throws MovieDbException { public StatusCode removeMovieFromList(String sessionId, String listId, Integer movieId) throws MovieDbException {
return modifyMovieList(sessionId, listId, movieId, "/remove_item"); return modifyMovieList(sessionId, listId, movieId, "remove_item");
} }
private StatusCode modifyMovieList(String sessionId, String listId, Integer movieId, String operation) throws MovieDbException { private StatusCode modifyMovieList(String sessionId, String listId, Integer movieId, String operation) throws MovieDbException {
@ -1841,7 +1841,7 @@ public class TheMovieDbApi {
TmdbParameters parameters = new TmdbParameters(); TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.SESSION, sessionId); parameters.add(Param.SESSION, sessionId);
URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "/movie_watchlist").buildUrl(parameters); URL url = new ApiUrl(apiKey, BASE_ACCOUNT).setSubMethod(accountId, "movie_watchlist").buildUrl(parameters);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
try { try {
@ -1953,7 +1953,7 @@ public class TheMovieDbApi {
params.add(Param.START_DATE, startDate); params.add(Param.START_DATE, startDate);
params.add(Param.END_DATE, endDate); params.add(Param.END_DATE, endDate);
URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod("/changes").buildUrl(params); URL url = new ApiUrl(apiKey, BASE_MOVIE).setSubMethod("changes").buildUrl(params);
String webpage = httpTools.getRequest(url); String webpage = httpTools.getRequest(url);
try { try {

@ -23,9 +23,10 @@ import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -42,12 +43,10 @@ public class ApiUrl {
// Parameter configuration // Parameter configuration
private static final String DELIMITER_FIRST = "?"; private static final String DELIMITER_FIRST = "?";
private static final String DELIMITER_SUBSEQUENT = "&"; private static final String DELIMITER_SUBSEQUENT = "&";
private static final String DEFAULT_STRING = "";
// Properties // Properties
private final String apiKey; private final String apiKey;
private final String method; private final String method;
private String submethod; private String submethod = StringUtils.EMPTY;
private final Map<String, String> arguments = new HashMap<String, String>();
/** /**
* Constructor for the simple API URL method without a sub-method * Constructor for the simple API URL method without a sub-method
@ -110,23 +109,26 @@ public class ApiUrl {
* @param params * @param params
* @return * @return
*/ */
public URL buildUrl(TmdbParameters params) { public URL buildUrl(final TmdbParameters params) {
StringBuilder urlString = new StringBuilder(TMDB_API_BASE); StringBuilder urlString = new StringBuilder(TMDB_API_BASE);
LOG.trace("Method: '{}', Sub-method: '{}', Params: {}", method, submethod,
ToStringBuilder.reflectionToString(params, ToStringStyle.SHORT_PREFIX_STYLE));
// Get the start of the URL // Get the start of the URL
urlString.append(method); urlString.append(method);
// We have either a queury, or a direct request // We have either a queury, or a direct request
if (params.has(Param.QUERY)) { if (params.has(Param.QUERY)) {
// Append the suffix of the API URL // Append the suffix of the API URL
if (StringUtils.endsWith(urlString, "/") && submethod.startsWith("/")) { if (StringUtils.isNotBlank(submethod)) {
urlString.deleteCharAt(urlString.length() - 1); urlString.append("/").append(submethod);
} }
urlString.append(submethod);
// Append the key information // Append the key information
urlString.append(DELIMITER_FIRST).append(Param.API_KEY.getValue()); urlString.append(DELIMITER_FIRST)
urlString.append(apiKey); .append(Param.API_KEY.getValue())
.append(apiKey);
// Append the search term // Append the search term
urlString.append(DELIMITER_SUBSEQUENT); urlString.append(DELIMITER_SUBSEQUENT);
@ -141,40 +143,40 @@ public class ApiUrl {
// If we can't encode it, try it raw // If we can't encode it, try it raw
urlString.append(query); urlString.append(query);
} }
// Remove the query from the arguments so it is not added later
params.remove(Param.QUERY);
} else { } else {
// Append the ID if provided // Append the ID if provided
if (params.has(Param.ID)) { if (params.has(Param.ID)) {
urlString.append(params.get(Param.ID)); urlString.append("/").append(params.get(Param.ID));
params.remove(Param.ID);
} }
// Append the suffix of the API URL if (StringUtils.isNotBlank(submethod)) {
if (StringUtils.endsWith(urlString, "/") && submethod.startsWith("/")) { urlString.append("/").append(submethod);
urlString.deleteCharAt(urlString.length() - 1);
} }
urlString.append(submethod);
// Append the key information // Append the key information
urlString.append(DELIMITER_FIRST).append(Param.API_KEY); urlString.append(DELIMITER_FIRST)
urlString.append(apiKey); .append(Param.API_KEY.getValue())
.append(apiKey);
} }
for (Map.Entry<String, String> argEntry : arguments.entrySet()) { // Append remaining parameters
urlString.append(DELIMITER_SUBSEQUENT).append(argEntry.getKey()); for (Map.Entry<Param, String> argEntry : params.getEntries()) {
urlString.append(argEntry.getValue()); // Skip the ID an QUERY params
if (argEntry.getKey() == Param.ID || argEntry.getKey() == Param.QUERY) {
continue;
}
urlString.append(DELIMITER_SUBSEQUENT)
.append(argEntry.getKey().getValue())
.append(argEntry.getValue());
} }
try { try {
LOG.trace("URL: {}", urlString.toString()); LOG.trace("URL: {}", urlString.toString());
return new URL(urlString.toString()); return new URL(urlString.toString());
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
LOG.warn("Failed to create URL {} - {}", urlString.toString(), ex.toString()); LOG.warn("Failed to create URL {} - {}", urlString.toString(), ex.getMessage());
return null; return null;
} finally {
arguments.clear();
} }
} }
} }

@ -21,6 +21,7 @@ package com.omertron.themoviedbapi.tools;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
@ -40,12 +41,20 @@ public class TmdbParameters {
public TmdbParameters() { public TmdbParameters() {
} }
/**
* Get the entry set of the parameters
*
* @return
*/
public Set<Map.Entry<Param, String>> getEntries() {
return parameters.entrySet();
}
/** /**
* Add a parameter to the collection * Add a parameter to the collection
* *
* @param key Parameter to add * @param key Parameter to add
* @param value The array value to use (will be converted into a comma * @param value The array value to use (will be converted into a comma separated list)
* separated list)
*/ */
public void add(Param key, String[] value) { public void add(Param key, String[] value) {
parameters.put(key, toList(value)); parameters.put(key, toList(value));
@ -70,7 +79,7 @@ public class TmdbParameters {
* @param value The value to add (will be checked to ensure >0) * @param value The value to add (will be checked to ensure >0)
*/ */
public void add(Param key, int value) { public void add(Param key, int value) {
if (value > 0) { if (value > 0f) {
parameters.put(key, String.valueOf(value)); parameters.put(key, String.valueOf(value));
} }
} }

@ -0,0 +1,142 @@
/*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package com.omertron.themoviedbapi.tools;
import com.omertron.themoviedbapi.TestLogger;
import java.net.URL;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test case for ApiUrl
*
* @author Stuart
*/
public class ApiUrlTest {
private static final Logger LOG = LoggerFactory.getLogger(ApiUrlTest.class);
private static final String APIKEY = "APIKEY";
public ApiUrlTest() {
}
@BeforeClass
public static void setUpClass() {
TestLogger.Configure();
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testConfiguration() {
LOG.info("Configuration Test");
URL result = new ApiUrl(APIKEY, "configuration").buildUrl();
String expResult = "http://api.themoviedb.org/3/configuration?api_key=APIKEY";
assertEquals("Wrong config URL", expResult, result.toString());
}
@Test
public void testQuery() {
LOG.info("Query Test");
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.QUERY, "query");
URL result = new ApiUrl(APIKEY, "method").buildUrl(parameters);
String expResult = "http://api.themoviedb.org/3/method?api_key=APIKEY&query=query";
assertEquals("Wrong Query URL", expResult, result.toString());
}
@Test
public void testQuerySub() {
LOG.info("Query-Sub Test");
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.QUERY, "query");
URL result = new ApiUrl(APIKEY, "method").setSubMethod("sub").buildUrl(parameters);
String expResult = "http://api.themoviedb.org/3/method/sub?api_key=APIKEY&query=query";
assertEquals("Wrong Query-Sub URL", expResult, result.toString());
}
@Test
public void testQueryExtra() {
LOG.info("Query Extra Test");
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.QUERY, "query");
parameters.add(Param.PAGE, 1);
parameters.add(Param.LANGUAGE, "lang");
URL result = new ApiUrl(APIKEY, "method").setSubMethod("sub").buildUrl(parameters);
String expResult = "http://api.themoviedb.org/3/method/sub?api_key=APIKEY&query=query&language=lang&page=1";
assertEquals("Wrong Query Extra URL", expResult, result.toString());
}
@Test
public void testId() {
LOG.info("ID Test");
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, "ID");
URL result = new ApiUrl(APIKEY, "method").buildUrl(parameters);
String expResult = "http://api.themoviedb.org/3/method/ID?api_key=APIKEY";
assertEquals("Wrong ID URL", expResult, result.toString());
}
@Test
public void testIdSub() {
LOG.info("ID-Sub Test");
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, "ID");
URL result = new ApiUrl(APIKEY, "method").setSubMethod("sub").buildUrl(parameters);
String expResult = "http://api.themoviedb.org/3/method/ID/sub?api_key=APIKEY";
assertEquals("Wrong ID-Sub URL", expResult, result.toString());
}
@Test
public void testIdExtra() {
LOG.info("ID Extra Test");
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, "ID");
parameters.add(Param.PAGE, 1);
parameters.add(Param.LANGUAGE, "lang");
URL result = new ApiUrl(APIKEY, "method").setSubMethod("sub").buildUrl(parameters);
String expResult = "http://api.themoviedb.org/3/method/ID/sub?api_key=APIKEY&language=lang&page=1";
assertEquals("Wrong Query Extra URL", expResult, result.toString());
}
}
Loading…
Cancel
Save