Source code cleanup

master
Omertron 14 years ago
parent 44b962a60d
commit d0ca6931ec

@ -15,12 +15,12 @@
<system>Google Code</system> <system>Google Code</system>
<url>http://code.google.com/p/themoviedbapi/issues/list</url> <url>http://code.google.com/p/themoviedbapi/issues/list</url>
</issueManagement> </issueManagement>
<ciManagement> <ciManagement>
<system>Hudson CI</system> <system>Hudson CI</system>
<url>http://jenkins.omertron.com/job/API-TheMovieDb/</url> <url>http://jenkins.omertron.com/job/API-TheMovieDb/</url>
</ciManagement> </ciManagement>
<scm> <scm>
<connection>scm:svn:http://themoviedbapi.googlecode.com/svn/trunk/themoviedbapi</connection> <connection>scm:svn:http://themoviedbapi.googlecode.com/svn/trunk/themoviedbapi</connection>
<developerConnection>scm:svn:https://themoviedbapi.googlecode.com/svn/trunk/themoviedbapi</developerConnection> <developerConnection>scm:svn:https://themoviedbapi.googlecode.com/svn/trunk/themoviedbapi</developerConnection>
@ -39,8 +39,13 @@
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
</dependency> </dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
</dependencies> </dependencies>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>

@ -1,14 +1,14 @@
/* /*
* Copyright (c) 2004-2011 YAMJ Members * Copyright (c) 2004-2011 YAMJ Members
* http://code.google.com/p/moviejukebox/people/list * http://code.google.com/p/moviejukebox/people/list
* *
* Web: http://code.google.com/p/moviejukebox/ * Web: http://code.google.com/p/moviejukebox/
* *
* This software is licensed under a Creative Commons License * This software is licensed under a Creative Commons License
* See this page: http://code.google.com/p/moviejukebox/wiki/License * See this page: http://code.google.com/p/moviejukebox/wiki/License
* *
* For any reuse or distribution, you must make clear to others the * For any reuse or distribution, you must make clear to others the
* license terms of this work. * license terms of this work.
*/ */
package com.moviejukebox.themoviedb; package com.moviejukebox.themoviedb;
@ -36,7 +36,7 @@ import com.moviejukebox.themoviedb.tools.WebBrowser;
* This is the main class for the API to connect to TheMovieDb.org. * This is the main class for the API to connect to TheMovieDb.org.
* The implementation is for v2.1 of the API as detailed here: * The implementation is for v2.1 of the API as detailed here:
* http://api.themoviedb.org/2.1 * http://api.themoviedb.org/2.1
* *
* @author Stuart.Boston * @author Stuart.Boston
* @version 1.3 * @version 1.3
*/ */
@ -47,7 +47,56 @@ public class TheMovieDb {
private static ConsoleHandler tmdbConsoleHandler = new ConsoleHandler(); private static ConsoleHandler tmdbConsoleHandler = new ConsoleHandler();
private static final String API_SITE = "http://api.themoviedb.org/2.1/"; private static final String API_SITE = "http://api.themoviedb.org/2.1/";
private static final String DEFAULT_LANGUAGE = "en-US"; private static final String DEFAULT_LANGUAGE = "en-US";
/**
* Constructor with default logger.
* @param apiKey
*/
public TheMovieDb(String apiKey) {
setLogger(Logger.getLogger("TheMovieDB"));
if (!isValidString(apiKey)) {
logger.severe("TheMovieDb was initialized with a wrong API key!");
}
setApiKey(apiKey);
}
/*
* API Methods
* http://api.themoviedb.org/2.1
* Note: This is currently a read-only interface and as such, no write methods exist.
*/
/*
* Media
*/
@SuppressWarnings("unused")
private static final String MEDIA_GET_INFO = "Media.getInfo";
/*
* Movies
*/
private static final String MOVIE_BROWSE = "Movie.browse";
private static final String MOVIE_GET_IMAGES = "Movie.getImages";
private static final String MOVIE_GET_INFO = "Movie.getInfo";
private static final String MOVIE_GET_LATEST = "Movie.getLatest";
private static final String MOVIE_GET_TRANSLATIONS = "Movie.getTranslations";
private static final String MOVIE_GET_VERSION = "Movie.getVersion";
private static final String MOVIE_IMDB_LOOKUP = "Movie.imdbLookup";
private static final String MOVIE_SEARCH = "Movie.search";
/*
* People
*/
private static final String PERSON_GET_INFO = "Person.getInfo";
private static final String PERSON_GET_LATEST = "Person.getLatest";
private static final String PERSON_GET_VERSION = "Person.getVersion";
private static final String PERSON_SEARCH = "Person.search";
/*
* Misc
*/
private static final String GENRES_GET_LIST = "Genres.getList";
/** /**
* Compare the MovieDB object with a title & year * Compare the MovieDB object with a title & year
* @param moviedb The moviedb object to compare too * @param moviedb The moviedb object to compare too
@ -96,7 +145,7 @@ public class TheMovieDb {
} }
return false; return false;
} }
/** /**
* Search a list of movies and return the one that matches the title & year * Search a list of movies and return the one that matches the title & year
* @param movieList The list of movies to search * @param movieList The list of movies to search
@ -117,7 +166,7 @@ public class TheMovieDb {
return null; return null;
} }
/** /**
* Check the string passed to see if it contains a value. * Check the string passed to see if it contains a value.
* @param testString The string to test * @param testString The string to test
@ -131,68 +180,11 @@ public class TheMovieDb {
} }
return true; return true;
} }
/*
* API Methods
* http://api.themoviedb.org/2.1
* Note: This is currently a read-only interface and as such, no write methods exist.
*/
/*
* Media
*/
@SuppressWarnings("unused")
private static final String MEDIA_GET_INFO = "Media.getInfo";
/*
* Movies
*/
private static final String MOVIE_BROWSE = "Movie.browse";
private static final String MOVIE_GET_IMAGES = "Movie.getImages";
private static final String MOVIE_GET_INFO = "Movie.getInfo";
private static final String MOVIE_GET_LATEST = "Movie.getLatest";
private static final String MOVIE_GET_TRANSLATIONS = "Movie.getTranslations";
private static final String MOVIE_GET_VERSION = "Movie.getVersion";
private static final String MOVIE_IMDB_LOOKUP = "Movie.imdbLookup";
private static final String MOVIE_SEARCH = "Movie.search";
/*
* People
*/
private static final String PERSON_GET_INFO = "Person.getInfo";
private static final String PERSON_GET_LATEST = "Person.getLatest";
private static final String PERSON_GET_VERSION = "Person.getVersion";
private static final String PERSON_SEARCH = "Person.search";
/*
* Misc
*/
private static final String GENRES_GET_LIST = "Genres.getList";
public static Logger getLogger() { public static Logger getLogger() {
return logger; return logger;
} }
/**
* Constructor with default logger.
* @param apiKey
*/
public TheMovieDb(String apiKey) {
setLogger(Logger.getLogger("TheMovieDB"));
if (!isValidString(apiKey)) {
logger.severe("TheMovieDb was initialized with a wrong API key!");
}
setApiKey(apiKey);
}
public TheMovieDb(String apiKey, Logger logger) {
setLogger(logger);
if (!isValidString(apiKey)) {
logger.severe("TheMovieDb was initialized with a wrong API key!");
}
setApiKey(apiKey);
}
/** /**
* Build comma separated ids for Movie.getLatest and Movie.getVersion. * Build comma separated ids for Movie.getLatest and Movie.getVersion.
* @param ids a List of ids * @param ids a List of ids
@ -200,7 +192,7 @@ public class TheMovieDb {
*/ */
private String buildIds(List<String> ids) { private String buildIds(List<String> ids) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (int i = 0; i < ids.size(); i++) { for (int i = 0; i < ids.size(); i++) {
if (i == 0) { if (i == 0) {
builder.append(ids.get(i)); builder.append(ids.get(i));
@ -221,9 +213,9 @@ public class TheMovieDb {
*/ */
private String buildUrl(String prefix, String searchTerm, String language) { private String buildUrl(String prefix, String searchTerm, String language) {
StringBuilder url = new StringBuilder(); StringBuilder url = new StringBuilder();
url.append(API_SITE); url.append(API_SITE);
url.append(prefix); url.append(prefix);
url.append("/"); url.append("/");
@ -321,11 +313,11 @@ public class TheMovieDb {
validParameters.add("companies"); validParameters.add("companies");
validParameters.add("countries"); validParameters.add("countries");
StringBuilder searchUrl = new StringBuilder(); StringBuilder searchUrl = new StringBuilder();
searchUrl.append("order_by=").append(orderBy); searchUrl.append("order_by=").append(orderBy);
searchUrl.append("&order=").append(order); searchUrl.append("&order=").append(order);
if(!parameters.isEmpty()) { if(!parameters.isEmpty()) {
for (String key : validParameters) { for (String key : validParameters) {
if (parameters.containsKey(key)) { if (parameters.containsKey(key)) {
@ -336,11 +328,11 @@ public class TheMovieDb {
// Get the search url // Get the search url
String baseUrl = buildUrl(MOVIE_BROWSE, "", language); String baseUrl = buildUrl(MOVIE_BROWSE, "", language);
// Now append the parameter url to the end of the search url // Now append the parameter url to the end of the search url
searchUrl.insert(0, "?"); searchUrl.insert(0, "?");
searchUrl.insert(0, baseUrl); searchUrl.insert(0, baseUrl);
return MovieDbParser.parseMovies(searchUrl.toString()); return MovieDbParser.parseMovies(searchUrl.toString());
} }
@ -395,13 +387,13 @@ public class TheMovieDb {
/** /**
* Gets all the information for a given TheMovieDb ID * Gets all the information for a given TheMovieDb ID
* *
* @param movie * @param movie
* An existing MovieDB object to populate with the data * An existing MovieDB object to populate with the data
* @param tmdbID * @param tmdbID
* The Movie Db ID for the movie to get information for * The Movie Db ID for the movie to get information for
* @param language * @param language
* The two digit language code. E.g. en=English * The two digit language code. E.g. en=English
* @return A movie bean with all of the information * @return A movie bean with all of the information
*/ */
public MovieDB moviedbGetInfo(String tmdbID, MovieDB movie, String language) { public MovieDB moviedbGetInfo(String tmdbID, MovieDB movie, String language) {
@ -424,9 +416,9 @@ public class TheMovieDb {
/** /**
* Passes a null MovieDB object to the full function * Passes a null MovieDB object to the full function
* *
* @param tmdbID TheMovieDB ID of the movie to get the information for * @param tmdbID TheMovieDB ID of the movie to get the information for
* @param language The two digit language code. E.g. en=English * @param language The two digit language code. E.g. en=English
* @return A movie bean with all of the information * @return A movie bean with all of the information
*/ */
public MovieDB moviedbGetInfo(String tmdbID, String language) { public MovieDB moviedbGetInfo(String tmdbID, String language) {
@ -493,9 +485,9 @@ public class TheMovieDb {
/** /**
* Searches the database using the IMDb reference * Searches the database using the IMDb reference
* *
* @param imdbID IMDb reference, must include the "tt" at the start * @param imdbID IMDb reference, must include the "tt" at the start
* @param language The two digit language code. E.g. en=English * @param language The two digit language code. E.g. en=English
* @return A movie bean with the data extracted * @return A movie bean with the data extracted
*/ */
public MovieDB moviedbImdbLookup(String imdbID, String language) { public MovieDB moviedbImdbLookup(String imdbID, String language) {
@ -512,7 +504,7 @@ public class TheMovieDb {
/** /**
* Searches the database using the movie title passed * Searches the database using the movie title passed
* *
* @param movieTitle The title to search for * @param movieTitle The title to search for
* @param language The two digit language code. E.g. en=English * @param language The two digit language code. E.g. en=English
* @return A movie bean with the data extracted * @return A movie bean with the data extracted
@ -528,9 +520,9 @@ public class TheMovieDb {
} }
/** /**
* The Person.getInfo method is used to retrieve the full filmography, known movies, * The Person.getInfo method is used to retrieve the full filmography, known movies,
* images and things like birthplace for a specific person in the TMDb database. * images and things like birthplace for a specific person in the TMDb database.
* *
* @param personID * @param personID
* @param language * @param language
* @return * @return
@ -574,18 +566,18 @@ public class TheMovieDb {
} }
/** /**
* The Person.getVersion method is used to retrieve the last modified time * The Person.getVersion method is used to retrieve the last modified time
* along with the current version number of the called object(s). This is * along with the current version number of the called object(s). This is
* useful if you've already called the object sometime in the past and * useful if you've already called the object sometime in the past and
* simply want to do a quick check for updates. * simply want to do a quick check for updates.
* *
* @param personID a Person TMDb id * @param personID a Person TMDb id
* @param language the two digit language code. E.g. en=English * @param language the two digit language code. E.g. en=English
* @return * @return
*/ */
public Person personGetVersion(String personID, String language) { public Person personGetVersion(String personID, String language) {
Person person = new Person(); Person person = new Person();
if (!isValidString(personID)) { if (!isValidString(personID)) {
return person; return person;
} }
@ -601,7 +593,7 @@ public class TheMovieDb {
/** /**
* The Person.search method is used to search for an actor, actress or production member. * The Person.search method is used to search for an actor, actress or production member.
* http://api.themoviedb.org/2.1/methods/Person.search * http://api.themoviedb.org/2.1/methods/Person.search
* *
* @param personName * @param personName
* @param language * @param language
* @return * @return

@ -1,34 +1,38 @@
/* /*
* Copyright (c) 2004-2011 YAMJ Members * Copyright (c) 2004-2011 YAMJ Members
* http://code.google.com/p/moviejukebox/people/list * http://code.google.com/p/moviejukebox/people/list
* *
* Web: http://code.google.com/p/moviejukebox/ * Web: http://code.google.com/p/moviejukebox/
* *
* This software is licensed under a Creative Commons License * This software is licensed under a Creative Commons License
* See this page: http://code.google.com/p/moviejukebox/wiki/License * See this page: http://code.google.com/p/moviejukebox/wiki/License
* *
* For any reuse or distribution, you must make clear to others the * For any reuse or distribution, you must make clear to others the
* license terms of this work. * license terms of this work.
*/ */
package com.moviejukebox.themoviedb.model; package com.moviejukebox.themoviedb.model;
import com.moviejukebox.themoviedb.TheMovieDb;
import java.io.Serializable; import java.io.Serializable;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Date; import java.util.Date;
import com.moviejukebox.themoviedb.tools.ModelTools; import com.moviejukebox.themoviedb.tools.ModelTools;
import java.util.logging.Logger;
/** /**
* This is the Movie Search bean for the MovieDb.org search * This is the Movie Search bean for the MovieDb.org search
* *
* @author Stuart.Boston * @author Stuart.Boston
*/ */
public class MovieDB extends ModelTools implements Serializable { public class MovieDB extends ModelTools implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static final Logger logger = TheMovieDb.getLogger();
public static final String UNKNOWN = "UNKNOWN"; public static final String UNKNOWN = "UNKNOWN";
@ -63,7 +67,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getPopularity() { public String getPopularity() {
return popularity; return popularity;
} }
public void setPopularity(String popularity) { public void setPopularity(String popularity) {
this.popularity = popularity; this.popularity = popularity;
} }
@ -71,7 +75,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getTitle() { public String getTitle() {
return title; return title;
} }
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
@ -79,11 +83,11 @@ public class MovieDB extends ModelTools implements Serializable {
public String getType() { public String getType() {
return type; return type;
} }
public void setType(String type) { public void setType(String type) {
this.type = type; this.type = type;
} }
public String getId() { public String getId() {
return id; return id;
} }
@ -91,11 +95,11 @@ public class MovieDB extends ModelTools implements Serializable {
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
public String getImdb() { public String getImdb() {
return imdb; return imdb;
} }
public void setImdb(String imdb) { public void setImdb(String imdb) {
this.imdb = imdb; this.imdb = imdb;
} }
@ -103,7 +107,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getUrl() { public String getUrl() {
return url; return url;
} }
public void setUrl(String url) { public void setUrl(String url) {
this.url = url; this.url = url;
} }
@ -111,7 +115,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getOverview() { public String getOverview() {
return overview; return overview;
} }
public void setOverview(String overview) { public void setOverview(String overview) {
this.overview = overview; this.overview = overview;
} }
@ -119,7 +123,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getReleaseDate() { public String getReleaseDate() {
return releaseDate; return releaseDate;
} }
public void setReleaseDate(String releaseDate) { public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate; this.releaseDate = releaseDate;
} }
@ -127,7 +131,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getRating() { public String getRating() {
return rating; return rating;
} }
public void setRating(String rating) { public void setRating(String rating) {
this.rating = rating; this.rating = rating;
} }
@ -135,7 +139,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getRuntime() { public String getRuntime() {
return runtime; return runtime;
} }
public void setRuntime(String runtime) { public void setRuntime(String runtime) {
this.runtime = runtime; this.runtime = runtime;
} }
@ -143,7 +147,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getBudget() { public String getBudget() {
return budget; return budget;
} }
public void setBudget(String budget) { public void setBudget(String budget) {
this.budget = budget; this.budget = budget;
} }
@ -151,7 +155,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getRevenue() { public String getRevenue() {
return revenue; return revenue;
} }
public void setRevenue(String revenue) { public void setRevenue(String revenue) {
this.revenue = revenue; this.revenue = revenue;
} }
@ -159,7 +163,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getHomepage() { public String getHomepage() {
return homepage; return homepage;
} }
public void setHomepage(String homepage) { public void setHomepage(String homepage) {
this.homepage = homepage; this.homepage = homepage;
} }
@ -167,7 +171,7 @@ public class MovieDB extends ModelTools implements Serializable {
public String getTrailer() { public String getTrailer() {
return trailer; return trailer;
} }
public void setTrailer(String trailer) { public void setTrailer(String trailer) {
this.trailer = trailer; this.trailer = trailer;
} }
@ -175,17 +179,17 @@ public class MovieDB extends ModelTools implements Serializable {
public List<Country> getProductionCountries() { public List<Country> getProductionCountries() {
return countries; return countries;
} }
public void addProductionCountry(Country country) { public void addProductionCountry(Country country) {
if (country != null) { if (country != null) {
countries.add(country); countries.add(country);
} }
} }
public List<Person> getPeople() { public List<Person> getPeople() {
return people; return people;
} }
public void addPerson(Person person) { public void addPerson(Person person) {
if (person != null) { if (person != null) {
people.add(person); people.add(person);
@ -195,7 +199,7 @@ public class MovieDB extends ModelTools implements Serializable {
public List<Category> getCategories() { public List<Category> getCategories() {
return categories; return categories;
} }
public void addCategory(Category category) { public void addCategory(Category category) {
if (category != null) { if (category != null) {
categories.add(category); categories.add(category);
@ -273,13 +277,13 @@ public class MovieDB extends ModelTools implements Serializable {
public void setStudios(List<Studio> studios) { public void setStudios(List<Studio> studios) {
this.studios = studios; this.studios = studios;
} }
public void addStudio(Studio studio) { public void addStudio(Studio studio) {
if (studio != null) { if (studio != null) {
this.studios.add(studio); this.studios.add(studio);
} }
} }
public void setCountries(List<Country> countries) { public void setCountries(List<Country> countries) {
this.countries = countries; this.countries = countries;
} }
@ -298,11 +302,10 @@ public class MovieDB extends ModelTools implements Serializable {
public void setLastModifiedAt(String lastModifiedAt) { public void setLastModifiedAt(String lastModifiedAt) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try { try {
setLastModifiedAt(df.parse(lastModifiedAt)); setLastModifiedAt(df.parse(lastModifiedAt));
} catch (Exception ignore) { } catch (ParseException ex) {
return; logger.fine("MovieDB: Error parsing date: " + lastModifiedAt);
} }
} }

@ -1,34 +1,38 @@
/* /*
* Copyright (c) 2004-2011 YAMJ Members * Copyright (c) 2004-2011 YAMJ Members
* http://code.google.com/p/moviejukebox/people/list * http://code.google.com/p/moviejukebox/people/list
* *
* Web: http://code.google.com/p/moviejukebox/ * Web: http://code.google.com/p/moviejukebox/
* *
* This software is licensed under a Creative Commons License * This software is licensed under a Creative Commons License
* See this page: http://code.google.com/p/moviejukebox/wiki/License * See this page: http://code.google.com/p/moviejukebox/wiki/License
* *
* For any reuse or distribution, you must make clear to others the * For any reuse or distribution, you must make clear to others the
* license terms of this work. * license terms of this work.
*/ */
package com.moviejukebox.themoviedb.model; package com.moviejukebox.themoviedb.model;
import com.moviejukebox.themoviedb.TheMovieDb;
import java.io.Serializable; import java.io.Serializable;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import com.moviejukebox.themoviedb.tools.ModelTools; import com.moviejukebox.themoviedb.tools.ModelTools;
import java.util.logging.Logger;
/** /**
* This is the new bean for the Person * This is the new bean for the Person
* *
* @author Stuart.Boston * @author Stuart.Boston
* *
*/ */
public class Person extends ModelTools implements Serializable { public class Person extends ModelTools implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static final Logger logger = TheMovieDb.getLogger();
private static final String UNKNOWN = MovieDB.UNKNOWN; private static final String UNKNOWN = MovieDB.UNKNOWN;
@ -49,119 +53,226 @@ public class Person extends ModelTools implements Serializable {
private List<Filmography> filmography = new ArrayList<Filmography>(); private List<Filmography> filmography = new ArrayList<Filmography>();
private List<String> aka = new ArrayList<String>(); private List<String> aka = new ArrayList<String>();
private List<Artwork> images = new ArrayList<Artwork>(); private List<Artwork> images = new ArrayList<Artwork>();
/**
* Add a single AKA
* @param alsoKnownAs
*/
public void addAka(String alsoKnownAs) { public void addAka(String alsoKnownAs) {
this.aka.add(alsoKnownAs); this.aka.add(alsoKnownAs);
} }
/**
* Add a film for the person
* @param film
*/
public void addFilm(Filmography film) { public void addFilm(Filmography film) {
this.filmography.add(film); this.filmography.add(film);
} }
/**
* Add an artwork image to the person
* @param image
*/
public void addImage(Artwork image) { public void addImage(Artwork image) {
if (image != null) { if (image != null) {
this.images.add(image); this.images.add(image);
} }
} }
/**
* Get all the AKA values
* @return
*/
public List<String> getAka() { public List<String> getAka() {
return aka; return aka;
} }
/**
* Get the biography information
* @return
*/
public String getBiography() { public String getBiography() {
return biography; return biography;
} }
/**
* Get the birthday of the person
* @return
*/
public Date getBirthday() { public Date getBirthday() {
return birthday; return birthday;
} }
/**
* Get the birthplace
* @return
*/
public String getBirthPlace() { public String getBirthPlace() {
return birthPlace; return birthPlace;
} }
/**
* get the cast ID
* @return
*/
public int getCastId() { public int getCastId() {
return castId; return castId;
} }
/**
* get the character
* @return
*/
public String getCharacter() { public String getCharacter() {
return character; return character;
} }
/**
* get the department
* @return
*/
public String getDepartment() { public String getDepartment() {
return department; return department;
} }
/**
* get the list of films
* @return
*/
public List<Filmography> getFilmography() { public List<Filmography> getFilmography() {
return filmography; return filmography;
} }
/**
* get the ID of the person
* @return
*/
public String getId() { public String getId() {
return id; return id;
} }
/**
* get a list of images for the person
* @return
*/
public List<Artwork> getImages() { public List<Artwork> getImages() {
return images; return images;
} }
/**
* get the job
* @return
*/
public String getJob() { public String getJob() {
return job; return job;
} }
/**
* get the known movies
* @return
*/
public int getKnownMovies() { public int getKnownMovies() {
return knownMovies; return knownMovies;
} }
/**
* get the last modified date for the person
* @return
*/
public Date getLastModifiedAt() { public Date getLastModifiedAt() {
return lastModifiedAt; return lastModifiedAt;
} }
/**
* get the name
* @return
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
* get the order
* @return
*/
public int getOrder() { public int getOrder() {
return order; return order;
} }
/**
* get the URL for the person
* @return
*/
public String getUrl() { public String getUrl() {
return url; return url;
} }
/**
* get the version
* @return
*/
public int getVersion() { public int getVersion() {
return version; return version;
} }
/**
* Set the AKA list for the person
* @param aka
*/
public void setAka(List<String> aka) { public void setAka(List<String> aka) {
this.aka = aka; this.aka = aka;
} }
/**
* Set the biography
* @param biography
*/
public void setBiography(String biography) { public void setBiography(String biography) {
this.biography = biography; this.biography = biography;
} }
/**
* Set the person's birthday
* @param birthday
*/
public void setBirthday(Date birthday) { public void setBirthday(Date birthday) {
this.birthday = birthday; this.birthday = birthday;
} }
/**
* Set the person's birthday
* @param sBirthday
*/
public void setBirthday(String sBirthday) { public void setBirthday(String sBirthday) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try { try {
setBirthday(df.parse(sBirthday)); setBirthday(df.parse(sBirthday));
} catch (Exception ignore) { } catch (ParseException ex) {
return; logger.fine("TheMovieDB - Person: Error parsing birthday: " + sBirthday);
} }
} }
/**
* Set the birth place
* @param birthPlace
*/
public void setBirthPlace(String birthPlace) { public void setBirthPlace(String birthPlace) {
this.birthPlace = birthPlace; this.birthPlace = birthPlace;
} }
/**
* Set the cast ID for the person
* @param castId
*/
public void setCastId(int castId) { public void setCastId(int castId) {
this.castId = castId; this.castId = castId;
} }
/**
* Set the cast ID for the person
* @param castId
*/
public void setCastId(String castId) { public void setCastId(String castId) {
try { try {
this.castId = Integer.parseInt(castId); this.castId = Integer.parseInt(castId);
@ -170,41 +281,77 @@ public class Person extends ModelTools implements Serializable {
} }
} }
/**
* Set the character
* @param character
*/
public void setCharacter(String character) { public void setCharacter(String character) {
this.character = character; this.character = character;
} }
/**
* set the Department
* @param department
*/
public void setDepartment(String department) { public void setDepartment(String department) {
this.department = department; this.department = department;
} }
/**
* Add a list of films
* @param filmography
*/
public void setFilmography(List<Filmography> filmography) { public void setFilmography(List<Filmography> filmography) {
this.filmography = filmography; this.filmography = filmography;
} }
/**
* Set the ID of the person
* @param id
*/
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
/**
* Set a list of images for the person
* @param images
*/
public void setImages(List<Artwork> images) { public void setImages(List<Artwork> images) {
this.images = images; this.images = images;
} }
/**
* Set the job for the person
* @param job
*/
public void setJob(String job) { public void setJob(String job) {
this.job = job; this.job = job;
} }
/**
* Set the known movie for the person
* @param knownMovies
*/
public void setKnownMovies(int knownMovies) { public void setKnownMovies(int knownMovies) {
this.knownMovies = knownMovies; this.knownMovies = knownMovies;
} }
/**
* Set the last modified date
* @param lastModifiedAt
*/
public void setLastModifiedAt(Date lastModifiedAt) { public void setLastModifiedAt(Date lastModifiedAt) {
this.lastModifiedAt = lastModifiedAt; this.lastModifiedAt = lastModifiedAt;
} }
/**
* Set the last modified date
* @param lastModifiedAt
*/
public void setLastModifiedAt(String lastModifiedAt) { public void setLastModifiedAt(String lastModifiedAt) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try { try {
Date lma = df.parse(lastModifiedAt); Date lma = df.parse(lastModifiedAt);
setLastModifiedAt(lma); setLastModifiedAt(lma);
@ -213,14 +360,26 @@ public class Person extends ModelTools implements Serializable {
} }
} }
/**
* Set the person's anme
* @param name
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/**
*Set the order
* @param order
*/
public void setOrder(int order) { public void setOrder(int order) {
this.order = order; this.order = order;
} }
/**
* Set the order
* @param order
*/
public void setOrder(String order) { public void setOrder(String order) {
try { try {
this.order = Integer.parseInt(order); this.order = Integer.parseInt(order);
@ -229,14 +388,26 @@ public class Person extends ModelTools implements Serializable {
} }
} }
/**
* Set the URL
* @param url
*/
public void setUrl(String url) { public void setUrl(String url) {
this.url = url; this.url = url;
} }
/**
* Set the version
* @param version
*/
public void setVersion(int version) { public void setVersion(int version) {
this.version = version; this.version = version;
} }
/**
* Generate a String representation of the person
* @return
*/
@Override @Override
public String toString() { public String toString() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();

@ -1,36 +0,0 @@
/*
* Copyright (c) 2004-2011 YAMJ Members
* http://code.google.com/p/moviejukebox/people/list
*
* Web: http://code.google.com/p/moviejukebox/
*
* This software is licensed under a Creative Commons License
* See this page: http://code.google.com/p/moviejukebox/wiki/License
*
* For any reuse or distribution, you must make clear to others the
* license terms of this work.
*/
package com.moviejukebox.themoviedb.tools;
public class Base64 {
private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
public static String base64Encode(String string) {
String unEncoded = string; // Copy the string so we can modify it
StringBuffer encoded = new StringBuffer();
// determine how many padding bytes to add to the output
int paddingCount = (3 - (unEncoded.length() % 3)) % 3;
// add any necessary padding to the input
unEncoded += "\0\0".substring(0, paddingCount);
// process 3 bytes at a time, churning out 4 output bytes
// worry about CRLF insertions later
for (int i = 0; i < unEncoded.length(); i += 3) {
int j = (unEncoded.charAt(i) << 16) + (unEncoded.charAt(i + 1) << 8) + unEncoded.charAt(i + 2);
encoded.append(base64code.charAt((j >> 18) & 0x3f) + base64code.charAt((j >> 12) & 0x3f) + base64code.charAt((j >> 6) & 0x3f)
+ base64code.charAt(j & 0x3f));
}
// replace encoded padding nulls with "="
// return encoded;
return "Basic " + encoded.toString();
}
}

@ -1,14 +1,14 @@
/* /*
* Copyright (c) 2004-2011 YAMJ Members * Copyright (c) 2004-2011 YAMJ Members
* http://code.google.com/p/moviejukebox/people/list * http://code.google.com/p/moviejukebox/people/list
* *
* Web: http://code.google.com/p/moviejukebox/ * Web: http://code.google.com/p/moviejukebox/
* *
* This software is licensed under a Creative Commons License * This software is licensed under a Creative Commons License
* See this page: http://code.google.com/p/moviejukebox/wiki/License * See this page: http://code.google.com/p/moviejukebox/wiki/License
* *
* For any reuse or distribution, you must make clear to others the * For any reuse or distribution, you must make clear to others the
* license terms of this work. * license terms of this work.
*/ */
package com.moviejukebox.themoviedb.tools; package com.moviejukebox.themoviedb.tools;
@ -35,7 +35,7 @@ import com.moviejukebox.themoviedb.TheMovieDb;
* *
*/ */
public class DOMHelper { public class DOMHelper {
private static Logger logger = TheMovieDb.getLogger(); private static final Logger logger = TheMovieDb.getLogger();
/** /**
* Gets the string value of the tag element name passed * Gets the string value of the tag element name passed
@ -71,11 +71,11 @@ public class DOMHelper {
Document doc = null; Document doc = null;
InputStream in = null; InputStream in = null;
String webPage = null; String webPage = null;
try { try {
boolean validWebPage = false; boolean validWebPage = false;
webPage = WebBrowser.request(url); webPage = WebBrowser.request(url);
// There seems to be an error with some of the web pages that returns garbage // There seems to be an error with some of the web pages that returns garbage
if (webPage.startsWith("<?xml version")) { if (webPage.startsWith("<?xml version")) {
// This looks like a valid web page // This looks like a valid web page
@ -84,10 +84,10 @@ public class DOMHelper {
logger.fine("DOMHelper: Error with API Call for: " + url); logger.fine("DOMHelper: Error with API Call for: " + url);
return null; return null;
} }
if (validWebPage) { if (validWebPage) {
in = new ByteArrayInputStream(webPage.getBytes("UTF-8")); in = new ByteArrayInputStream(webPage.getBytes("UTF-8"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder(); DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(in); doc = db.parse(in);

@ -1,43 +1,46 @@
/* /*
* Copyright (c) 2004-2011 YAMJ Members * Copyright (c) 2004-2011 YAMJ Members
* http://code.google.com/p/moviejukebox/people/list * http://code.google.com/p/moviejukebox/people/list
* *
* Web: http://code.google.com/p/moviejukebox/ * Web: http://code.google.com/p/moviejukebox/
* *
* This software is licensed under a Creative Commons License * This software is licensed under a Creative Commons License
* See this page: http://code.google.com/p/moviejukebox/wiki/License * See this page: http://code.google.com/p/moviejukebox/wiki/License
* *
* For any reuse or distribution, you must make clear to others the * For any reuse or distribution, you must make clear to others the
* license terms of this work. * license terms of this work.
*/ */
package com.moviejukebox.themoviedb.tools; package com.moviejukebox.themoviedb.tools;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
public class LogFormatter extends java.util.logging.Formatter public class LogFormatter extends java.util.logging.Formatter {
{
private static String apiKey = null; private static String apiKey = null;
private static String EOL = (String)java.security.AccessController.doPrivileged(new PrivilegedAction<Object>() { private static final String EOL = (String) java.security.AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() { public Object run() {
return System.getProperty("line.separator"); return System.getProperty("line.separator");
} }
}); });
@Override
public synchronized String format(LogRecord logRecord) { public synchronized String format(LogRecord logRecord) {
String logMessage = logRecord.getMessage(); String logMessage = logRecord.getMessage();
logMessage = "[TheMovieDb API] " + logMessage.replace(apiKey, "[APIKEY]") + EOL; logMessage = "[TheMovieDb API] " + logMessage.replace(apiKey, "[APIKEY]") + EOL;
Throwable thrown = logRecord.getThrown(); Throwable thrown = logRecord.getThrown();
if (thrown != null) { if (thrown != null) {
logMessage = logMessage + thrown.toString(); logMessage = logMessage + thrown.toString();
} }
return logMessage; return logMessage;
} }
public void addApiKey(String apiKey) { public void addApiKey(String apiKey) {
LogFormatter.apiKey = apiKey; LogFormatter.apiKey = apiKey;
return; return;
} }
} }

@ -1,14 +1,14 @@
/* /*
* Copyright (c) 2004-2011 YAMJ Members * Copyright (c) 2004-2011 YAMJ Members
* http://code.google.com/p/moviejukebox/people/list * http://code.google.com/p/moviejukebox/people/list
* *
* Web: http://code.google.com/p/moviejukebox/ * Web: http://code.google.com/p/moviejukebox/
* *
* This software is licensed under a Creative Commons License * This software is licensed under a Creative Commons License
* See this page: http://code.google.com/p/moviejukebox/wiki/License * See this page: http://code.google.com/p/moviejukebox/wiki/License
* *
* For any reuse or distribution, you must make clear to others the * For any reuse or distribution, you must make clear to others the
* license terms of this work. * license terms of this work.
*/ */
package com.moviejukebox.themoviedb.tools; package com.moviejukebox.themoviedb.tools;
@ -34,10 +34,14 @@ import com.moviejukebox.themoviedb.model.MovieDB;
import com.moviejukebox.themoviedb.model.Person; import com.moviejukebox.themoviedb.model.Person;
import com.moviejukebox.themoviedb.model.Studio; import com.moviejukebox.themoviedb.model.Studio;
/**
* The parser helper class for TheMovieDb API
* @author stuart.boston
*/
public class MovieDbParser { public class MovieDbParser {
private static Logger logger = TheMovieDb.getLogger(); private static final Logger logger = TheMovieDb.getLogger();
private static final String NAME = "name"; private static final String NAME = "name";
private static final String GENRE = "genre"; private static final String GENRE = "genre";
private static final String ID = "id"; private static final String ID = "id";
@ -86,27 +90,32 @@ public class MovieDbParser {
return categories; return categories;
} }
/**
* Get the list of available languages
* @param url
* @return
*/
public static List<Language> parseLanguages(String url) { public static List<Language> parseLanguages(String url) {
List<Language> languages = new ArrayList<Language>(); List<Language> languages = new ArrayList<Language>();
Document doc = null; Document doc = null;
try { try {
doc = DOMHelper.getEventDocFromUrl(url); doc = DOMHelper.getEventDocFromUrl(url);
} catch (Exception e) { } catch (Exception e) {
logger.severe("Movie.getTranslations error: " + e.getMessage()); logger.severe("Movie.getTranslations error: " + e.getMessage());
return languages; return languages;
} }
if (doc == null) { if (doc == null) {
return languages; return languages;
} }
NodeList nlLanguages = doc.getElementsByTagName(LANGUAGE); NodeList nlLanguages = doc.getElementsByTagName(LANGUAGE);
if ((nlLanguages == null) || nlLanguages.getLength() == 0) { if ((nlLanguages == null) || nlLanguages.getLength() == 0) {
return languages; return languages;
} }
for (int i = 0; i < nlLanguages.getLength(); i++) { for (int i = 0; i < nlLanguages.getLength(); i++) {
Node node = nlLanguages.item(i); Node node = nlLanguages.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeType() == Node.ELEMENT_NODE) {
@ -114,7 +123,7 @@ public class MovieDbParser {
languages.add(parseSimpleLanguage(element)); languages.add(parseSimpleLanguage(element));
} }
} }
return languages; return languages;
} }
@ -155,6 +164,11 @@ public class MovieDbParser {
return movie; return movie;
} }
/**
* Parse a DOM document and return the person information
* @param url
* @return
*/
public static Person parseLatestPerson(String url) { public static Person parseLatestPerson(String url) {
Person person = new Person(); Person person = new Person();
Document doc = null; Document doc = null;
@ -219,6 +233,11 @@ public class MovieDbParser {
return movie; return movie;
} }
/**
* Parse the DOM document for movie information and return a list of movies
* @param url
* @return
*/
public static List<MovieDB> parseMovieGetVersion(String url) { public static List<MovieDB> parseMovieGetVersion(String url) {
List<MovieDB> movies = new ArrayList<MovieDB>(); List<MovieDB> movies = new ArrayList<MovieDB>();
Document doc = null; Document doc = null;
@ -251,6 +270,11 @@ public class MovieDbParser {
return movies; return movies;
} }
/**
* Returns a MovieDB object from the Element
* @param movieElement
* @return
*/
private static MovieDB parseMovieInfo(Element movieElement) { private static MovieDB parseMovieInfo(Element movieElement) {
// Inspired by // Inspired by
// http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html // http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
@ -552,6 +576,9 @@ public class MovieDbParser {
return people; return people;
} }
/**
* Parse the URL and return a list of the people found in the DOM document
*/
public static ArrayList<Person> parsePersonInfo(String searchUrl) { public static ArrayList<Person> parsePersonInfo(String searchUrl) {
ArrayList<Person> people = new ArrayList<Person>(); ArrayList<Person> people = new ArrayList<Person>();
Person person = null; Person person = null;
@ -570,15 +597,15 @@ public class MovieDbParser {
NodeList personNodeList = doc.getElementsByTagName(PERSON); NodeList personNodeList = doc.getElementsByTagName(PERSON);
if ((personNodeList == null) || personNodeList.getLength() == 0) { if ((personNodeList == null) || personNodeList.getLength() == 0) {
return people; return people;
} }
for (int loop = 0; loop < personNodeList.getLength(); loop++) { for (int loop = 0; loop < personNodeList.getLength(); loop++) {
Node personNode = personNodeList.item(loop); Node personNode = personNodeList.item(loop);
person = new Person(); person = new Person();
if (personNode == null) { if (personNode == null) {
logger.finest("Person not found"); logger.finest("Person not found");
return people; return people;
@ -587,23 +614,23 @@ public class MovieDbParser {
if (personNode.getNodeType() == Node.ELEMENT_NODE) { if (personNode.getNodeType() == Node.ELEMENT_NODE) {
try { try {
Element personElement = (Element) personNode; Element personElement = (Element) personNode;
person.setName(DOMHelper.getValueFromElement(personElement, NAME)); person.setName(DOMHelper.getValueFromElement(personElement, NAME));
person.setId(DOMHelper.getValueFromElement(personElement, ID)); person.setId(DOMHelper.getValueFromElement(personElement, ID));
person.setBiography(DOMHelper.getValueFromElement(personElement, "biography")); person.setBiography(DOMHelper.getValueFromElement(personElement, "biography"));
try { try {
person.setKnownMovies(Integer.parseInt(DOMHelper.getValueFromElement(personElement, "known_movies"))); person.setKnownMovies(Integer.parseInt(DOMHelper.getValueFromElement(personElement, "known_movies")));
} catch (NumberFormatException error) { } catch (NumberFormatException error) {
person.setKnownMovies(0); person.setKnownMovies(0);
} }
person.setBirthday(DOMHelper.getValueFromElement(personElement, "birthday")); person.setBirthday(DOMHelper.getValueFromElement(personElement, "birthday"));
person.setBirthPlace(DOMHelper.getValueFromElement(personElement, "birthplace")); person.setBirthPlace(DOMHelper.getValueFromElement(personElement, "birthplace"));
person.setUrl(DOMHelper.getValueFromElement(personElement, URL)); person.setUrl(DOMHelper.getValueFromElement(personElement, URL));
person.setVersion(Integer.parseInt(DOMHelper.getValueFromElement(personElement, "version"))); person.setVersion(Integer.parseInt(DOMHelper.getValueFromElement(personElement, "version")));
person.setLastModifiedAt(DOMHelper.getValueFromElement(personElement, "last_modified_at")); person.setLastModifiedAt(DOMHelper.getValueFromElement(personElement, "last_modified_at"));
NodeList artworkNodeList = doc.getElementsByTagName("image"); NodeList artworkNodeList = doc.getElementsByTagName("image");
for (int nodeLoop = 0; nodeLoop < artworkNodeList.getLength(); nodeLoop++) { for (int nodeLoop = 0; nodeLoop < artworkNodeList.getLength(); nodeLoop++) {
Node artworkNode = artworkNodeList.item(nodeLoop); Node artworkNode = artworkNodeList.item(nodeLoop);
@ -617,25 +644,25 @@ public class MovieDbParser {
person.addArtwork(artwork); person.addArtwork(artwork);
} }
} }
NodeList filmNodeList = doc.getElementsByTagName(MOVIE); NodeList filmNodeList = doc.getElementsByTagName(MOVIE);
for (int nodeLoop = 0; nodeLoop < filmNodeList.getLength(); nodeLoop++) { for (int nodeLoop = 0; nodeLoop < filmNodeList.getLength(); nodeLoop++) {
Node filmNode = filmNodeList.item(nodeLoop); Node filmNode = filmNodeList.item(nodeLoop);
if (filmNode.getNodeType() == Node.ELEMENT_NODE) { if (filmNode.getNodeType() == Node.ELEMENT_NODE) {
Element filmElement = (Element) filmNode; Element filmElement = (Element) filmNode;
Filmography film = new Filmography(); Filmography film = new Filmography();
film.setCharacter(filmElement.getAttribute("character")); film.setCharacter(filmElement.getAttribute("character"));
film.setDepartment(filmElement.getAttribute("department")); film.setDepartment(filmElement.getAttribute("department"));
film.setId(filmElement.getAttribute(ID)); film.setId(filmElement.getAttribute(ID));
film.setJob(filmElement.getAttribute("job")); film.setJob(filmElement.getAttribute("job"));
film.setName(filmElement.getAttribute(NAME)); film.setName(filmElement.getAttribute(NAME));
film.setUrl(filmElement.getAttribute(URL)); film.setUrl(filmElement.getAttribute(URL));
person.addFilm(film); person.addFilm(film);
} }
} }
people.add(person); people.add(person);
} catch (Exception error) { } catch (Exception error) {
logger.severe("PersonInfo: " + error.getMessage()); logger.severe("PersonInfo: " + error.getMessage());
@ -646,7 +673,7 @@ public class MovieDbParser {
} }
} }
} }
return people; return people;
} }
@ -688,7 +715,7 @@ public class MovieDbParser {
movie.setLastModifiedAt(DOMHelper.getValueFromElement(element, "last_modified_at")); movie.setLastModifiedAt(DOMHelper.getValueFromElement(element, "last_modified_at"));
return movie; return movie;
} }
/** /**
* Parse a "simple" Person in the form: * Parse a "simple" Person in the form:
* <person> * <person>

@ -1,14 +1,14 @@
/* /*
* Copyright (c) 2004-2011 YAMJ Members * Copyright (c) 2004-2011 YAMJ Members
* http://code.google.com/p/moviejukebox/people/list * http://code.google.com/p/moviejukebox/people/list
* *
* Web: http://code.google.com/p/moviejukebox/ * Web: http://code.google.com/p/moviejukebox/
* *
* This software is licensed under a Creative Commons License * This software is licensed under a Creative Commons License
* See this page: http://code.google.com/p/moviejukebox/wiki/License * See this page: http://code.google.com/p/moviejukebox/wiki/License
* *
* For any reuse or distribution, you must make clear to others the * For any reuse or distribution, you must make clear to others the
* license terms of this work. * license terms of this work.
*/ */
package com.moviejukebox.themoviedb.tools; package com.moviejukebox.themoviedb.tools;
@ -26,14 +26,15 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
/** /**
* Web browser with simple cookies support * Web browser with simple cookies support
*/ */
public final class WebBrowser { public final class WebBrowser {
private static Map<String, String> browserProperties = new HashMap<String, String>(); private static Map<String, String> browserProperties = new HashMap<String, String>();
private static Map<String, Map<String, String>> cookies; private static Map<String, Map<String, String>> cookies = new HashMap<String, Map<String, String>>();
private static String proxyHost = null; private static String proxyHost = null;
private static String proxyPort = null; private static String proxyPort = null;
private static String proxyUsername = null; private static String proxyUsername = null;
@ -42,68 +43,87 @@ public final class WebBrowser {
private static int webTimeoutConnect = 25000; // 25 second timeout private static int webTimeoutConnect = 25000; // 25 second timeout
private static int webTimeoutRead = 90000; // 90 second timeout private static int webTimeoutRead = 90000; // 90 second timeout
static { /**
browserProperties.put("User-Agent", "Mozilla/5.25 Netscape/5.0 (Windows; I; Win95)"); * Constructor for WebBrowser.
cookies = new HashMap<String, Map<String, String>>(); * Does instantiates the browser properties.
*/
public WebBrowser() {
if (browserProperties.isEmpty()) {
browserProperties.put("User-Agent", "Mozilla/5.25 Netscape/5.0 (Windows; I; Win95)");
}
} }
/**
* Request the web page at the specified URL
* @param url
* @return
* @throws IOException
*/
public static String request(String url) throws IOException { public static String request(String url) throws IOException {
return request(new URL(url)); return request(new URL(url));
} }
/**
* Open a connection using proxy parameters if they exist.
* @param url
* @return
* @throws IOException
*/
public static URLConnection openProxiedConnection(URL url) throws IOException { public static URLConnection openProxiedConnection(URL url) throws IOException {
if (proxyHost != null) { if (proxyHost != null) {
System.getProperties().put("proxySet", "true"); System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", proxyHost); System.getProperties().put("proxyHost", proxyHost);
System.getProperties().put("proxyPort", proxyPort); System.getProperties().put("proxyPort", proxyPort);
} }
URLConnection cnx = url.openConnection(); URLConnection cnx = url.openConnection();
if (proxyUsername != null) { if (proxyUsername != null) {
cnx.setRequestProperty("Proxy-Authorization", proxyEncodedPassword); cnx.setRequestProperty("Proxy-Authorization", proxyEncodedPassword);
} }
return cnx; return cnx;
} }
/**
* Request the web page at the specified URL
* @param url
* @return
* @throws IOException
*/
public static String request(URL url) throws IOException { public static String request(URL url) throws IOException {
StringWriter content = null; StringBuilder content = new StringBuilder();
BufferedReader in = null;
URLConnection cnx = null;
try { try {
content = new StringWriter(); cnx = openProxiedConnection(url);
BufferedReader in = null; sendHeader(cnx);
URLConnection cnx = null; readHeader(cnx);
try {
cnx = openProxiedConnection(url);
sendHeader(cnx); in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx)));
readHeader(cnx); String line;
while ((line = in.readLine()) != null) {
in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx))); content.append(line);
String line;
while ((line = in.readLine()) != null) {
content.write(line);
}
} finally {
if (in != null) {
in.close();
}
if ((cnx != null) && (cnx instanceof HttpURLConnection)) {
((HttpURLConnection)cnx).disconnect();
}
} }
return content.toString();
} finally { } finally {
if (content != null) { if (in != null) {
content.close(); in.close();
}
if ((cnx != null) && (cnx instanceof HttpURLConnection)) {
((HttpURLConnection) cnx).disconnect();
} }
} }
return content.toString();
} }
/**
* Set the header information for the connection
* @param cnx
*/
private static void sendHeader(URLConnection cnx) { private static void sendHeader(URLConnection cnx) {
// send browser properties // send browser properties
for (Map.Entry<String, String> browserProperty : browserProperties.entrySet()) { for (Map.Entry<String, String> browserProperty : browserProperties.entrySet()) {
@ -116,6 +136,11 @@ public final class WebBrowser {
} }
} }
/**
* Create the cookies for the header
* @param cnx
* @return
*/
private static String createCookieHeader(URLConnection cnx) { private static String createCookieHeader(URLConnection cnx) {
String host = cnx.getURL().getHost(); String host = cnx.getURL().getHost();
StringBuilder cookiesHeader = new StringBuilder(); StringBuilder cookiesHeader = new StringBuilder();
@ -136,6 +161,10 @@ public final class WebBrowser {
return cookiesHeader.toString(); return cookiesHeader.toString();
} }
/**
* Read the header information into the cookies
* @param cnx
*/
private static void readHeader(URLConnection cnx) { private static void readHeader(URLConnection cnx) {
// read new cookies and update our cookies // read new cookies and update our cookies
for (Map.Entry<String, List<String>> header : cnx.getHeaderFields().entrySet()) { for (Map.Entry<String, List<String>> header : cnx.getHeaderFields().entrySet()) {
@ -172,6 +201,11 @@ public final class WebBrowser {
} }
} }
/**
* Determine the charset for the connection
* @param cnx
* @return
*/
private static Charset getCharset(URLConnection cnx) { private static Charset getCharset(URLConnection cnx) {
Charset charset = null; Charset charset = null;
// content type will be string like "text/html; charset=UTF-8" or "text/html" // content type will be string like "text/html; charset=UTF-8" or "text/html"
@ -191,59 +225,108 @@ public final class WebBrowser {
if (charset == null) { if (charset == null) {
charset = Charset.defaultCharset(); charset = Charset.defaultCharset();
} }
return charset; return charset;
} }
/**
* Return the proxy host name
* @return
*/
public static String getProxyHost() { public static String getProxyHost() {
return proxyHost; return proxyHost;
} }
/**
* Set the proxy host name
* @param tvdbProxyHost
*/
public static void setProxyHost(String tvdbProxyHost) { public static void setProxyHost(String tvdbProxyHost) {
WebBrowser.proxyHost = tvdbProxyHost; WebBrowser.proxyHost = tvdbProxyHost;
} }
/**
* Get the proxy port
* @return
*/
public static String getProxyPort() { public static String getProxyPort() {
return proxyPort; return proxyPort;
} }
public static void setProxyPort(String tvdbProxyPort) { /**
WebBrowser.proxyPort = tvdbProxyPort; * Set the proxy port
* @param proxyPort
*/
public static void setProxyPort(String proxyPort) {
WebBrowser.proxyPort = proxyPort;
} }
public static String getTvdbProxyUsername() { /**
* Get the proxy username
* @return
*/
public static String getProxyUsername() {
return proxyUsername; return proxyUsername;
} }
public static void setProxyUsername(String tvdbProxyUsername) { /**
WebBrowser.proxyUsername = tvdbProxyUsername; * Set the proxy username
* @param proxyUsername
*/
public static void setProxyUsername(String proxyUsername) {
WebBrowser.proxyUsername = proxyUsername;
} }
/**
* Get the proxy password
* @return
*/
public static String getProxyPassword() { public static String getProxyPassword() {
return proxyPassword; return proxyPassword;
} }
public static void setProxyPassword(String tvdbProxyPassword) { /**
WebBrowser.proxyPassword = tvdbProxyPassword; * Set the proxy password.
* Note this will automatically encode the password
if (proxyUsername != null) { * @param proxyPassword
proxyEncodedPassword = proxyUsername + ":" + tvdbProxyPassword; */
proxyEncodedPassword = Base64.base64Encode(proxyEncodedPassword); public static void setProxyPassword(String proxyPassword) {
WebBrowser.proxyPassword = proxyPassword;
if (proxyUsername != null && !proxyPassword.isEmpty()) {
proxyEncodedPassword = proxyUsername + ":" + proxyPassword;
proxyEncodedPassword = "Basic " + new String(Base64.encodeBase64((proxyUsername + ":" + proxyPassword).getBytes()));
} }
} }
/**
* Get the current web connect timeout value
* @return
*/
public static int getWebTimeoutConnect() { public static int getWebTimeoutConnect() {
return webTimeoutConnect; return webTimeoutConnect;
} }
/**
* Get the current web read timeout value
* @return
*/
public static int getWebTimeoutRead() { public static int getWebTimeoutRead() {
return webTimeoutRead; return webTimeoutRead;
} }
/**
* Set the web connect timeout value
* @param webTimeoutConnect
*/
public static void setWebTimeoutConnect(int webTimeoutConnect) { public static void setWebTimeoutConnect(int webTimeoutConnect) {
WebBrowser.webTimeoutConnect = webTimeoutConnect; WebBrowser.webTimeoutConnect = webTimeoutConnect;
} }
/**
* Set the web read timeout value
* @param webTimeoutRead
*/
public static void setWebTimeoutRead(int webTimeoutRead) { public static void setWebTimeoutRead(int webTimeoutRead) {
WebBrowser.webTimeoutRead = webTimeoutRead; WebBrowser.webTimeoutRead = webTimeoutRead;
} }

Loading…
Cancel
Save