Updated methods with new TheMovieDb functionality

master
Omertron 13 years ago
parent ac0aa98a05
commit 658d39cefb

@ -5,7 +5,7 @@ public class MovieDbException extends Exception {
private static final long serialVersionUID = -8952129102483143278L; private static final long serialVersionUID = -8952129102483143278L;
public enum MovieDbExceptionType { public enum MovieDbExceptionType {
UNKNOWN_CAUSE, INVALID_URL, HTTP_404_ERROR, MOVIE_ID_NOT_FOUND, MAPPING_FAILED, CONNECTION_ERROR, INVALID_IMAGE; UNKNOWN_CAUSE, INVALID_URL, HTTP_404_ERROR, MOVIE_ID_NOT_FOUND, MAPPING_FAILED, CONNECTION_ERROR, INVALID_IMAGE, AUTHORISATION_FAILURE;
} }
private final MovieDbExceptionType exceptionType; private final MovieDbExceptionType exceptionType;

@ -17,7 +17,8 @@ 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 org.apache.commons.lang3.StringUtils; import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
@ -35,28 +36,42 @@ public class ApiUrl {
* TheMovieDb API Base URL * TheMovieDb API Base URL
*/ */
private static final String TMDB_API_BASE = "http://api.themoviedb.org/3/"; private static final String TMDB_API_BASE = "http://api.themoviedb.org/3/";
// private static final String TMDB_API_BASE = "http://private-3aa3-themoviedb.apiary.io/3/";
/* /*
* 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 PARAMETER_API_KEY = "api_key="; // The API Key is always needed and always first private static final String DEFAULT_STRING = "";
private static final String PARAMETER_QUERY = "query=";
private static final String PARAMETER_LANGUAGE = DELIMITER_SUBSEQUENT + "language=";
private static final String PARAMETER_COUNTRY = DELIMITER_SUBSEQUENT + "country=";
private static final String PARAMETER_PAGE = DELIMITER_SUBSEQUENT + "page=";
public static final String DEFAULT_STRING = "";
public static final int DEFAULT_INT = -1;
/* /*
* Properties * Properties
*/ */
private TheMovieDb tmdb;
private String method; private String method;
private String submethod; private String submethod;
private TheMovieDb tmdb; private Map<String, String> arguments = new HashMap<String, String>();
/*
* 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_MOVIE_ID = "movie_id=";
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=";
//<editor-fold defaultstate="collapsed" desc="Constructor Methods"> //<editor-fold defaultstate="collapsed" desc="Constructor Methods">
/** /**
* Constructor for the simple API URL method without a sub-method * Constructor for the simple API URL method without a sub-method
*
* @param method * @param method
*/ */
public ApiUrl(TheMovieDb tmdb, String method) { public ApiUrl(TheMovieDb tmdb, String method) {
@ -67,6 +82,7 @@ public class ApiUrl {
/** /**
* Constructor for the API URL with a sub-method * Constructor for the API URL with a sub-method
*
* @param method * @param method
* @param submethod * @param submethod
*/ */
@ -78,69 +94,58 @@ public class ApiUrl {
//</editor-fold> //</editor-fold>
/** /**
* Create the full URL with the API. * Build the URL from the pre-created arguments.
* *
* @param query
* @param tmdbId
* @param language
* @param country
* @param page
* @return * @return
*/ */
private URL getFullUrl(String query, String movieId, String language, String country, int page) { public URL buildUrl() {
StringBuilder urlString = new StringBuilder(TMDB_API_BASE); StringBuilder urlString = new StringBuilder(TMDB_API_BASE);
// Get the start of the URL // Get the start of the URL
urlString.append(method); urlString.append(method);
// Append the search term if required // We have either a queury, or a direct request
if (StringUtils.isNotBlank(query)) { if (arguments.containsKey(PARAM_QUERY)) {
urlString.append(DELIMITER_FIRST); // Append the suffix of the API URL
urlString.append(PARAMETER_QUERY); urlString.append(submethod);
// Append the key information
urlString.append(DELIMITER_FIRST).append(PARAM_API_KEY);
urlString.append(tmdb.getApiKey());
// Append the search term
urlString.append(DELIMITER_SUBSEQUENT);
urlString.append(PARAM_QUERY);
String query = arguments.get(PARAM_QUERY);
try { try {
urlString.append(URLEncoder.encode(query, "UTF-8")); urlString.append(URLEncoder.encode(query, "UTF-8"));
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
LOGGER.trace("Unable to encode query: '" + query + "' trying raw.");
// If we can't encode it, try it raw // If we can't encode it, try it raw
urlString.append(query); urlString.append(query);
} }
}
// Append the ID if provided
if (StringUtils.isNotBlank(movieId)) {
urlString.append(movieId);
}
// Append the suffix of the API URL
urlString.append(submethod);
// Append the key information arguments.remove(PARAM_QUERY);
if (StringUtils.isBlank(query)) {
// This is the first parameter
urlString.append(DELIMITER_FIRST);
} else { } else {
// The first parameter was the query // Append the ID if provided
urlString.append(DELIMITER_SUBSEQUENT); if (arguments.containsKey(PARAM_ID)) {
} urlString.append(arguments.get(PARAM_ID));
urlString.append(PARAMETER_API_KEY); arguments.remove(PARAM_ID);
urlString.append(tmdb.getApiKey()); }
// Append the language to the URL // Append the suffix of the API URL
if (StringUtils.isNotBlank(language)) { urlString.append(submethod);
urlString.append(PARAMETER_LANGUAGE);
urlString.append(language);
}
// Append the country to the URL // Append the key information
if (StringUtils.isNotBlank(country)) { urlString.append(DELIMITER_FIRST).append(PARAM_API_KEY);
urlString.append(PARAMETER_COUNTRY); urlString.append(tmdb.getApiKey());
urlString.append(country);
} }
// Append the page to the URL for (Map.Entry<String, String> argEntry : arguments.entrySet()) {
if (page > DEFAULT_INT) { urlString.append(DELIMITER_SUBSEQUENT).append(argEntry.getKey());
urlString.append(PARAMETER_PAGE); urlString.append(argEntry.getValue());
urlString.append(page);
} }
try { try {
@ -149,100 +154,54 @@ public class ApiUrl {
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
LOGGER.warn("Failed to create URL " + urlString.toString() + " - " + ex.toString()); LOGGER.warn("Failed to create URL " + urlString.toString() + " - " + ex.toString());
return null; return null;
} finally {
arguments.clear();
} }
} }
/** /**
* Create an URL using the query (string), language and page * Add arguments individually
* *
* @param query * @param key
* @param language * @param value
* @param page
* @return
*/
public URL getQueryUrl(String query, String language, int page) {
return getFullUrl(query, DEFAULT_STRING, language, null, page);
}
/**
* Create an URL using the query (string)
* @param query
* @return
*/
public URL getQueryUrl(String query) {
return getQueryUrl(query, DEFAULT_STRING, DEFAULT_INT);
}
/**
* Create an URL using the query (string) and language
* @param query
* @param language
* @return
*/ */
public URL getQueryUrl(String query, String language) { public void addArgument(String key, String value) {
return getQueryUrl(query, language, DEFAULT_INT); arguments.put(key, value);
} }
/** /**
* Create an URL using the movie ID, language and country code * Add arguments individually
* *
* @param movieId * @param key
* @param language * @param value
* @param country
* @return
*/
public URL getIdUrl(String movieId, String language, String country) {
return getFullUrl(DEFAULT_STRING, movieId, language, country, DEFAULT_INT);
}
/**
* Create an URL using the movie ID and language
* @param movieId
* @param language
* @return
*/
public URL getIdUrl(String movieId, String language) {
return getIdUrl(movieId, language, DEFAULT_STRING);
}
/**
* Create an URL using the movie ID
* @param movieId
* @return
*/ */
public URL getIdUrl(String movieId) { public void addArgument(String key, int value) {
return getIdUrl(movieId, DEFAULT_STRING, DEFAULT_STRING); arguments.put(key, Integer.toString(value));
} }
/** /**
* Create an URL using the movie ID, language and country code * Add arguments individually
* *
* @param movieId * @param key
* @param language * @param value
* @param country
* @return
*/ */
public URL getIdUrl(int movieId, String language, String country) { public void addArgument(String key, boolean value) {
return getIdUrl(String.valueOf(movieId), language, country); arguments.put(key, Boolean.toString(value));
} }
/** /**
* Create an URL using the movie ID and language * Clear the arguments
* @param movieId
* @param language
* @return
*/ */
public URL getIdUrl(int movieId, String language) { public void clearArguments() {
return getIdUrl(String.valueOf(movieId), language, DEFAULT_STRING); arguments.clear();
} }
/** /**
* Create an URL using the movie ID * Set the arguments directly
* @param movieId *
* @return * @param args
*/ */
public URL getIdUrl(int movieId) { public void setArguments(Map<String, String> args) {
return getIdUrl(String.valueOf(movieId), DEFAULT_STRING, DEFAULT_STRING); arguments.putAll(args);
} }
} }

@ -20,18 +20,27 @@ import org.apache.log4j.spi.LoggingEvent;
/** /**
* Log4J Filtering routine to remove API keys from the output * Log4J Filtering routine to remove API keys from the output
*
* @author Stuart.Boston * @author Stuart.Boston
* *
*/ */
public class FilteringLayout extends PatternLayout { public class FilteringLayout extends PatternLayout {
private static Pattern apiKeys = Pattern.compile("DO_NOT_MATCH");
public static void addApiKey(String apiKey) { private static final String REPLACEMENT = "[APIKEY]";
apiKeys = Pattern.compile(apiKey); private static Pattern replacementPattern = Pattern.compile("DO_NOT_MATCH");
/**
* Add the string to replace in the log output
*
* @param replacementString
*/
public static void addReplacementString(String replacementString) {
replacementPattern = Pattern.compile(replacementString);
} }
/** /**
* Extend the format to remove the API_KEYS from the output * Extend the format to remove the API_KEYS from the output
*
* @param event * @param event
* @return * @return
*/ */
@ -40,12 +49,12 @@ public class FilteringLayout extends PatternLayout {
if (event.getMessage() instanceof String) { if (event.getMessage() instanceof String) {
String message = event.getRenderedMessage(); String message = event.getRenderedMessage();
Matcher matcher = apiKeys.matcher(message); Matcher matcher = replacementPattern.matcher(message);
if (matcher.find()) { if (matcher.find()) {
String maskedMessage = matcher.replaceAll("[APIKEY]"); String maskedMessage = matcher.replaceAll(REPLACEMENT);
Throwable throwable = event.getThrowableInformation() != null ? Throwable throwable = event.getThrowableInformation() != null
event.getThrowableInformation().getThrowable() : null; ? event.getThrowableInformation().getThrowable() : null;
LoggingEvent maskedEvent = new LoggingEvent(event.fqnOfCategoryClass, LoggingEvent maskedEvent = new LoggingEvent(event.fqnOfCategoryClass,
Logger.getLogger(event.getLoggerName()), event.timeStamp, Logger.getLogger(event.getLoggerName()), event.timeStamp,

@ -13,9 +13,11 @@
package com.moviejukebox.themoviedb; package com.moviejukebox.themoviedb;
import com.moviejukebox.themoviedb.model.*; import com.moviejukebox.themoviedb.model.*;
import com.moviejukebox.themoviedb.tools.FilteringLayout;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.junit.*; import org.junit.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -46,6 +48,10 @@ public class TheMovieDbTest {
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() throws Exception {
// Set the logger level to TRACE
Logger.getRootLogger().setLevel(Level.TRACE);
// Show the version of the API
TheMovieDb.showVersion();
} }
@AfterClass @AfterClass
@ -54,6 +60,8 @@ public class TheMovieDbTest {
@Before @Before
public void setUp() { public void setUp() {
// Make sure the filter isn't applied to the test output
FilteringLayout.addReplacementString("DO_NOT_MATCH");
} }
@After @After
@ -76,6 +84,14 @@ public class TheMovieDbTest {
LOGGER.info(tmdbConfig.toString()); LOGGER.info(tmdbConfig.toString());
} }
/**
* Test of showVersion method, of class TheMovieDb.
*/
@Test
public void testShowVersion() {
// Not required
}
/** /**
* Test of searchMovie method, of class TheMovieDb. * Test of searchMovie method, of class TheMovieDb.
*/ */
@ -84,15 +100,16 @@ public class TheMovieDbTest {
LOGGER.info("searchMovie"); LOGGER.info("searchMovie");
// Try a movie with less than 1 page of results // Try a movie with less than 1 page of results
List<MovieDb> movieList = tmdb.searchMovie("Blade Runner", "", true); List<MovieDb> movieList = tmdb.searchMovie("Blade Runner", 0, "", true, 0);
// List<MovieDb> movieList = tmdb.searchMovie("Blade Runner", "", true);
assertTrue("No movies found, should be at least 1", movieList.size() > 0); assertTrue("No movies found, should be at least 1", movieList.size() > 0);
// Try a russian langugage movie // Try a russian langugage movie
movieList = tmdb.searchMovie("О чём говорят мужчины", "ru", true); movieList = tmdb.searchMovie("О чём говорят мужчины", 0, "ru", true, 0);
assertTrue("No movies found, should be at least 1", movieList.size() > 0); assertTrue("No movies found, should be at least 1", movieList.size() > 0);
// Try a movie with more than 20 results // Try a movie with more than 20 results
movieList = tmdb.searchMovie("Star Wars", "en", false); movieList = tmdb.searchMovie("Star Wars", 0, "en", false, 0);
assertTrue("Not enough movies found, should be over 15, found " + movieList.size(), movieList.size() >= 15); assertTrue("Not enough movies found, should be over 15, found " + movieList.size(), movieList.size() >= 15);
} }
@ -212,6 +229,10 @@ public class TheMovieDbTest {
assertFalse("No collection information", result.getParts().isEmpty()); assertFalse("No collection information", result.getParts().isEmpty());
} }
/**
* Test of createImageUrl method, of class TheMovieDb.
* @throws MovieDbException
*/
@Test @Test
public void testCreateImageUrl() throws MovieDbException { public void testCreateImageUrl() throws MovieDbException {
LOGGER.info("createImageUrl"); LOGGER.info("createImageUrl");
@ -383,14 +404,6 @@ public class TheMovieDbTest {
assertTrue("No company movies found", !results.isEmpty()); assertTrue("No company movies found", !results.isEmpty());
} }
/**
* Test of showVersion method, of class TheMovieDb.
*/
@Test
public void testShowVersion() {
// Not required
}
/** /**
* Test of searchCompanies method, of class TheMovieDb. * Test of searchCompanies method, of class TheMovieDb.
*/ */
@ -430,4 +443,54 @@ public class TheMovieDbTest {
List<MovieDb> results = tmdb.getGenreMovies(ID_GENRE_ACTION, "", true); List<MovieDb> results = tmdb.getGenreMovies(ID_GENRE_ACTION, "", true);
assertTrue("No genre movies found", !results.isEmpty()); assertTrue("No genre movies found", !results.isEmpty());
} }
/**
* Test of getUpcoming method, of class TheMovieDb.
*/
@Test
public void testGetUpcoming() throws Exception {
LOGGER.info("getUpcoming");
List<MovieDb> results = tmdb.getUpcoming("");
assertTrue("No upcoming movies found", !results.isEmpty());
}
/**
* Test of getCollectionImages method, of class TheMovieDb.
*/
@Test
public void testGetCollectionImages() throws Exception {
LOGGER.info("getCollectionImages");
String language = "";
List<Artwork> result = tmdb.getCollectionImages(ID_MOVIE_STAR_WARS_COLLECTION, language);
assertFalse("No artwork found", result.isEmpty());
}
/**
* Test of getAuthorisationToken method, of class TheMovieDb.
*/
// @Test
public void testGetAuthorisationToken() throws Exception {
LOGGER.info("getAuthorisationToken");
TokenAuthorisation result = tmdb.getAuthorisationToken();
assertFalse("Token is null", result == null);
assertTrue("Token is not valid", result.getSuccess());
LOGGER.info(result.toString());
}
/**
* Test of getSessionToken method, of class TheMovieDb.
*/
// @Test
public void testGetSessionToken() throws Exception {
LOGGER.info("getSessionToken");
TokenAuthorisation token = tmdb.getAuthorisationToken();
assertFalse("Token is null", token == null);
assertTrue("Token is not valid", token.getSuccess());
LOGGER.info(token.toString());
TokenSession result = tmdb.getSessionToken(token);
assertFalse("Session token is null", result == null);
assertTrue("Session token is not valid", result.getSuccess());
LOGGER.info(result.toString());
}
} }

Loading…
Cancel
Save