1 package net.matuschek.util; 2 3 import java.io.FilterInputStream ; 4 import java.io.IOException ; 5 import java.io.InputStream ; 6 9 10 11 21 public class LimitedBandwidthStream 22 extends FilterInputStream { 23 24 25 26 private int bandwidth = 0; 27 28 29 private boolean isReading = false; 30 31 32 private int count = 0; 33 34 35 private static int CHECK_INTERVAL = 100; 36 37 38 long starttime = 0; 39 40 41 long usedtime = 0; 42 43 44 47 public LimitedBandwidthStream (InputStream in, int bandwidth) 48 throws IOException 49 { 50 super(in); 51 52 if (bandwidth > 0) { 53 this.bandwidth=bandwidth; 54 } else { 55 this.bandwidth=0; 56 } 57 58 count = 0; 59 } 60 61 74 public int read() 75 throws IOException 76 { 77 long currentBandwidth; 78 79 if (! isReading) { 80 starttime = System.currentTimeMillis(); 81 isReading = true; 82 } 83 84 if ((bandwidth > 0) && 86 ((count % CHECK_INTERVAL) == 0)) { 87 do { 88 usedtime = System.currentTimeMillis()-starttime; 89 if (usedtime > 0) { 90 currentBandwidth = (count*1000) / usedtime; 91 } else { 92 currentBandwidth = 0; 93 } 94 if (currentBandwidth > bandwidth) { 95 try { 96 Thread.sleep(100); 97 } catch (InterruptedException e) {} 98 } 99 } while (currentBandwidth > bandwidth); 100 } 101 102 count++; 103 return super.read(); 104 } 105 106 111 public int read(byte[] b) throws IOException { 112 return read(b, 0, b.length); 113 } 114 115 125 public int read(byte[] b, int off, int len) throws IOException { 126 int mycount = 0; 127 int current = 0; 128 if (bandwidth > 0) { 130 for (int i=off; i < off+len; i++) { 131 current = read(); 132 if (current == -1) { 133 return mycount; 134 } else { 135 b[i]=(byte)current; 136 count++; 137 mycount++; 138 } 139 } 140 return mycount; 141 } else { 142 return in.read(b, off, len); 143 } 144 } 145 146 } | Popular Tags |