Update account methods

Move to their own class
Updated HttpClient for POST and DELETE
master
Stuart Boston 11 years ago
parent e736aee48a
commit 47ed93b69f

@ -61,10 +61,12 @@ 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.wrapper.WrapperAlternativeTitles;
@ -108,8 +110,7 @@ import org.yamj.api.common.http.SimpleHttpClientBuilder;
/**
* The MovieDb API
* <p>
* 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
*/
@ -193,8 +194,7 @@ 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,16 +310,13 @@ public class TheMovieDbApi {
//<editor-fold defaultstate="collapsed" desc="Authentication Functions">
/**
* 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
@ -339,8 +336,7 @@ 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.
*
@ -368,21 +364,51 @@ public class TheMovieDbApi {
}
}
/**
* 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.
*
* @param token Session token
* @param username User's username
* @param password User's password
* @return
* @throws MovieDbException
*/
public TokenAuthorisation getSessionTokenLogin(TokenAuthorisation token, String username, String password) throws MovieDbException {
ApiUrl apiUrl = new ApiUrl(apiKey, BASE_AUTH, "token/validate_with_login");
if (!token.getSuccess()) {
LOG.warn("Session token was not successful!");
throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Authorisation token was not successful!", apiUrl.buildUrl());
}
apiUrl.addArgument(PARAM_TOKEN, token.getRequestToken());
apiUrl.addArgument(PARAM_USERNAME, username);
apiUrl.addArgument(PARAM_PASSWORD, password);
URL url = apiUrl.buildUrl();
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, TokenAuthorisation.class);
} catch (IOException ex) {
LOG.warn("Failed to get Session Token: {}", ex.getMessage(), ex);
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, webpage, url, ex);
}
}
/**
* 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
@ -402,8 +428,7 @@ 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
@ -515,8 +540,7 @@ 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
@ -555,8 +579,7 @@ 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
@ -591,8 +614,7 @@ 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
@ -654,8 +676,7 @@ public class TheMovieDbApi {
}
/**
* This method should be used when youre wanting to retrieve all of the
* images for a particular movie.
* This method should be used when youre wanting to retrieve all of the images for a particular movie.
*
* @param movieId
* @param language
@ -688,8 +709,7 @@ 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,8 +739,7 @@ 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
@ -750,8 +769,7 @@ 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.
*
@ -786,8 +804,7 @@ public class TheMovieDbApi {
}
/**
* This method is used to retrieve a list of the available translations for
* a specific movie.
* This method is used to retrieve a list of the available translations for a specific movie.
*
* @param movieId
* @param appendToResponse
@ -815,11 +832,9 @@ public class TheMovieDbApi {
}
/**
* The similar movies method will let you retrieve the similar movies for a
* particular movie.
* The similar movies method will let you retrieve the similar movies for a particular movie.
*
* This data is created dynamically but with the help of users votes on
* TMDb.
* This data is created dynamically but with the help of users votes on TMDb.
*
* The data is much better with movies that have more keywords
*
@ -931,13 +946,11 @@ public class TheMovieDbApi {
*
* By default, only the last 24 hours of changes are returned.
*
* The maximum number of days that can be returned in a single request is
* 14.
* The maximum number of days that can be returned in a single request is 14.
*
* The language is present on fields that are translatable.
*
* TODO: DOES NOT WORK AT THE MOMENT. This is due to the "value" item
* changing type in the ChangeItem
* TODO: DOES NOT WORK AT THE MOMENT. This is due to the "value" item changing type in the ChangeItem
*
* @param movieId
* @param startDate the start date of the changes, optional
@ -1035,8 +1048,7 @@ public class TheMovieDbApi {
/**
* This method is used to retrieve the movies currently in theatres.
*
* This is a curated list that will normally contain 100 movies. The default
* response will return 20 movies.
* This is a curated list that will normally contain 100 movies. The default response will return 20 movies.
*
* TODO: Implement more than 20 movies
*
@ -1108,8 +1120,7 @@ public class TheMovieDbApi {
}
/**
* This method is used to retrieve the top rated movies that have over 10
* votes on TMDb.
* This method is used to retrieve the top rated movies that have over 10 votes on TMDb.
*
* The default response will return 20 movies.
*
@ -1154,7 +1165,7 @@ public class TheMovieDbApi {
* @throws MovieDbException
*/
public List<MovieDb> getRatedMovies(String sessionId, int accountId) throws MovieDbException {
ApiUrl apiUrl = new ApiUrl(apiKey, BASE_ACCOUNT, accountId + "/rated_movies");
ApiUrl apiUrl = new ApiUrl(apiKey, BASE_ACCOUNT, accountId + "/rated/movies");
apiUrl.addArgument(PARAM_SESSION, sessionId);
URL url = apiUrl.buildUrl();
@ -1189,7 +1200,7 @@ public class TheMovieDbApi {
}
String jsonBody = convertToJson(Collections.singletonMap("value", rating));
LOG.info("Body: {}", jsonBody);
LOG.debug("Body: {}", jsonBody);
URL url = apiUrl.buildUrl();
String webpage = httpTools.postRequest(url, jsonBody);
@ -1207,11 +1218,9 @@ public class TheMovieDbApi {
//<editor-fold defaultstate="collapsed" desc="Collection Functions">
/**
* This method is used to retrieve all of the basic information about a
* movie collection.
* This method is used to retrieve all of the basic information about a movie collection.
*
* You can get the ID needed for this method by making a getMovieInfo
* request for the belongs_to_collection.
* You can get the ID needed for this method by making a getMovieInfo request for the belongs_to_collection.
*
* @param collectionId
* @param language
@ -1297,8 +1306,7 @@ public class TheMovieDbApi {
}
/**
* This method is used to retrieve all of the cast & crew information for
* the person.
* This method is used to retrieve all of the cast & crew information for the person.
*
* It will return the single highest rated poster for each movie record.
*
@ -1360,8 +1368,7 @@ public class TheMovieDbApi {
*
* By default, only the last 24 hours of changes are returned.
*
* The maximum number of days that can be returned in a single request is
* 14.
* The maximum number of days that can be returned in a single request is 14.
*
* The language is present on fields that are translatable.
*
@ -1439,8 +1446,7 @@ public class TheMovieDbApi {
//<editor-fold defaultstate="collapsed" desc="Company Functions">
/**
* This method is used to retrieve the basic information about a production
* company on TMDb.
* This method is used to retrieve the basic information about a production company on TMDb.
*
* @param companyId
* @return
@ -1465,8 +1471,7 @@ public class TheMovieDbApi {
/**
* This method is used to retrieve the movies associated with a company.
*
* These movies are returned in order of most recently released to oldest.
* The default response will return 20 movies per page.
* These movies are returned in order of most recently released to oldest. The default response will return 20 movies per page.
*
* TODO: Implement more than 20 movies
*
@ -1535,11 +1540,9 @@ public class TheMovieDbApi {
/**
* Get a list of movies per genre.
*
* It is important to understand that only movies with more than 10 votes
* get listed.
* It is important to understand that only movies with more than 10 votes get listed.
*
* This prevents movies from 1 10/10 rating from being listed first and for
* the first 5 pages.
* This prevents movies from 1 10/10 rating from being listed first and for the first 5 pages.
*
* @param genreId
* @param language
@ -1579,16 +1582,13 @@ public class TheMovieDbApi {
//<editor-fold defaultstate="collapsed" desc="Search Functions">
/**
* Search Movies This is a good starting point to start finding movies on
* TMDb.
* Search Movies This is a good starting point to start finding movies on TMDb.
*
* @param movieName
* @param searchYear Limit the search to the provided year. Zero (0) will
* get all years
* @param searchYear Limit the search to the provided year. Zero (0) will get all years
* @param language The language to include. Can be blank/null.
* @param includeAdult true or false to include adult titles in the search
* @param page The page of results to return. 0 to get the default (first
* page)
* @param page The page of results to return. 0 to get the default (first page)
* @return
* @throws MovieDbException
*/
@ -1668,8 +1668,7 @@ public class TheMovieDbApi {
/**
* This is a good starting point to start finding people on TMDb.
*
* The idea is to be a quick and light method so you can iterate through
* people quickly.
* The idea is to be a quick and light method so you can iterate through people quickly.
*
* @param personName
* @param includeAdult
@ -1741,8 +1740,8 @@ public class TheMovieDbApi {
/**
* Search Companies.
*
* You can use this method to search for production companies that are part
* of TMDb. The company IDs will map to those returned on movie calls.
* You can use this method to search for production companies that are part of TMDb. The company IDs will map to those returned
* on movie calls.
*
* http://help.themoviedb.org/kb/api/search-companies
*
@ -1906,8 +1905,7 @@ public class TheMovieDbApi {
}
/**
* This method lets users add new movies to a list that they created. A
* valid session id is required.
* This method lets users add new movies to a list that they created. A valid session id is required.
*
* @param sessionId
* @param listId
@ -1920,8 +1918,7 @@ public class TheMovieDbApi {
}
/**
* This method lets users remove movies from a list that they created. A
* valid session id is required.
* This method lets users remove movies from a list that they created. A valid session id is required.
*
* @param sessionId
* @param listId
@ -1975,8 +1972,7 @@ public class TheMovieDbApi {
}
/**
* This method lets users delete a list that they created. A valid session
* id is required.
* This method lets users delete a list that they created. A valid session id is required.
*
* @param sessionId
* @param listId
@ -2063,12 +2059,10 @@ public class TheMovieDbApi {
//<editor-fold defaultstate="collapsed" desc="Changes Functions">
/**
* Get a list of movie ids that have been edited. By default we show the
* last 24 hours and only 100 items per page. The maximum number of days
* that can be returned in a single request is 14. You can then use the
* movie changes API to get the actual data that has been changed. Please
* note that the change log system to support this was changed on October 5,
* 2012 and will only show movies that have been edited since.
* Get a list of movie ids that have been edited. By default we show the last 24 hours and only 100 items per page. The maximum
* number of days that can be returned in a single request is 14. You can then use the movie changes API to get the actual data
* that has been changed. Please note that the change log system to support this was changed on October 5, 2012 and will only
* show movies that have been edited since.
*
* @param page
* @param startDate the start date of the changes, optional
@ -2132,42 +2126,30 @@ public class TheMovieDbApi {
//<editor-fold defaultstate="collapsed" desc="Discover">
/**
* Discover movies by different types of data like average rating, number of
* votes, genres and certifications.
* Discover movies by different types of data like average rating, number of votes, genres and certifications.
*
* You can alternatively create a "discover" object and pass it to this
* method to cut out the requirement for all of these parameters
* You can alternatively create a "discover" object and pass it to this method to cut out the requirement for all of these
* parameters
*
* @param page Minimum value is 1
* @param language ISO 639-1 code.
* @param sortBy Available options are vote_average.desc, vote_average.asc,
* release_date.desc, release_date.asc, popularity.desc, popularity.asc
* @param sortBy Available options are vote_average.desc, vote_average.asc, release_date.desc, release_date.asc,
* popularity.desc, popularity.asc
* @param includeAdult Toggle the inclusion of adult titles
* @param year Filter the results release dates to matches that include this
* value
* @param primaryReleaseYear Filter the results so that only the primary
* release date year has this value
* @param voteCountGte Only include movies that are equal to, or have a vote
* count higher than this value
* @param voteAverageGte Only include movies that are equal to, or have a
* higher average rating than this value
* @param withGenres Only include movies with the specified genres. Expected
* value is an integer (the id of a genre). Multiple values can be
* specified. Comma separated indicates an 'AND' query, while a pipe (|)
* separated value indicates an 'OR'.
* @param releaseDateGte The minimum release to include. Expected format is
* YYYY-MM-DD
* @param releaseDateLte The maximum release to include. Expected format is
* YYYY-MM-DD
* @param certificationCountry Only include movies with certifications for a
* specific country. When this value is specified, 'certificationLte' is
* required. A ISO 3166-1 is expected.
* @param certificationLte Only include movies with this certification and
* lower. Expected value is a valid certification for the specified
* 'certificationCountry'.
* @param withCompanies Filter movies to include a specific company.
* Expected value is an integer (the id of a company). They can be comma
* separated to indicate an 'AND' query.
* @param year Filter the results release dates to matches that include this value
* @param primaryReleaseYear Filter the results so that only the primary release date year has this value
* @param voteCountGte Only include movies that are equal to, or have a vote count higher than this value
* @param voteAverageGte Only include movies that are equal to, or have a higher average rating than this value
* @param withGenres Only include movies with the specified genres. Expected value is an integer (the id of a genre). Multiple
* values can be specified. Comma separated indicates an 'AND' query, while a pipe (|) separated value indicates an 'OR'.
* @param releaseDateGte The minimum release to include. Expected format is YYYY-MM-DD
* @param releaseDateLte The maximum release to include. Expected format is YYYY-MM-DD
* @param certificationCountry Only include movies with certifications for a specific country. When this value is specified,
* 'certificationLte' is required. A ISO 3166-1 is expected.
* @param certificationLte Only include movies with this certification and lower. Expected value is a valid certification for
* the specified 'certificationCountry'.
* @param withCompanies Filter movies to include a specific company. Expected value is an integer (the id of a company). They
* can be comma separated to indicate an 'AND' query.
* @return
* @throws MovieDbException
*/
@ -2195,8 +2177,7 @@ public class TheMovieDbApi {
}
/**
* Discover movies by different types of data like average rating, number of
* votes, genres and certifications.
* Discover movies by different types of data like average rating, number of votes, genres and certifications.
*
* @param discover A discover object containing the search criteria required
* @return

@ -76,6 +76,8 @@ public class ApiUrl {
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=";
//<editor-fold defaultstate="collapsed" desc="Constructor Methods">

@ -5,6 +5,8 @@ import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
@ -25,8 +27,7 @@ public class HttpTools {
private final CloseableHttpClient httpClient;
private static final Charset CHARSET = Charset.forName("UTF-8");
private static final int HTTP_STATUS_300 = 300;
private static final int HTTP_STATUS_500 = 500;
private static final String APPLICATION_JSON = "application/json";
public HttpTools(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
@ -42,7 +43,7 @@ public class HttpTools {
public String getRequest(final URL url) throws MovieDbException {
try {
HttpGet httpGet = new HttpGet(url.toURI());
httpGet.addHeader("accept", "application/json");
httpGet.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON);
return validateResponse(DigestedResponseReader.requestContent(httpClient, httpGet, CHARSET), url);
} catch (URISyntaxException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
@ -82,7 +83,8 @@ public class HttpTools {
public String postRequest(final URL url, final String jsonBody) throws MovieDbException {
try {
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
httpPost.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON);
StringEntity params = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
httpPost.setEntity(params);
@ -103,9 +105,9 @@ public class HttpTools {
* @throws MovieDbException
*/
private String validateResponse(final DigestedResponse response, final URL url) throws MovieDbException {
if (response.getStatusCode() >= HTTP_STATUS_500) {
if (response.getStatusCode() >= HttpStatus.SC_INTERNAL_SERVER_ERROR) {
throw new MovieDbException(ApiExceptionType.HTTP_503_ERROR, response.getContent(), response.getStatusCode(), url, null);
} else if (response.getStatusCode() >= HTTP_STATUS_300) {
} else if (response.getStatusCode() >= HttpStatus.SC_MULTIPLE_CHOICES) {
throw new MovieDbException(ApiExceptionType.HTTP_404_ERROR, response.getContent(), response.getStatusCode(), url, null);
}

@ -0,0 +1,275 @@
/*
* 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;
import com.omertron.themoviedbapi.model.Account;
import com.omertron.themoviedbapi.model.MovieDb;
import com.omertron.themoviedbapi.model.MovieDbList;
import com.omertron.themoviedbapi.model.StatusCode;
import com.omertron.themoviedbapi.model.TokenAuthorisation;
import com.omertron.themoviedbapi.model.TokenSession;
import java.io.File;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestAccounts {
private static final Logger LOG = LoggerFactory.getLogger(TestAccounts.class);
// API Key
private static final String PROP_FIlENAME = "testing.properties";
private static String API_KEY;
private static String ACCOUNT_USERNAME;
private static String ACCOUNT_PASSWORD;
private static TheMovieDbApi tmdb;
private static TokenSession tokenSession = null;
private static Account account = null;
public TestAccounts() throws MovieDbException {
}
@BeforeClass
public static void setUpClass() throws MovieDbException {
TestLogger.Configure();
Properties props = new Properties();
File f = new File(PROP_FIlENAME);
if (f.exists()) {
LOG.info("Loading properties from '{}'", PROP_FIlENAME);
TestLogger.loadProperties(props, f);
API_KEY = props.getProperty("API_Key");
ACCOUNT_USERNAME = props.getProperty("Username");
ACCOUNT_PASSWORD = props.getProperty("Password");
} else {
// Properties file is created in the main test class
fail("Failed to get key information from properties file '" + PROP_FIlENAME + "'");
}
tmdb = new TheMovieDbApi(API_KEY);
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() throws MovieDbException {
if (tokenSession == null) {
testSessionCreation();
}
if (account == null) {
testAccount();
}
}
@After
public void tearDown() {
}
/**
* Test and create a session token for the rest of the tests
*
* @throws MovieDbException
*/
@Test
public void testSessionCreation() throws MovieDbException {
LOG.info("Test and create a session token for the rest of the tests");
// 1: Create a request token
TokenAuthorisation token = tmdb.getAuthorisationToken();
assertFalse("Token (auth) is null", token == null);
assertTrue("Token (auth) is not valid", token.getSuccess());
LOG.info("Token (auth): {}", token.toString());
// 2b; Get user permission
token = tmdb.getSessionTokenLogin(token, ACCOUNT_USERNAME, ACCOUNT_PASSWORD);
assertFalse("Token (login) is null", token == null);
assertTrue("Token (login) is not valid", token.getSuccess());
LOG.info("Token (login): {}", token.toString());
// 3: Create the sessions ID
tokenSession = tmdb.getSessionToken(token);
assertFalse("Session token is null", tokenSession == null);
assertTrue("Session token is not valid", tokenSession.getSuccess());
LOG.info("Session token: {}", tokenSession.toString());
}
/**
* Test the account information
*
* @throws MovieDbException
*/
@Test
public void testAccount() throws MovieDbException {
LOG.info("Using Session ID '{}' for test", tokenSession.getSessionId());
account = tmdb.getAccount(tokenSession.getSessionId());
LOG.info("Account: {}", account);
// Make sure properties are extracted correctly
assertEquals("Wrong username!", ACCOUNT_USERNAME, account.getUserName());
}
@Test
public void testWatchList() throws MovieDbException {
// If the static account is null, get it
if (account == null) {
account = tmdb.getAccount(tokenSession.getSessionId());
}
// make sure it's empty (because it's just a test account
Assert.assertTrue(tmdb.getWatchList(tokenSession.getSessionId(), account.getId()).isEmpty());
// add a movie
tmdb.addToWatchList(tokenSession.getSessionId(), account.getId(), 550);
List<MovieDb> watchList = tmdb.getWatchList(tokenSession.getSessionId(), account.getId());
assertNotNull("Empty watch list returned", watchList);
assertEquals("Watchlist wrong size", 1, watchList.size());
// clean up again
tmdb.removeFromWatchList(tokenSession.getSessionId(), account.getId(), 550);
Assert.assertTrue(tmdb.getWatchList(tokenSession.getSessionId(), account.getId()).isEmpty());
}
@Test
public void testFavorites() throws MovieDbException {
// If the static account is null, get it
if (account == null) {
account = tmdb.getAccount(tokenSession.getSessionId());
}
// make sure it's empty (because it's just a test account
Assert.assertTrue(tmdb.getFavoriteMovies(tokenSession.getSessionId(), account.getId()).isEmpty());
// add a movie
tmdb.changeFavoriteStatus(tokenSession.getSessionId(), account.getId(), 550, true);
List<MovieDb> watchList = tmdb.getFavoriteMovies(tokenSession.getSessionId(), account.getId());
assertNotNull("Empty watch list returned", watchList);
assertEquals("Watchlist wrong size", 1, watchList.size());
// clean up again
tmdb.changeFavoriteStatus(tokenSession.getSessionId(), account.getId(), 550, false);
Assert.assertTrue(tmdb.getFavoriteMovies(tokenSession.getSessionId(), account.getId()).isEmpty());
}
/**
* Test of getSessionToken method, of class TheMovieDbApi.
*
* TODO: Cannot be tested without a HTTP authorisation:
* http://help.themoviedb.org/kb/api/user-authentication
*
* @throws MovieDbException
*/
@Ignore("Tested in setup")
public void testGetSessionToken() throws MovieDbException {
}
/**
* Test of getGuestSessionToken method, of class TheMovieDbApi.
*
* @throws MovieDbException
*/
@Test
public void testGetGuestSessionToken() throws MovieDbException {
LOG.info("getGuestSessionToken");
TokenSession result = tmdb.getGuestSessionToken();
assertTrue("Failed to get guest session", result.getSuccess());
}
/**
* Test of postMovieRating method, of class TheMovieDbApi.
*
* TODO: Cannot be tested without a HTTP authorisation:
* http://help.themoviedb.org/kb/api/user-authentication
*
* @throws MovieDbException
*/
@Test
public void testMovieRating() throws MovieDbException {
LOG.info("postMovieRating");
Integer movieID = 68724;
Integer rating = new Random().nextInt(10) + 1;
boolean wasPosted = tmdb.postMovieRating(tokenSession.getSessionId(), movieID, rating);
assertTrue("Rating was not added", wasPosted);
// get all rated movies
List<MovieDb> ratedMovies = tmdb.getRatedMovies(tokenSession.getSessionId(), account.getId());
assertTrue("No rated movies", ratedMovies.size() > 0);
// make sure that we find the movie and it is rated correctly
boolean foundMovie = false;
for (MovieDb movie : ratedMovies) {
if (movie.getId() == movieID) {
assertEquals("Incorrect movie rating", movie.getUserRating(), (float) rating, 0);
foundMovie = true;
}
}
assertTrue(foundMovie);
}
@Test
public void testMovieLists() throws MovieDbException {
Integer movieID = 68724;
// use a random name to avoid that we clash we leftovers of incomplete test runs
String name = "test list " + new Random().nextInt(100);
// create the list
String listId = tmdb.createList(tokenSession.getSessionId(), name, "api testing only");
// add a movie, and test that it is on the list now
tmdb.addMovieToList(tokenSession.getSessionId(), listId, movieID);
MovieDbList list = tmdb.getList(listId);
assertNotNull("Movie list returned was null", list);
assertEquals("Unexpected number of items returned", 1, list.getItemCount());
assertEquals((int) movieID, list.getItems().get(0).getId());
// now remove the movie
tmdb.removeMovieFromList(tokenSession.getSessionId(), listId, movieID);
assertEquals(tmdb.getList(listId).getItemCount(), 0);
// delete the test list
StatusCode statusCode = tmdb.deleteMovieList(tokenSession.getSessionId(), listId);
assertEquals(statusCode.getStatusCode(), 13);
}
}

@ -56,6 +56,7 @@ public class TestLogger {
config.append("java.util.logging.SimpleFormatter.format = [%1$tH:%1$tM:%1$tS %4$6s] %2$s - %5$s %6$s%n").append(CRLF);
// Exclude http logging
config.append("sun.net.www.protocol.http.HttpURLConnection.level = OFF").append(CRLF);
config.append("org.apache.http.level = SEVERE").append(CRLF);
InputStream ins = new ByteArrayInputStream(config.toString().getBytes());
try {

@ -19,7 +19,6 @@
*/
package com.omertron.themoviedbapi;
import com.omertron.themoviedbapi.model.Account;
import com.omertron.themoviedbapi.model.AlternativeTitle;
import com.omertron.themoviedbapi.model.Artwork;
import com.omertron.themoviedbapi.model.ChangedItem;
@ -39,7 +38,6 @@ import com.omertron.themoviedbapi.model.Person;
import com.omertron.themoviedbapi.model.PersonCredit;
import com.omertron.themoviedbapi.model.ReleaseInfo;
import com.omertron.themoviedbapi.model.Reviews;
import com.omertron.themoviedbapi.model.StatusCode;
import com.omertron.themoviedbapi.model.TmdbConfiguration;
import com.omertron.themoviedbapi.model.TokenAuthorisation;
import com.omertron.themoviedbapi.model.TokenSession;
@ -50,12 +48,9 @@ import com.omertron.themoviedbapi.results.TmdbResultsMap;
import java.io.File;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@ -80,8 +75,6 @@ public class TheMovieDbApiTest {
// API Key
private static final String PROP_FIlENAME = "testing.properties";
private static String API_KEY;
private static int ACCOUNT_ID_APITESTS;
private static String SESSION_ID_APITESTS;
private static TheMovieDbApi tmdb;
// Test data
private static final int ID_MOVIE_BLADE_RUNNER = 78;
@ -102,7 +95,7 @@ public class TheMovieDbApiTest {
}
@BeforeClass
public static void setUpClass() throws Exception {
public static void setUpClass() throws MovieDbException {
TestLogger.Configure();
Properties props = new Properties();
@ -112,14 +105,12 @@ public class TheMovieDbApiTest {
TestLogger.loadProperties(props, f);
API_KEY = props.getProperty("API_Key");
ACCOUNT_ID_APITESTS = NumberUtils.toInt(props.getProperty("Account_ID"), 0);
SESSION_ID_APITESTS = props.getProperty("Session_ID");
} else {
LOG.info("Property file '{}' not found, creating dummy file.", PROP_FIlENAME);
props.setProperty("API_Key", "INSERT_YOUR_KEY_HERE");
props.setProperty("Account_ID", "ACCOUNT ID FOR SESSION TESTS");
props.setProperty("Session_ID", "INSERT_YOUR_SESSION_ID_HERE");
props.setProperty("Username", "INSERT_YOUR_USERNAME_HERE");
props.setProperty("Password", "INSERT_YOUR_PASSWORD_HERE");
TestLogger.saveProperties(props, f, "Properties file for tests");
fail("Failed to get key information from properties file '" + PROP_FIlENAME + "'");
@ -129,7 +120,7 @@ public class TheMovieDbApiTest {
}
@AfterClass
public static void tearDownClass() throws Exception {
public static void tearDownClass() throws MovieDbException {
}
@Before
@ -156,52 +147,6 @@ public class TheMovieDbApiTest {
LOG.info(tmdbConfig.toString());
}
@Test
public void testAccount() throws MovieDbException {
LOG.info("Using Session ID '{}' for test", SESSION_ID_APITESTS);
Account account = tmdb.getAccount(SESSION_ID_APITESTS);
// Make sure properties are extracted correctly
assertEquals("apitests", account.getUserName());
assertEquals(ACCOUNT_ID_APITESTS, account.getId());
}
@Ignore("Session required")
public void testWatchList() throws MovieDbException {
// make sure it's empty (because it's just a test account
Assert.assertTrue(tmdb.getWatchList(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS).isEmpty());
// add a movie
tmdb.addToWatchList(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS, 550);
List<MovieDb> watchList = tmdb.getWatchList(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS);
assertNotNull("Empty watch list returned", watchList);
assertEquals("Watchlist wrong size", 1, watchList.size());
// clean up again
tmdb.removeFromWatchList(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS, 550);
Assert.assertTrue(tmdb.getWatchList(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS).isEmpty());
}
@Ignore("Session required")
public void testFavorites() throws MovieDbException {
// make sure it's empty (because it's just a test account
Assert.assertTrue(tmdb.getFavoriteMovies(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS).isEmpty());
// add a movie
tmdb.changeFavoriteStatus(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS, 550, true);
List<MovieDb> watchList = tmdb.getFavoriteMovies(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS);
assertNotNull("Empty watch list returned", watchList);
assertEquals("Watchlist wrong size", 1, watchList.size());
// clean up again
tmdb.changeFavoriteStatus(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS, 550, false);
Assert.assertTrue(tmdb.getFavoriteMovies(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS).isEmpty());
}
/**
* Test of searchMovie method, of class TheMovieDbApi.
*
@ -563,7 +508,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testGetUpcoming() throws Exception {
public void testGetUpcoming() throws MovieDbException {
LOG.info("getUpcoming");
TmdbResultsList<MovieDb> result = tmdb.getUpcoming(LANGUAGE_DEFAULT, 0);
assertTrue("No upcoming movies found", !result.getResults().isEmpty());
@ -575,7 +520,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testGetCollectionImages() throws Exception {
public void testGetCollectionImages() throws MovieDbException {
LOG.info("getCollectionImages");
TmdbResultsList<Artwork> result = tmdb.getCollectionImages(ID_COLLECTION_STAR_WARS, LANGUAGE_DEFAULT);
assertFalse("No artwork found", result.getResults().isEmpty());
@ -587,7 +532,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testGetAuthorisationToken() throws Exception {
public void testGetAuthorisationToken() throws MovieDbException {
LOG.info("getAuthorisationToken");
TokenAuthorisation result = tmdb.getAuthorisationToken();
assertFalse("Token is null", result == null);
@ -604,7 +549,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Ignore("Session required")
public void testGetSessionToken() throws Exception {
public void testGetSessionToken() throws MovieDbException {
LOG.info("getSessionToken");
TokenAuthorisation token = tmdb.getAuthorisationToken();
assertFalse("Token is null", token == null);
@ -623,14 +568,14 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Ignore("Not ready yet")
public void testGetGuestSessionToken() throws Exception {
public void testGetGuestSessionToken() throws MovieDbException {
LOG.info("getGuestSessionToken");
TokenSession result = tmdb.getGuestSessionToken();
assertTrue("Failed to get guest session", result.getSuccess());
}
public void testGetMovieLists() throws Exception {
public void testGetMovieLists() throws MovieDbException {
LOG.info("getMovieLists");
TmdbResultsList<MovieList> result = tmdb.getMovieLists(ID_MOVIE_BLADE_RUNNER, LANGUAGE_ENGLISH, 0);
assertNotNull("No results found", result);
@ -645,7 +590,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Ignore("Do not test this until it is fixed")
public void testGetMovieChanges() throws Exception {
public void testGetMovieChanges() throws MovieDbException {
LOG.info("getMovieChanges");
String startDate = "";
@ -662,7 +607,7 @@ public class TheMovieDbApiTest {
}
@Test
public void testGetPersonLatest() throws Exception {
public void testGetPersonLatest() throws MovieDbException {
LOG.info("getPersonLatest");
Person result = tmdb.getPersonLatest();
@ -677,7 +622,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testSearchCollection() throws Exception {
public void testSearchCollection() throws MovieDbException {
LOG.info("searchCollection");
String query = "batman";
int page = 0;
@ -692,7 +637,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testSearchList() throws Exception {
public void testSearchList() throws MovieDbException {
LOG.info("searchList");
String query = "watch";
int page = 0;
@ -707,7 +652,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testSearchKeyword() throws Exception {
public void testSearchKeyword() throws MovieDbException {
LOG.info("searchKeyword");
String query = "action";
int page = 0;
@ -716,73 +661,13 @@ public class TheMovieDbApiTest {
assertTrue("No keywords found", result.getResults().size() > 0);
}
/**
* Test of postMovieRating method, of class TheMovieDbApi.
*
* TODO: Cannot be tested without a HTTP authorisation:
* http://help.themoviedb.org/kb/api/user-authentication
*
* @throws MovieDbException
*/
@Ignore("Session required")
public void testMovieRating() throws Exception {
LOG.info("postMovieRating");
Integer movieID = 68724;
Integer rating = new Random().nextInt(10) + 1;
boolean wasPosted = tmdb.postMovieRating(SESSION_ID_APITESTS, movieID, rating);
assertNotNull(wasPosted);
assertTrue(wasPosted);
// get all rated movies
List<MovieDb> ratedMovies = tmdb.getRatedMovies(SESSION_ID_APITESTS, ACCOUNT_ID_APITESTS);
assertTrue(ratedMovies.size() > 0);
// make sure that we find the movie and it is rated correctly
boolean foundMovie = false;
for (MovieDb movie : ratedMovies) {
if (movie.getId() == movieID) {
assertEquals(movie.getUserRating(), (float) rating, 0);
foundMovie = true;
}
}
assertTrue(foundMovie);
}
@Ignore("Session required")
public void testMovieLists() throws Exception {
Integer movieID = 68724;
// use a random name to avoid that we clash we leftovers of incomplete test runs
String name = "test list " + new Random().nextInt(100);
// create the list
String listId = tmdb.createList(SESSION_ID_APITESTS, name, "api testing only");
// add a movie, and test that it is on the list now
tmdb.addMovieToList(SESSION_ID_APITESTS, listId, movieID);
MovieDbList list = tmdb.getList(listId);
assertNotNull("Movie list returned was null", list);
assertEquals("Unexpected number of items returned", 1, list.getItemCount());
assertEquals((int) movieID, list.getItems().get(0).getId());
// now remove the movie
tmdb.removeMovieFromList(SESSION_ID_APITESTS, listId, movieID);
assertEquals(tmdb.getList(listId).getItemCount(), 0);
// delete the test list
StatusCode statusCode = tmdb.deleteMovieList(SESSION_ID_APITESTS, listId);
assertEquals(statusCode.getStatusCode(), 13);
}
/**
* Test of getPersonChanges method, of class TheMovieDbApi.
*
* @throws MovieDbException
*/
@Ignore("Not ready yet")
public void testGetPersonChanges() throws Exception {
public void testGetPersonChanges() throws MovieDbException {
LOG.info("getPersonChanges");
String startDate = "";
String endDate = "";
@ -795,7 +680,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testGetList() throws Exception {
public void testGetList() throws MovieDbException {
LOG.info("getList");
String listId = "509ec17b19c2950a0600050d";
MovieDbList result = tmdb.getList(listId);
@ -808,7 +693,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testGetKeyword() throws Exception {
public void testGetKeyword() throws MovieDbException {
LOG.info("getKeyword");
Keyword result = tmdb.getKeyword(ID_KEYWORD);
assertEquals("fight", result.getName());
@ -820,7 +705,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testGetKeywordMovies() throws Exception {
public void testGetKeywordMovies() throws MovieDbException {
LOG.info("getKeywordMovies");
int page = 0;
TmdbResultsList<KeywordMovie> result = tmdb.getKeywordMovies(ID_KEYWORD, LANGUAGE_DEFAULT, page);
@ -833,7 +718,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testGetReviews() throws Exception {
public void testGetReviews() throws MovieDbException {
LOG.info("getReviews");
int page = 0;
TmdbResultsList<Reviews> result = tmdb.getReviews(ID_MOVIE_THE_AVENGERS, LANGUAGE_DEFAULT, page);
@ -841,68 +726,26 @@ public class TheMovieDbApiTest {
assertFalse("No reviews found", result.getResults().isEmpty());
}
/**
* Test of compareMovies method, of class TheMovieDbApi.
*
*/
@Ignore("Not required")
public void testCompareMovies_3args() {
}
/**
* Test of compareMovies method, of class TheMovieDbApi.
*
*/
@Ignore("Not required")
public void testCompareMovies_4args() {
}
/**
* Test of getPersonPopular method, of class TheMovieDbApi.
*
*/
@Ignore("Not required")
public void testGetPersonPopular_0args() {
}
/**
* Test of getPersonPopular method, of class TheMovieDbApi.
*
* @throws MovieDbException
*/
@Test
public void testGetPersonPopular_int() throws Exception {
public void testGetPersonPopular_int() throws MovieDbException {
LOG.info("getPersonPopular");
int page = 0;
TmdbResultsList<Person> result = tmdb.getPersonPopular(page);
assertFalse("No popular people", result.getResults().isEmpty());
}
/**
* Test of getGenreMovies method, of class TheMovieDbApi.
*
* @throws MovieDbException
*/
@Ignore("Not required")
public void testGetGenreMovies_3args() throws Exception {
}
/**
* Test of getGenreMovies method, of class TheMovieDbApi.
*
* @throws MovieDbException
*/
@Ignore("Not required")
public void testGetGenreMovies_4args() throws Exception {
}
/**
* Test of getMovieChangesList method, of class TheMovieDbApi.
*
* @throws MovieDbException
*/
@Test
public void testGetMovieChangesList() throws Exception {
public void testGetMovieChangesList() throws MovieDbException {
LOG.info("getMovieChangesList");
int page = 0;
String startDate = "";
@ -917,7 +760,7 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Ignore("Not ready yet")
public void testGetPersonChangesList() throws Exception {
public void testGetPersonChangesList() throws MovieDbException {
LOG.info("getPersonChangesList");
int page = 0;
String startDate = "";
@ -933,28 +776,19 @@ public class TheMovieDbApiTest {
* @throws MovieDbException
*/
@Test
public void testGetJobs() throws Exception {
public void testGetJobs() throws MovieDbException {
LOG.info("getJobs");
TmdbResultsList<JobDepartment> result = tmdb.getJobs();
assertFalse("No jobs found", result.getResults().isEmpty());
}
/**
* Test of getDiscover method, of class TheMovieDbApi.
*
* @throws MovieDbException
*/
@Ignore("Not required")
public void testGetDiscover_14args() throws Exception {
}
/**
* Test of getDiscover method, of class TheMovieDbApi.
*
* @throws MovieDbException
*/
@Test
public void testGetDiscover_Discover() throws Exception {
public void testGetDiscover_Discover() throws MovieDbException {
LOG.info("getDiscover");
Discover discover = new Discover();
discover.year(2013).language(LANGUAGE_ENGLISH);

Loading…
Cancel
Save