Thursday, June 25, 2009

Implementing a Bandwidth Contorlled Pipe in Java

I implemented this one and though will post here so that I can reuse it in future.

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;


import org.apache.commons.io.output.ThresholdingOutputStream;
public class Pipe extends ThresholdingOutputStream{

long LastTimeTheThresoldHasReached;
OutputStream OStream;

int BWCountPeriodInMiliSeconds;

public Pipe(int bwInBytes,int periodInSec, OutputStream oStream)
{
super(bwInBytes);
OStream =oStream;
BWCountPeriodInMiliSeconds = 1000* periodInSec;
LastTimeTheThresoldHasReached = 0;
}

@Override
protected OutputStream getStream() throws IOException {
return OStream;
}

@Override
protected void thresholdReached() throws IOException {
long now = System.currentTimeMillis();
long timeDiff = now - ( LastTimeTheThresoldHasReached + BWCountPeriodInMiliSeconds);
long bytesWritten = getByteCount();
long bytesExceeded = bytesWritten - getThreshold();
long timeThatWeNeedtoWait = (long) (((float)BWCountPeriodInMiliSeconds / getThreshold() ) * bytesExceeded) -timeDiff;

System.out.print("At " + new Date()+" Waiting for "+ timeThatWeNeedtoWait);

if ( timeThatWeNeedtoWait > 0)
{// We used the allocated quota quicker that we should have. So lets wait.
try {
Thread.sleep(timeThatWeNeedtoWait);
} catch (InterruptedException e) {
}

}

System.out.println("... " + new Date()+" Done");
resetByteCount();
LastTimeTheThresoldHasReached = now;
}



public static void main(String[] args) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Pipe pipe = new Pipe(10,10,baos);
while(true)
{
try {
pipe.write("123456789012345".getBytes()); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

No comments: