View Javadoc

1   /*
2    *  XNap - A P2P framework and client.
3    *
4    *  See the file AUTHORS for copyright information.
5    *
6    *  This program is free software; you can redistribute it and/or modify
7    *  it under the terms of the GNU General Public License as published by
8    *  the Free Software Foundation.
9    *
10   *  This program is distributed in the hope that it will be useful,
11   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   *  GNU General Public License for more details.
14   *
15   *  You should have received a copy of the GNU General Public License
16   *  along with this program; if not, write to the Free Software
17   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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      // --- Data Field(s) ---
35  
36  	private long bytesLeft;
37  	private int priority;
38  	
39      // --- Constructor(s) ---
40  
41      public ThrottledOutputStream(OutputStream out) 
42      {
43  		super(out);
44  
45  		UploadBandwidthManager.getInstance().consume(1, false);
46      }
47  	
48      // --- Method(s) ---
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  }