00001 package riverrat.testing;
00002
00003 import java.net.*;
00004 import java.io.*;
00005 import java.util.*;
00006
00018 public class DelayedInputStream extends FilterInputStream {
00019 static final boolean DEBUG = false;
00020
00021 static final int DELAY_FACTOR = 100;
00022 static final int BLOCK_SIZE = 10;
00023
00025 private Random fRandom = new Random(System.currentTimeMillis());
00026
00028 public DelayedInputStream(InputStream in) {
00029 super(in);
00030 }
00031
00033 public int read(byte[] buffer, int offset, int length) throws IOException {
00034
00035 if (length > BLOCK_SIZE) {
00036 length = BLOCK_SIZE;
00037 }
00038 int count = 0;
00039
00040 long before = System.currentTimeMillis();
00041 count = in.read(buffer, offset, length);
00042 try {
00043 Thread.currentThread().sleep(Math.abs(fRandom.nextInt()) % DELAY_FACTOR);
00044 } catch (InterruptedException e) {
00045 e.printStackTrace(System.err);
00046 }
00047 long after = System.currentTimeMillis();
00048
00049 if(DEBUG) {
00050 System.out.print("read "+count+" bytes in "+(after-before)+" ms: ");
00051 printBuffer(buffer, offset, count);
00052 System.out.println();
00053 }
00054
00055 return count;
00056 }
00057
00059 private void printBuffer(byte[] buffer, int offset, int length) {
00060
00061 if (length <= 0) {
00062 System.out.print("no data read");
00063 return;
00064 }
00065
00066 System.out.print('[');
00067 for (int i = 0; i < length; i++) {
00068 switch ((char)buffer[offset + i]) {
00069 case '\r': {
00070 System.out.print("\\r");
00071 break;
00072 } case '\n': {
00073 System.out.print("\\n");
00074 break;
00075 } default: {
00076 System.out.print((char)buffer[offset + i]);
00077 }
00078 }
00079 }
00080 System.out.print(']');
00081 }
00082 }