Add HttpTools class

Add POST and DELETE commands
master
Stuart Boston 11 years ago
parent ba0c8bc564
commit 6eda79830e

@ -120,7 +120,7 @@
<dependency>
<groupId>org.yamj</groupId>
<artifactId>api-common</artifactId>
<version>1.3</version>
<version>1.4-SNAPSHOT</version>
</dependency>
</dependencies>

@ -66,7 +66,7 @@ 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_YEAR;
import com.omertron.themoviedbapi.tools.WebBrowser;
import com.omertron.themoviedbapi.tools.HttpTools;
import com.omertron.themoviedbapi.wrapper.WrapperAlternativeTitles;
import com.omertron.themoviedbapi.wrapper.WrapperChanges;
import com.omertron.themoviedbapi.wrapper.WrapperCollection;
@ -93,21 +93,16 @@ import com.omertron.themoviedbapi.wrapper.WrapperTranslations;
import com.omertron.themoviedbapi.wrapper.WrapperVideos;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamj.api.common.exception.ApiExceptionType;
import org.yamj.api.common.http.DigestedResponse;
import org.yamj.api.common.http.DigestedResponseReader;
import org.yamj.api.common.http.SimpleHttpClientBuilder;
/**
@ -122,10 +117,8 @@ public class TheMovieDbApi {
private static final Logger LOG = LoggerFactory.getLogger(TheMovieDbApi.class);
private String apiKey;
private CloseableHttpClient httpClient;
private TmdbConfiguration tmdbConfig;
private static final String DEFAULT_CHARSET = "UTF-8";
private final Charset charset = Charset.forName(DEFAULT_CHARSET);
private HttpTools httpTools;
// API Methods
private static final String BASE_MOVIE = "movie/";
private static final String BASE_PERSON = "person/";
@ -148,8 +141,6 @@ public class TheMovieDbApi {
private static final int YEAR_LENGTH = 4;
private static final int RATING_MAX = 10;
private static final int POST_SUCCESS_STATUS_CODE = 12;
private static final int HTTP_STATUS_300 = 300;
private static final int HTTP_STATUS_500 = 500;
/**
* API for The Movie Db.
@ -170,11 +161,11 @@ public class TheMovieDbApi {
*/
public TheMovieDbApi(String apiKey, CloseableHttpClient httpClient) throws MovieDbException {
this.apiKey = apiKey;
this.httpClient = httpClient;
this.httpTools = new HttpTools(httpClient);
ApiUrl apiUrl = new ApiUrl(apiKey, "configuration");
URL configUrl = apiUrl.buildUrl();
String webpage = requestWebPage(configUrl);
String webpage = httpTools.getRequest(configUrl);
try {
WrapperConfig wc = mapper.readValue(webpage, WrapperConfig.class);
@ -193,56 +184,6 @@ public class TheMovieDbApi {
return apiKey;
}
private String requestWebPage(URL url) throws MovieDbException {
return requestWebPage(url, null, Boolean.FALSE);
}
private String requestWebPage(URL url, String jsonBody) throws MovieDbException {
return requestWebPage(url, jsonBody, Boolean.FALSE);
}
private String requestWebPage(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException {
String webpage;
// use HTTP client implementation
if (httpClient == null) {
// use web browser
webpage = WebBrowser.request(url, jsonBody, isDeleteRequest);
} else {
try {
HttpGet httpGet = new HttpGet(url.toURI());
httpGet.addHeader("accept", "application/json");
if (StringUtils.isNotBlank(jsonBody)) {
// TODO: Add the json body to the request
throw new MovieDbException(ApiExceptionType.UNKNOWN_CAUSE, "Unable to proces JSON request", url);
}
if (isDeleteRequest) {
//TODO: Handle delete request
throw new MovieDbException(ApiExceptionType.UNKNOWN_CAUSE, "Unable to proces delete request", url);
}
final DigestedResponse response = DigestedResponseReader.requestContent(httpClient, httpGet, charset);
if (response.getStatusCode() >= HTTP_STATUS_500) {
throw new MovieDbException(ApiExceptionType.HTTP_503_ERROR, response.getContent(), response.getStatusCode(), url, null);
} else if (response.getStatusCode() >= HTTP_STATUS_300) {
throw new MovieDbException(ApiExceptionType.HTTP_404_ERROR, response.getContent(), response.getStatusCode(), url, null);
}
webpage = response.getContent();
} catch (URISyntaxException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
} catch (RuntimeException ex) {
throw new MovieDbException(ApiExceptionType.HTTP_503_ERROR, "Service Unavailable", url, ex);
}
}
return webpage;
}
/**
* Compare the MovieDB object with a title & year
*
@ -396,7 +337,7 @@ public class TheMovieDbApi {
ApiUrl apiUrl = new ApiUrl(apiKey, BASE_AUTH, "token/new");
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, TokenAuthorisation.class);
@ -426,7 +367,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_TOKEN, token.getRequestToken());
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, TokenSession.class);
@ -459,7 +400,7 @@ public class TheMovieDbApi {
ApiUrl apiUrl = new ApiUrl(apiKey, BASE_AUTH, "guest_session/new");
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, TokenSession.class);
@ -483,7 +424,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_SESSION, sessionId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, Account.class);
@ -498,7 +439,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_SESSION, sessionId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, WrapperMovie.class).getMovies();
@ -519,7 +460,7 @@ public class TheMovieDbApi {
String jsonBody = convertToJson(body);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url, jsonBody);
String webpage = httpTools.postRequest(url, jsonBody);
try {
return mapper.readValue(webpage, StatusCode.class);
@ -566,7 +507,7 @@ public class TheMovieDbApi {
String jsonBody = convertToJson(body);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url, jsonBody);
String webpage = httpTools.postRequest(url, jsonBody);
try {
return mapper.readValue(webpage, StatusCode.class);
@ -604,7 +545,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
MovieDb movie = mapper.readValue(webpage, MovieDb.class);
if (movie == null || movie.getId() == 0) {
@ -644,7 +585,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
MovieDb movie = mapper.readValue(webpage, MovieDb.class);
if (movie == null || movie.getId() == 0) {
@ -679,7 +620,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperAlternativeTitles wrapper = mapper.readValue(webpage, WrapperAlternativeTitles.class);
TmdbResultsList<AlternativeTitle> results = new TmdbResultsList<AlternativeTitle>(wrapper.getTitles());
@ -708,7 +649,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovieCasts wrapper = mapper.readValue(webpage, WrapperMovieCasts.class);
@ -742,7 +683,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperImages wrapper = mapper.readValue(webpage, WrapperImages.class);
@ -773,7 +714,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovieKeywords wrapper = mapper.readValue(webpage, WrapperMovieKeywords.class);
@ -804,7 +745,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperReleaseInfo wrapper = mapper.readValue(webpage, WrapperReleaseInfo.class);
@ -840,11 +781,11 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperVideos wrapper = mapper.readValue(webpage, WrapperVideos.class);
TmdbResultsList<Video> results = new TmdbResultsList<Video>(wrapper.getTrailers());
TmdbResultsList<Video> results = new TmdbResultsList<Video>(wrapper.getVideos());
results.copyWrapper(wrapper);
return results;
} catch (IOException ex) {
@ -869,7 +810,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperTranslations wrapper = mapper.readValue(webpage, WrapperTranslations.class);
@ -913,7 +854,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovie wrapper = mapper.readValue(webpage, WrapperMovie.class);
@ -941,7 +882,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperReviews wrapper = mapper.readValue(webpage, WrapperReviews.class);
@ -979,7 +920,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovieList wrapper = mapper.readValue(webpage, WrapperMovieList.class);
@ -1026,7 +967,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperChanges wrapper = mapper.readValue(webpage, WrapperChanges.class);
@ -1052,7 +993,7 @@ public class TheMovieDbApi {
public MovieDb getLatestMovie() throws MovieDbException {
ApiUrl apiUrl = new ApiUrl(apiKey, BASE_MOVIE, "/latest");
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, MovieDb.class);
@ -1086,7 +1027,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovie wrapper = mapper.readValue(webpage, WrapperMovie.class);
@ -1125,7 +1066,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovie wrapper = mapper.readValue(webpage, WrapperMovie.class);
@ -1162,7 +1103,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovie wrapper = mapper.readValue(webpage, WrapperMovie.class);
@ -1200,7 +1141,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovie wrapper = mapper.readValue(webpage, WrapperMovie.class);
@ -1226,7 +1167,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_SESSION, sessionId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, WrapperMovie.class).getMovies();
@ -1259,7 +1200,7 @@ public class TheMovieDbApi {
String jsonBody = convertToJson(Collections.singletonMap("value", rating));
LOG.info("Body: {}", jsonBody);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url, jsonBody);
String webpage = httpTools.postRequest(url, jsonBody);
try {
StatusCode status = mapper.readValue(webpage, StatusCode.class);
@ -1295,7 +1236,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, CollectionInfo.class);
@ -1322,7 +1263,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperImages wrapper = mapper.readValue(webpage, WrapperImages.class);
@ -1354,7 +1295,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, Person.class);
@ -1382,7 +1323,7 @@ public class TheMovieDbApi {
apiUrl.appendToResponse(appendToResponse);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperPersonCredits wrapper = mapper.readValue(webpage, WrapperPersonCredits.class);
@ -1408,7 +1349,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_ID, personId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperImages wrapper = mapper.readValue(webpage, WrapperImages.class);
@ -1472,7 +1413,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperPersonList wrapper = mapper.readValue(webpage, WrapperPersonList.class);
@ -1494,7 +1435,7 @@ public class TheMovieDbApi {
public Person getPersonLatest() throws MovieDbException {
ApiUrl apiUrl = new ApiUrl(apiKey, BASE_PERSON, "/latest");
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, Person.class);
@ -1520,7 +1461,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_ID, companyId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, Company.class);
@ -1558,7 +1499,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperCompanyMovies wrapper = mapper.readValue(webpage, WrapperCompanyMovies.class);
@ -1587,7 +1528,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_LANGUAGE, language);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperGenres wrapper = mapper.readValue(webpage, WrapperGenres.class);
@ -1631,7 +1572,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_INCLUDE_ALL_MOVIES, includeAllMovies);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovie wrapper = mapper.readValue(webpage, WrapperMovie.class);
@ -1682,7 +1623,7 @@ public class TheMovieDbApi {
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovie wrapper = mapper.readValue(webpage, WrapperMovie.class);
TmdbResultsList<MovieDb> results = new TmdbResultsList<MovieDb>(wrapper.getMovies());
@ -1721,7 +1662,7 @@ public class TheMovieDbApi {
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperCollection wrapper = mapper.readValue(webpage, WrapperCollection.class);
TmdbResultsList<Collection> results = new TmdbResultsList<Collection>(wrapper.getResults());
@ -1755,7 +1696,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperPerson wrapper = mapper.readValue(webpage, WrapperPerson.class);
@ -1794,7 +1735,7 @@ public class TheMovieDbApi {
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovieList wrapper = mapper.readValue(webpage, WrapperMovieList.class);
TmdbResultsList<MovieList> results = new TmdbResultsList<MovieList>(wrapper.getMovieList());
@ -1828,7 +1769,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperCompany wrapper = mapper.readValue(webpage, WrapperCompany.class);
TmdbResultsList<Company> results = new TmdbResultsList<Company>(wrapper.getResults());
@ -1861,7 +1802,7 @@ public class TheMovieDbApi {
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperKeywords wrapper = mapper.readValue(webpage, WrapperKeywords.class);
TmdbResultsList<Keyword> results = new TmdbResultsList<Keyword>(wrapper.getResults());
@ -1887,7 +1828,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_ID, listId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, MovieDbList.class);
@ -1910,7 +1851,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_SESSION, sessionId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, WrapperMovieDbList.class).getLists();
@ -1940,7 +1881,7 @@ public class TheMovieDbApi {
String jsonBody = convertToJson(body);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url, jsonBody);
String webpage = httpTools.postRequest(url, jsonBody);
try {
return mapper.readValue(webpage, MovieDbListStatus.class).getListId();
@ -1963,7 +1904,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(MOVIE_ID, movieId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, ListItemStatus.class).isItemPresent();
@ -2009,7 +1950,7 @@ public class TheMovieDbApi {
String jsonBody = convertToJson(Collections.singletonMap("media_id", movieId + ""));
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url, jsonBody);
String webpage = httpTools.postRequest(url, jsonBody);
try {
return mapper.readValue(webpage, StatusCode.class);
@ -2032,7 +1973,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_SESSION, sessionId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, WrapperMovie.class).getMovies();
@ -2057,7 +1998,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_SESSION, sessionId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url, null, true);
String webpage = httpTools.deleteRequest(url);
try {
return mapper.readValue(webpage, StatusCode.class);
@ -2081,7 +2022,7 @@ public class TheMovieDbApi {
apiUrl.addArgument(PARAM_ID, keywordId);
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
return mapper.readValue(webpage, Keyword.class);
@ -2114,7 +2055,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperKeywordMovies wrapper = mapper.readValue(webpage, WrapperKeywordMovies.class);
@ -2160,7 +2101,7 @@ public class TheMovieDbApi {
}
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovieChanges wrapper = mapper.readValue(webpage, WrapperMovieChanges.class);
@ -2184,7 +2125,7 @@ public class TheMovieDbApi {
ApiUrl apiUrl = new ApiUrl(apiKey, BASE_JOB, "/list");
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperJobList wrapper = mapper.readValue(webpage, WrapperJobList.class);
@ -2276,7 +2217,7 @@ public class TheMovieDbApi {
apiUrl.setArguments(discover.getParams());
URL url = apiUrl.buildUrl();
String webpage = requestWebPage(url);
String webpage = httpTools.getRequest(url);
try {
WrapperMovie wrapper = mapper.readValue(webpage, WrapperMovie.class);

@ -20,12 +20,20 @@
package com.omertron.themoviedbapi.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.omertron.themoviedbapi.wrapper.*;
import com.omertron.themoviedbapi.wrapper.WrapperAlternativeTitles;
import com.omertron.themoviedbapi.wrapper.WrapperImages;
import com.omertron.themoviedbapi.wrapper.WrapperMovie;
import com.omertron.themoviedbapi.wrapper.WrapperMovieCasts;
import com.omertron.themoviedbapi.wrapper.WrapperMovieKeywords;
import com.omertron.themoviedbapi.wrapper.WrapperMovieList;
import com.omertron.themoviedbapi.wrapper.WrapperReleaseInfo;
import com.omertron.themoviedbapi.wrapper.WrapperReviews;
import com.omertron.themoviedbapi.wrapper.WrapperTranslations;
import com.omertron.themoviedbapi.wrapper.WrapperVideos;
import java.util.List;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.util.List;
/**
* Movie Bean
*
@ -345,8 +353,8 @@ public class MovieDb extends AbstractJsonMapping {
return releases.getCountries();
}
public List<Video> getTrailers() {
return trailers.getTrailers();
public List<Video> getVideos() {
return trailers.getVideos();
}
public List<Translation> getTranslations() {

@ -0,0 +1,115 @@
package com.omertron.themoviedbapi.tools;
import com.omertron.themoviedbapi.MovieDbException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.protocol.HTTP;
import org.yamj.api.common.exception.ApiExceptionType;
import org.yamj.api.common.http.DigestedResponse;
import org.yamj.api.common.http.DigestedResponseReader;
/**
* HTTP tools to aid in processing web requests
*
* @author Stuart.Boston
*/
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;
public HttpTools(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
}
/**
* GET data from the URL
*
* @param url URL to use in the request
* @return String content
* @throws MovieDbException
*/
public String getRequest(final URL url) throws MovieDbException {
try {
HttpGet httpGet = new HttpGet(url.toURI());
httpGet.addHeader("accept", "application/json");
return validateResponse(DigestedResponseReader.requestContent(httpClient, httpGet, CHARSET), url);
} catch (URISyntaxException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
} catch (RuntimeException ex) {
throw new MovieDbException(ApiExceptionType.HTTP_503_ERROR, "Service Unavailable", url, ex);
}
}
/**
* Execute a DELETE on the URL
*
* @param url URL to use in the request
* @return String content
* @throws MovieDbException
*/
public String deleteRequest(final URL url) throws MovieDbException {
try {
HttpDelete httpDel = new HttpDelete(url.toURI());
return validateResponse(DigestedResponseReader.deleteContent(httpClient, httpDel, CHARSET), url);
} catch (URISyntaxException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
}
}
/**
* POST content to the URL with the specified body
*
* @param url URL to use in the request
* @param jsonBody Body to use in the request
* @return String content
* @throws MovieDbException
*/
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");
StringEntity params = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
httpPost.setEntity(params);
return validateResponse(DigestedResponseReader.postContent(httpClient, httpPost, CHARSET), url);
} catch (URISyntaxException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
}
}
/**
* Check the status codes of the response and throw exceptions if needed
*
* @param response DigestedResponse to process
* @param url URL for notification purposes
* @return String content
* @throws MovieDbException
*/
private String validateResponse(final DigestedResponse response, final URL url) throws MovieDbException {
if (response.getStatusCode() >= HTTP_STATUS_500) {
throw new MovieDbException(ApiExceptionType.HTTP_503_ERROR, response.getContent(), response.getStatusCode(), url, null);
} else if (response.getStatusCode() >= HTTP_STATUS_300) {
throw new MovieDbException(ApiExceptionType.HTTP_404_ERROR, response.getContent(), response.getStatusCode(), url, null);
}
return response.getContent();
}
}

@ -1,335 +0,0 @@
/*
* 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.MovieDbException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamj.api.common.exception.ApiExceptionType;
/**
* Web browser with simple cookies support
*/
public final class WebBrowser {
private static final Logger LOG = LoggerFactory.getLogger(WebBrowser.class);
private static final Map<String, String> BROWSER_PROPERTIES = new HashMap<String, String>();
private static final Map<String, Map<String, String>> COOKIES = new HashMap<String, Map<String, String>>();
private static String proxyHost = null;
private static int proxyPort = 0;
private static String proxyUsername = null;
private static String proxyPassword = null;
private static String proxyEncodedPassword = null;
// 25 second timeout
private static int webTimeoutConnect = 25000;
// 90 second timeout
private static int webTimeoutRead = 90000;
// Hide the constructor
protected WebBrowser() {
// prevents calls from subclass
throw new UnsupportedOperationException();
}
/**
* Populate the browser properties
*/
private static void populateBrowserProperties() {
if (BROWSER_PROPERTIES.isEmpty()) {
BROWSER_PROPERTIES.put(HTTP.USER_AGENT, "Mozilla/5.25 Netscape/5.0 (Windows; I; Win95)");
BROWSER_PROPERTIES.put("Accept", "application/json");
BROWSER_PROPERTIES.put(HTTP.CONTENT_TYPE, "application/json");
}
}
public static String request(String url) throws MovieDbException {
try {
return request(new URL(url));
} catch (MalformedURLException ex) {
throw new MovieDbException(ApiExceptionType.INVALID_URL, null, url, ex);
}
}
public static URLConnection openProxiedConnection(URL url) throws MovieDbException {
try {
if (proxyHost != null) {
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", proxyHost);
System.getProperties().put("proxyPort", proxyPort);
}
URLConnection cnx = url.openConnection();
if (proxyUsername != null) {
cnx.setRequestProperty("Proxy-Authorization", proxyEncodedPassword);
}
return cnx;
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.INVALID_URL, null, url, ex);
}
}
public static String request(URL url) throws MovieDbException {
return request(url, null, Boolean.FALSE);
}
public static String request(URL url, String jsonBody) throws MovieDbException {
return request(url, jsonBody, Boolean.FALSE);
}
public static String request(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException {
StringWriter content = null;
try {
content = new StringWriter();
BufferedReader in = null;
HttpURLConnection cnx = null;
OutputStreamWriter wr = null;
try {
cnx = (HttpURLConnection) openProxiedConnection(url);
// If we get a null connection, then throw an exception
if (cnx == null) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, "No HTTP connection could be made.", url);
}
if (isDeleteRequest) {
cnx.setDoOutput(true);
cnx.setRequestProperty(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
cnx.setRequestMethod("DELETE");
}
sendHeader(cnx);
if (StringUtils.isNotBlank(jsonBody)) {
cnx.setDoOutput(true);
wr = new OutputStreamWriter(cnx.getOutputStream());
wr.write(jsonBody);
}
readHeader(cnx);
// http://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error
if (cnx.getResponseCode() >= 400) {
in = new BufferedReader(new InputStreamReader(cnx.getErrorStream(), getCharset(cnx)));
} else {
in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx)));
}
String line;
while ((line = in.readLine()) != null) {
content.write(line);
}
} finally {
if (wr != null) {
wr.flush();
wr.close();
}
if (in != null) {
in.close();
}
if (cnx instanceof HttpURLConnection) {
((HttpURLConnection) cnx).disconnect();
}
}
return content.toString();
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
} finally {
if (content != null) {
try {
content.close();
} catch (IOException ex) {
LOG.debug("Failed to close connection: {}", ex.getMessage());
}
}
}
}
private static void sendHeader(URLConnection cnx) {
populateBrowserProperties();
// send browser properties
for (Map.Entry<String, String> browserProperty : BROWSER_PROPERTIES.entrySet()) {
cnx.setRequestProperty(browserProperty.getKey(), browserProperty.getValue());
}
// send cookies
String cookieHeader = createCookieHeader(cnx);
if (!cookieHeader.isEmpty()) {
cnx.setRequestProperty("Cookie", cookieHeader);
}
}
private static String createCookieHeader(URLConnection cnx) {
String host = cnx.getURL().getHost();
StringBuilder cookiesHeader = new StringBuilder();
for (Map.Entry<String, Map<String, String>> domainCookies : COOKIES.entrySet()) {
if (host.endsWith(domainCookies.getKey())) {
for (Map.Entry<String, String> cookie : domainCookies.getValue().entrySet()) {
cookiesHeader.append(cookie.getKey());
cookiesHeader.append("=");
cookiesHeader.append(cookie.getValue());
cookiesHeader.append(";");
}
}
}
if (cookiesHeader.length() > 0) {
// remove last ; char
cookiesHeader.deleteCharAt(cookiesHeader.length() - 1);
}
return cookiesHeader.toString();
}
private static void readHeader(URLConnection cnx) {
// read new cookies and update our cookies
for (Map.Entry<String, List<String>> header : cnx.getHeaderFields().entrySet()) {
if ("Set-Cookie".equals(header.getKey())) {
for (String cookieHeader : header.getValue()) {
String[] cookieElements = cookieHeader.split(" *; *");
if (cookieElements.length >= 1) {
String[] firstElem = cookieElements[0].split(" *= *");
String cookieName = firstElem[0];
String cookieValue = firstElem.length > 1 ? firstElem[1] : null;
String cookieDomain = null;
// find cookie domain
for (int i = 1; i < cookieElements.length; i++) {
String[] cookieElement = cookieElements[i].split(" *= *");
if ("domain".equals(cookieElement[0])) {
cookieDomain = cookieElement.length > 1 ? cookieElement[1] : null;
break;
}
}
if (cookieDomain == null) {
// if domain isn't set take current host
cookieDomain = cnx.getURL().getHost();
}
Map<String, String> domainCookies = COOKIES.get(cookieDomain);
if (domainCookies == null) {
domainCookies = new HashMap<String, String>();
COOKIES.put(cookieDomain, domainCookies);
}
// add or replace cookie
domainCookies.put(cookieName, cookieValue);
}
}
}
}
}
private static Charset getCharset(URLConnection cnx) {
Charset charset = null;
// content type will be string like "text/html; charset=UTF-8" or "text/html"
String contentType = cnx.getContentType();
if (contentType != null) {
// changed 'charset' to 'harset' in regexp because some sites send 'Charset'
Matcher m = Pattern.compile("harset *=[ '\"]*([^ ;'\"]+)[ ;'\"]*").matcher(contentType);
if (m.find()) {
String encoding = m.group(1);
try {
charset = Charset.forName(encoding);
} catch (UnsupportedCharsetException e) {
// there will be used default charset
}
}
}
if (charset == null) {
charset = Charset.defaultCharset();
}
return charset;
}
public static String getProxyHost() {
return proxyHost;
}
public static void setProxyHost(String myProxyHost) {
WebBrowser.proxyHost = myProxyHost;
}
public static int getProxyPort() {
return proxyPort;
}
public static void setProxyPort(int myProxyPort) {
WebBrowser.proxyPort = myProxyPort;
}
public static String getProxyUsername() {
return proxyUsername;
}
public static void setProxyUsername(String myProxyUsername) {
WebBrowser.proxyUsername = myProxyUsername;
}
public static String getProxyPassword() {
return proxyPassword;
}
public static void setProxyPassword(String myProxyPassword) {
WebBrowser.proxyPassword = myProxyPassword;
if (proxyUsername != null) {
proxyEncodedPassword = proxyUsername + ":" + proxyPassword;
proxyEncodedPassword = "Basic " + new String(Base64.encodeBase64((proxyUsername + ":" + proxyPassword).getBytes()));
}
}
public static int getWebTimeoutConnect() {
return webTimeoutConnect;
}
public static int getWebTimeoutRead() {
return webTimeoutRead;
}
public static void setWebTimeoutConnect(int webTimeoutConnect) {
WebBrowser.webTimeoutConnect = webTimeoutConnect;
}
public static void setWebTimeoutRead(int webTimeoutRead) {
WebBrowser.webTimeoutRead = webTimeoutRead;
}
}

@ -22,7 +22,6 @@ package com.omertron.themoviedbapi.wrapper;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.omertron.themoviedbapi.model.Trailer;
import com.omertron.themoviedbapi.model.Video;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@ -36,38 +35,34 @@ public class WrapperVideos extends AbstractWrapperId implements Serializable {
private static final long serialVersionUID = 1L;
private List<Video> videos = null;
public List<Video> getTrailers() {
public List<Video> getVideos() {
return videos;
}
@JsonSetter("results")
public void setTrailers(List<Video> trailers) {
this.videos = trailers;
public void setVideos(List<Video> videos) {
this.videos = videos;
}
@JsonSetter("quicktime")
public void setQuickTime(List<Trailer> trailers) {
if (trailers == null) {
if (this.videos == null) {
this.videos = new ArrayList<Video>();
}
for (Trailer t : trailers) {
System.out.println(t.toString());
System.out.println(convertTrailer(t, "quicktime"));
videos.add(convertTrailer(t, "quicktime"));
}
}
@JsonSetter("youtube")
public void setYouTube(List<Trailer> trailers) {
if (trailers == null) {
if (this.videos == null) {
this.videos = new ArrayList<Video>();
}
for (Trailer t : trailers) {
System.out.println(t.toString());
Video v = convertTrailer(t, "youtube");
System.out.println(v.toString());
videos.add(v);
videos.add(convertTrailer(t, "youtube"));
}
}

@ -19,21 +19,54 @@
*/
package com.omertron.themoviedbapi;
import com.omertron.themoviedbapi.model.*;
import com.omertron.themoviedbapi.model.Account;
import com.omertron.themoviedbapi.model.AlternativeTitle;
import com.omertron.themoviedbapi.model.Artwork;
import com.omertron.themoviedbapi.model.ChangedItem;
import com.omertron.themoviedbapi.model.ChangedMovie;
import com.omertron.themoviedbapi.model.Collection;
import com.omertron.themoviedbapi.model.CollectionInfo;
import com.omertron.themoviedbapi.model.Company;
import com.omertron.themoviedbapi.model.Discover;
import com.omertron.themoviedbapi.model.Genre;
import com.omertron.themoviedbapi.model.JobDepartment;
import com.omertron.themoviedbapi.model.Keyword;
import com.omertron.themoviedbapi.model.KeywordMovie;
import com.omertron.themoviedbapi.model.MovieDb;
import com.omertron.themoviedbapi.model.MovieDbList;
import com.omertron.themoviedbapi.model.MovieList;
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;
import com.omertron.themoviedbapi.model.Translation;
import com.omertron.themoviedbapi.model.Video;
import com.omertron.themoviedbapi.results.TmdbResultsList;
import com.omertron.themoviedbapi.results.TmdbResultsMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import static org.junit.Assert.*;
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;
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;
/**
* Test cases for TheMovieDbApi API
@ -296,7 +329,7 @@ public class TheMovieDbApiTest {
@Test
public void testGetMovieTrailers() throws MovieDbException {
LOG.info("getMovieTrailers");
TmdbResultsList<Trailer> result = tmdb.getMovieTrailers(ID_MOVIE_BLADE_RUNNER, "");
TmdbResultsList<Video> result = tmdb.getMovieTrailers(ID_MOVIE_BLADE_RUNNER, "");
assertFalse("Movie trailers missing", result.getResults().isEmpty());
}
@ -619,7 +652,8 @@ public class TheMovieDbApiTest {
/**
* Test of getSessionToken method, of class TheMovieDbApi.
*
* TODO: Cannot be tested without a HTTP authorisation: http://help.themoviedb.org/kb/api/user-authentication
* TODO: Cannot be tested without a HTTP authorisation:
* http://help.themoviedb.org/kb/api/user-authentication
*
* @throws MovieDbException
*/
@ -650,7 +684,6 @@ public class TheMovieDbApiTest {
assertTrue("Failed to get guest session", result.getSuccess());
}
@Test
public void testGetMovieLists() throws Exception {
LOG.info("getMovieLists");
TmdbResultsList<MovieList> result = tmdb.getMovieLists(ID_MOVIE_BLADE_RUNNER, LANGUAGE_ENGLISH, 0);
@ -740,7 +773,8 @@ public class TheMovieDbApiTest {
/**
* Test of postMovieRating method, of class TheMovieDbApi.
*
* TODO: Cannot be tested without a HTTP authorisation: http://help.themoviedb.org/kb/api/user-authentication
* TODO: Cannot be tested without a HTTP authorisation:
* http://help.themoviedb.org/kb/api/user-authentication
*
* @throws MovieDbException
*/

Loading…
Cancel
Save