001/* 002 * feinrip 003 * 004 * Copyright (C) 2014 Richard "Shred" Körber 005 * https://github.com/shred/feinrip 006 * 007 * This program is free software: you can redistribute it and/or modify 008 * it under the terms of the GNU General Public License as 009 * published by the Free Software Foundation, either version 3 of the 010 * License, or (at your option) any later version. 011 * 012 * This program is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 015 */ 016package org.shredzone.feinrip.database; 017 018import static java.util.stream.Collectors.toList; 019 020import java.io.IOException; 021import java.io.InputStream; 022import java.net.HttpURLConnection; 023import java.net.URL; 024import java.net.URLEncoder; 025import java.util.List; 026 027import org.shredzone.commons.xml.XQuery; 028import org.xml.sax.InputSource; 029 030/** 031 * Service for accessing OFDb. 032 * 033 * @see <a href="http://www.ofdb.de">Online Filmdatenbank</a> 034 * @author Richard "Shred" Körber 035 */ 036public class OfdbService { 037 038 private static final String SITE = "http://ofdbgw.org"; 039 private static final int TIMEOUT = 10000; 040 041 /** 042 * Searches for titles matching a query. 043 * 044 * @param query 045 * Query string 046 * @return List of potential matches, may be empty but never {@code null} 047 */ 048 public static List<String> searchTitles(String query) throws IOException { 049 String url = SITE + "/search/" + URLEncoder.encode(query, "utf-8"); 050 051 HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); 052 conn.setConnectTimeout(TIMEOUT); 053 conn.setReadTimeout(TIMEOUT); 054 055 try (InputStream in = conn.getInputStream()) { 056 XQuery doc = XQuery.parse(new InputSource(in)); 057 return doc.select("//ofdbgw/resultat/eintrag") 058 .map(entry -> { 059 String title = entry.text("titel"); 060 String year = entry.text("jahr"); 061 062 if (year != null) { 063 title = title + " (" + year + ")"; 064 } 065 066 return title; 067 }) 068 .collect(toList()); 069 } 070 } 071 072}