1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package net.sf.hermesftp.utils;
26
27 /***
28 * Controls the upload/download bandwidth.
29 *
30 * @author Behnke
31 */
32 public class TransferRateLimiter {
33
34 private static final int SLEEP_INTERVAL = 100;
35
36 private double maxRate;
37
38 private long startTime;
39
40 private long transferredBytes;
41
42 /***
43 * Constructor.
44 */
45 public TransferRateLimiter() {
46 this(-1);
47 }
48
49 /***
50 * Constructor.
51 *
52 * @param maxRate KB per second.
53 */
54 public TransferRateLimiter(double maxRate) {
55 init(maxRate);
56 }
57
58 /***
59 * Initializes the object.
60 *
61 * @param maxRate The maximum transfer rate.
62 */
63 public void init(double maxRate) {
64 this.maxRate = maxRate;
65 startTime = System.currentTimeMillis();
66 transferredBytes = 0;
67 }
68
69 /***
70 * Returns the current transfer rate.
71 *
72 * @return The transfer rate in KB per seconds.
73 */
74 public double getCurrentTransferRate() {
75 double seconds = (System.currentTimeMillis() - startTime) / 1024d;
76 if (seconds <= 0) {
77 seconds = 1;
78 }
79 return (transferredBytes / 1024d) / seconds;
80
81 }
82
83 /***
84 * Updates the transfer rate statistics. If the maximum rate has been exceeded, the method
85 * pauses.
86 *
87 * @param byteCount The number of bytes previously transfered.
88 */
89 public void execute(long byteCount) {
90 transferredBytes += byteCount;
91 while (maxRate >= 0 && getCurrentTransferRate() > maxRate) {
92 try {
93 Thread.sleep(SLEEP_INTERVAL);
94 } catch (InterruptedException e) {
95 break;
96 }
97 }
98 }
99
100 }