Java Reference
In-Depth Information
String key = new File('mjg/rotten_tomatoes_apiKey.txt').text
String base = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?"
String qs = [apiKey:key, q:'vampire'].collect { it }.join('&')
String url = "$base$qs"
The API key is stored in an external file. Building the query string starts with a map of
parameters, which is transformed into a map of strings of the form “key=value” and then
joined with an ampersand. The full URL is then the base URL with an appended query
string. Getting the movies and saving them into the database is almost trivial:
def vampMovies = new JsonSlurper().parseText(url.toURL().text)
db.vampireMovies << vampMovies.movies
The JsonSlurper receives text data in JSON form from the URL and converts it to
JSON objects. Saving the results into the database is as simple as appending the whole col-
lection.
The API has a limit of 30 results per page. The search results include a property called
next that points to the next available page, assuming there is one. The script therefore
needs to loop that many times to retrieve the available data:
def next = vampMovies?.links?.next
while (next) {
println next
vampMovies = slurper.parseText("$next&apiKey=$key".toURL().text)
db.vampireMovies << vampMovies.movies
next = vampMovies?.links?.next
}
That's all there is to it. Using a relational database would require mapping the movie struc-
ture to relational tables, which would be a bit of a challenge. Because MongoDB uses
BSON as its native format, even a collection of JSON objects can be added with no work
at all.
There's an Eclipse plugin, called MonjaDB, which connects to MongoDB databases. Fig-
ure 8.5 shows a portion of the vampireMovies database.
Search WWH ::




Custom Search