Add rate limiting filter.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / filter / RateLimitingFilter.java
1 /*
2  * Sonitus - DelayFilter.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sonitus.data.filter;
19
20 import static com.google.common.io.Closeables.close;
21
22 import java.io.EOFException;
23 import java.io.IOException;
24 import java.io.PipedInputStream;
25 import java.io.PipedOutputStream;
26 import java.util.Arrays;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sonitus.data.ConnectException;
30 import net.pterodactylus.sonitus.data.Connection;
31 import net.pterodactylus.sonitus.data.Filter;
32 import net.pterodactylus.sonitus.data.Format;
33 import net.pterodactylus.sonitus.data.Source;
34
35 import com.google.common.base.Preconditions;
36
37 /**
38  * Rate limiting filter that only passes a specified amount of data per second
39  * from its {@link Source} to its {@link net.pterodactylus.sonitus.data.Sink}.
40  *
41  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
42  */
43 public class RateLimitingFilter implements Filter {
44
45         /** The logger. */
46         private static final Logger logger = Logger.getLogger(RateLimitingFilter.class.getName());
47
48         /** The limiting rate in bytes/second. */
49         private final int rate;
50
51         /** The source’s format. */
52         private Format format;
53
54         /** The input stream to read from. */
55         private PipedInputStream pipedInputStream = new PipedInputStream();
56
57         /**
58          * Creates a new rate limiting filter.
59          *
60          * @param rate
61          *              The limiting rate (in bytes/second)
62          */
63         public RateLimitingFilter(int rate) {
64                 this.rate = rate;
65         }
66
67         //
68         // FILTER METHODS
69         //
70
71         @Override
72         public Format format() {
73                 return format;
74         }
75
76         @Override
77         public byte[] get(int bufferSize) throws EOFException, IOException {
78                 byte[] buffer = new byte[bufferSize];
79                 int read = pipedInputStream.read(buffer);
80                 if (read == -1) {
81                         throw new EOFException();
82                 }
83                 return Arrays.copyOf(buffer, read);
84         }
85
86         @Override
87         public void connect(Source source) throws ConnectException {
88                 Preconditions.checkNotNull(source, "source must not be null");
89
90                 format = source.format();
91                 final long start = System.currentTimeMillis();
92                 try {
93                         pipedInputStream = new PipedInputStream();
94                         final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream);
95                         new Thread(new Connection(source) {
96
97                                 @Override
98                                 protected int bufferSize() {
99                                         return rate;
100                                 }
101
102                                 @Override
103                                 protected void feed(byte[] buffer) throws IOException {
104                                         long waitTime = 1000 * buffer.length / rate;
105                                         long now = System.currentTimeMillis();
106                                         pipedOutputStream.write(buffer);
107                                         pipedOutputStream.flush();
108                                         while ((System.currentTimeMillis() - now) < waitTime) {
109                                                 try {
110                                                         long limitDelay = waitTime - (System.currentTimeMillis() - now);
111                                                         logger.finest(String.format("Waiting %d ms...", limitDelay));
112                                                         Thread.sleep(limitDelay);
113                                                 } catch (InterruptedException ie1) {
114                                                         /* ignore, keep looping. */
115                                                 }
116                                         }
117                                 }
118
119                                 @Override
120                                 protected void finish() throws IOException {
121                                         close(pipedInputStream, true);
122                                         close(pipedOutputStream, true);
123                                 }
124                         }).start();
125                 } catch (IOException ioe1) {
126                         throw new ConnectException(ioe1);
127                 }
128         }
129
130 }