Thursday, October 16, 2008

Getting updates in a file over network

Faster than getting the actual diff every time:


URL logfile;
try {
logfile = new URL("url-to-file");
URLConnection uc = logfile.openConnection();
uc.setUseCaches(false);
uc.setConnectTimeout(10000);
uc.setRequestProperty("Cache-Control","no-cache");
uc.setRequestProperty("Keep-Alive", "5000");
String userPassword = "user:pswd";
Base64Converter b64c = new Base64Converter();
String encoding = b64c.encode(userPassword.getBytes());
uc.setRequestProperty("Authorization","Basic "+encoding);
uc.setRequestProperty("Content-Type","application/octet-stream");

int contentlength = uc.getContentLength();

//Do something that updates the file or wait till some other process updates it

URLConnection uc2 = logfile.openConnection();
uc2.setRequestProperty("Authorization","Basic "+encoding);
uc2.setRequestProperty("Content-Type","application/octet-stream");
InputStream reis = uc2.getInputStream();
BufferedReader newbr = new BufferedReader(new InputStreamReader(reis));
String temp_str = "";
String new_file = "";
newbr.skip(contentlength);
while((temp_str = newbr.readLine()) != null){
new_file += temp_str + "\n";
}
System.out.printl("Update:");
System.out.println(new_file);

No comments: