package dkay;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class IMDBBewertung {
private String movieURL = "http://www.imdb.com/title/tt";
private StringBuilder body = new StringBuilder();
private String bewertung;
private List<String> genres;
public IMDBBewertung(String id) throws IOException{
openURL(id);
}
private void openURL(String id) throws IOException{
URL url = new URL(movieURL + id);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(true);
connection.addRequestProperty("user-agent", "Firefox");
connection.setDoOutput(true);
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
body = new StringBuilder();
String line = null;
while (true)
{
line = in.readLine();
if (line == null)
break;
body.append(line);
}
in.close();
this.bewertung = extract("<span class=\"rating-rating\">([.|\\d]*?)<span>");
this.genres = extractAll("Genres:</h4>(.*?)</div>","<a href=\"/genre/.*?\">(.*?)</a>");
}
private String extract(String query){
Matcher matcher = Pattern.compile(query,Pattern.MULTILINE | Pattern.DOTALL).matcher(body);
if(matcher.find()){
if (matcher.groupCount() >= 1)
return matcher.group(1).trim();
else
return matcher.group().trim();
}
return "";
}
/** Extracts all matched subqueries in the first matched query */
private List<String> extractAll(String query, String subquery){
String substr;
List<String> list = new LinkedList<String>();
Matcher matcher = Pattern.compile(query,Pattern.MULTILINE | Pattern.DOTALL).matcher(body);
if(matcher.find()){
if (matcher.groupCount() >= 1)
substr = matcher.group(1).trim();
else
substr = matcher.group().trim();
matcher = Pattern.compile(subquery,Pattern.MULTILINE | Pattern.DOTALL).matcher(substr);
while(matcher.find()){
if (matcher.groupCount() >= 1)
list.add(matcher.group(1).trim());
else
list.add(matcher.group().trim());
}
}
return list;
}
public List<String> getGenres() {
return genres;
}
public String getBewertung() {
return bewertung;
}
public static void main(String[] args){
try {
IMDBBewertung movie = new IMDBBewertung("0162222"); // Cast away
System.out.println("Bewertung: " + movie.getBewertung());
System.out.println("Bewertung: " + movie.getGenres());
} catch (IOException e) {
e.printStackTrace();
}
}
}