1 package org.varienaja.util.coverart;
2
3 import java.io.IOException;
4 import java.io.InputStreamReader;
5 import java.net.URI;
6 import java.net.URISyntaxException;
7 import java.util.LinkedList;
8 import java.util.List;
9
10 import org.apache.log4j.Logger;
11
12
13
14
15 public class GoogleCoverArtFinder extends AbstractCoverArtFinder {
16 private static final Logger log = Logger.getLogger(GoogleCoverArtFinder.class);
17
18 @Override
19 public URI constructSearchURI(String band, String albumtitle) throws URISyntaxException {
20 return new URI("http",null,"images.google.com/images",-1,null,
21 "hl=en&btnG=Search+Images&gbv=2&q="+band+" "+albumtitle,null);
22 }
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 @Override
39 public List<CoverArtSearchResult> procesSearchResult(InputStreamReader in) throws IOException {
40 log.debug("Processing Google-imagesearch response");
41 List<CoverArtSearchResult> results = new LinkedList<CoverArtSearchResult>();
42 StringBuilder sb = new StringBuilder();
43 char[] read = new char[255];
44 int count;
45 while ((count = in.read(read))!=-1) {
46 sb.append(read,0,count);
47 }
48
49 int spot = 0;
50 while ((spot = sb.indexOf("\"/imgres?"))>=0) {
51 CoverArtSearchResult casr = extractData(sb,spot);
52 sb.delete(0,spot+8);
53 if (casr!=null) {
54 results.add(casr);
55 }
56 }
57
58 return results;
59 }
60
61 private CoverArtSearchResult extractData(StringBuilder sb, int spot) {
62 CoverArtSearchResult casr = null;
63 int end = sb.indexOf("],",spot);
64 String interestingpart = sb.substring(spot,end);
65
66 String[] parts = interestingpart.split("\",\"");
67
68 int width = 0;
69 int height = 0;
70 int size = 0;
71 try {
72 String[] sizeparts = parts[9].split(" ");
73
74 width = Integer.parseInt(sizeparts[0]);
75 height = Integer.parseInt(sizeparts[2]);
76 size = 1024*Integer.parseInt(sizeparts[4].substring(0,sizeparts[4].indexOf("k")));
77 } catch (IndexOutOfBoundsException e) {
78
79 } catch (NumberFormatException e) {
80
81 }
82 try {
83
84 casr = new CoverArtSearchResult(parts[3],width,height,size);
85 log.debug("Image extracted: "+casr);
86 } catch (URISyntaxException e) {
87
88 log.debug("Could not construct CoverArtSearchResult with uri: "+parts[3]);
89 }
90 return casr;
91 }
92
93
94
95
96
97 @Override
98 protected Logger getLogger() {
99 return log;
100 }
101
102 }