View Javadoc

1   package org.varienaja.util.coverart;
2   
3   import java.io.IOException;
4   import java.io.InputStreamReader;
5   import java.net.MalformedURLException;
6   import java.net.URI;
7   import java.net.URISyntaxException;
8   import java.net.URL;
9   import java.net.URLConnection;
10  import java.util.LinkedList;
11  import java.util.List;
12  
13  import org.apache.log4j.Logger;
14  
15  /**
16   * @author Varienaja
17   */
18  public abstract class AbstractCoverArtFinder implements ICoverArtFinder {
19  	
20  	/**
21  	 * @return A Logger to write log-statements to.
22  	 */
23  	protected abstract Logger getLogger();
24  	
25  	/**
26  	 * Gets the URI to call, in order to search for Covers from a certain Album
27  	 * of a Band.
28  	 * @param band The name of the Band.
29  	 * @param albumtitle The name of the Album.
30  	 * @return An URI.
31  	 * @throws URISyntaxException If both a scheme and a path are given but the
32  	 *  path is relative, if the URI string constructed from the given 
33  	 *  components violates RFC 2396, or if the authority component of the
34  	 *  string is present but cannot be parsed as a server-based authority.
35  	 */
36  	public abstract URI constructSearchURI(String band, String albumtitle) throws URISyntaxException;
37  	
38  	/**
39  	 * Processes the InputStream of the URI from constructSearchURI(), and
40  	 * extracts a list of CoverArtSearchResult objects from it.
41  	 * @param in The InputStream
42  	 * @return A non-null List of CoverArtSearchResult objects.
43  	 * @throws IOException If an I/O error occurs.
44  	 */
45  	public abstract List<CoverArtSearchResult> procesSearchResult(InputStreamReader in) throws IOException;
46  	
47  	/*
48  	 * (non-Javadoc)
49  	 * @see org.varienaja.util.coverart.ICoverArtFinder#findCoverURLs(java.lang.String, java.lang.String)
50  	 */
51  	public List<CoverArtSearchResult> findCoverURLs(String band, String albumtitle) {
52  		List<CoverArtSearchResult> results = new LinkedList<CoverArtSearchResult>();
53  		try {
54  			URI searchURI = constructSearchURI(band,albumtitle);
55  			URL url = new URL(searchURI.toASCIIString()); //non-ASCII tokens don't seem to function in URLs, toASCII solves that
56  			URLConnection urlc = url.openConnection();
57  			urlc.setRequestProperty("user-agent","Mozilla/5.0"); //Google wants a user-agent.
58  			InputStreamReader in = new InputStreamReader(urlc.getInputStream());
59  			results = procesSearchResult(in);
60  			
61  			in.close();
62  		} catch (URISyntaxException e) {
63  			getLogger().error("Error finding covers: "+e);
64  			e.printStackTrace();
65  		} catch (MalformedURLException e) {
66  			getLogger().error("Error finding covers: "+e);
67  			e.printStackTrace();
68  		} catch (IOException e) {
69  			getLogger().error("Error finding covers: "+e);
70  			e.printStackTrace();
71  		}
72  		return results;
73  	}
74  
75  }