Τετάρτη 10 Μαρτίου 2010

Apache HttpClient 4.x Monitoring File Upload

There are quite a few articles on the web which are implementing the monitoring of a file upload with HttpClient 3.x. Since 4.0 release the API has been changed and HttpClient component is incompatible with the previous versions. Digging a bit into the source code i came up with the following implementation.

In order to capture the file upload progress there is a need for controlling the data send over the output stream.

Ex.
FileBody fooBin = new FileBody(new File("/foo.png"));

The class FileBody contains a method writeTo(OutputStream out) which is responsible for the byte transfer over the output stream. In order to capture the bytes send, the FileBody class should be inherited and the writeTo method should be overridden as shown below.

Simple listener:

public interface IFileUploadProgressListener{
public void blockSend(int blockSize);
}

Inherited FilePart Class:

@Override
public void writeTo(OutputStream out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream in = new FileInputStream(getFile());
try {
byte[] tmp = new byte[4096];
int l;
while ((l = in.read(tmp)) != -1) {
out.write(tmp, 0, l);
if(this.progressListener != null){
this.progressListener.blockSend(4096);
}

}
out.flush();
} finally {
in.close();
}
}


In this example i use a simple interface as a progress listener. When a block of bytes is sent over the output stream the listener informs any class which implements it.