forked from sandofsky/code_swarm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAvatarFetcher.java
93 lines (81 loc) · 2.51 KB
/
AvatarFetcher.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class AvatarFetcher {
protected CodeSwarmConfig cfg;
public int size;
public AvatarFetcher(CodeSwarmConfig cfg) {
this.cfg = cfg;
size = cfg.getPositiveIntProperty("AvatarSize");
}
public String fetchUserImage(String username) {
throw new RuntimeException("Override fetchUserImage in your Avatar Fetcher");
}
protected static String getFilename(String key){
return "image_cache/" + key;
}
protected static boolean imageCached(String key) {
return new File(getFilename(key)).exists();
}
protected static String getImage(String key, URL url) {
String filename = getFilename(key);
if (!imageCached(key)){
boolean successful = fetchImage(filename, url);
if (!successful)
return null;
}
return filename;
}
protected static boolean fetchImage(String filename, URL url) {
try {
new File("image_cache").mkdirs();
URLConnection con = url.openConnection();
InputStream input = con.getInputStream();
FileOutputStream output = new FileOutputStream(filename);
int length = con.getContentLength();
if (length == -1){
//read until exhausted
while(true){
int val = input.read();
if (val == -1)
break;
output.write(input.read());
}
}
else{
//read length bytes
for(int i = 0; i < length; i++)
output.write(input.read());
}
output.close();
input.close();
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
//these two methods taken from http://en.gravatar.com/site/implement/java
private static String hex(byte[] array) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i)
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
return sb.toString();
}
protected static String md5Hex (String message) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
return hex (md.digest(message.getBytes("CP1252")));
} catch (NoSuchAlgorithmException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
}