1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.io;
21
22 import java.io.FilterOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25
26 /***
27 * The global throtteled OutputStream. All uploads should pipe their
28 * data through this stream.
29 */
30 public class ThrottledOutputStream extends FilterOutputStream
31 implements BandwidthManagable
32 {
33
34
35
36 private long bytesLeft;
37 private int priority;
38
39
40
41 public ThrottledOutputStream(OutputStream out)
42 {
43 super(out);
44
45 UploadBandwidthManager.getInstance().consume(1, false);
46 }
47
48
49
50 public void close() throws IOException
51 {
52 UploadBandwidthManager.getInstance().consume(-1, false);
53 super.close();
54 }
55
56 public int getPriority()
57 {
58 return priority;
59 }
60
61 public void setAllocated(long bytes)
62 {
63 this.bytesLeft = bytes;
64 }
65
66 public void write(byte[] b, int off, int len) throws IOException
67 {
68 while (len > 0) {
69 if (bytesLeft == 0) {
70 try {
71 if (!UploadBandwidthManager.getInstance().allocate(this)) {
72 bytesLeft = len;
73 }
74 }
75 catch (InterruptedException e) {
76 throw new IOException("interrupted");
77 }
78 }
79 int bytes = (int)Math.min(bytesLeft, len);
80 out.write(b, off, bytes);
81 off += bytes;
82 len -= bytes;
83 bytesLeft -= bytes;
84 }
85 }
86 }