forked from sandofsky/code_swarm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFreebaseAvatarFetcher.java
79 lines (73 loc) · 2.51 KB
/
FreebaseAvatarFetcher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FreebaseAvatarFetcher extends AvatarFetcher{
public FreebaseAvatarFetcher(CodeSwarmConfig cfg) {
super(cfg);
}
static private Pattern imageIDPattern = Pattern.compile("\"image:id\"\\s*:\\s*\"(.*?)\"");
private static String readURLToString(URL url) {
try {
URLConnection con = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
int length = con.getContentLength();
if (length == -1){
//read until exhausted
while(true){
String line = reader.readLine();
if (line == null) break;
sb.append(line);
}
}
else{
//read length bytes
for(int i = 0; i < length; i++)
sb.append((char)reader.read());
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static String getUserImageID(String username) {
try {
new File("image_cache").mkdirs();
String json = readURLToString(new URL("http://www.freebase.com/api/service/mqlread?query=" +
"{%22query%22:{%22!/common/image/appears_in_topic_gallery%22:"+
"[{%22image:id%22:null}],%22id%22:%22/user/" + username + "%22}}"));
if (json == null) return null;
Matcher m = imageIDPattern.matcher(json);
if (m.find())
return m.group(1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String fetchUserImage(String username) {
String key = md5Hex("metaweb:" + username);
if (imageCached(key))
return getFilename(key);
try {
String imageID = getUserImageID(username);
if (imageID == null) return null;
return getImage(key, new URL("http://www.freebase.com/api/trans/image_thumb/"
+ imageID
+ "?maxheight=" + size
+ "&maxwidth=" + size
+ "&mode=fillcrop"));
} catch (MalformedURLException e) {
e.printStackTrace(); //should be impossible...
return null;
}
}
}