Add method to expose a source’s metadata.
[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.Metadata;
34 import net.pterodactylus.sonitus.data.Source;
35
36 import com.google.common.base.Preconditions;
37
38 /**
39  * Rate limiting filter that only passes a specified amount of data per second
40  * from its {@link Source} to its {@link net.pterodactylus.sonitus.data.Sink}.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class RateLimitingFilter implements Filter {
45
46         /** The logger. */
47         private static final Logger logger = Logger.getLogger(RateLimitingFilter.class.getName());
48
49         /** The limiting rate in bytes/second. */
50         private final int rate;
51
52         /** The source’s format. */
53         private Source source;
54
55         /** The input stream to read from. */
56         private PipedInputStream pipedInputStream = new PipedInputStream();
57
58         /**
59          * Creates a new rate limiting filter.
60          *
61          * @param rate
62          *              The limiting rate (in bytes/second)
63          */
64         public RateLimitingFilter(int rate) {
65                 this.rate = rate;
66         }
67
68         //
69         // FILTER METHODS
70         //
71
72         @Override
73         public Format format() {
74                 return source.format();
75         }
76
77         @Override
78         public Metadata metadata() {
79                 return source.metadata();
80         }
81
82         @Override
83         public byte[] get(int bufferSize) throws EOFException, IOException {
84                 byte[] buffer = new byte[bufferSize];
85                 int read = pipedInputStream.read(buffer);
86                 if (read == -1) {
87                         throw new EOFException();
88                 }
89                 return Arrays.copyOf(buffer, read);
90         }
91
92         @Override
93         public void connect(Source source) throws ConnectException {
94                 Preconditions.checkNotNull(source, "source must not be null");
95
96                 this.source = source;
97                 final long start = System.currentTimeMillis();
98                 try {
99                         pipedInputStream = new PipedInputStream();
100                         final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream);
101                         new Thread(new Connection(source) {
102
103                                 @Override
104                                 protected int bufferSize() {
105                                         return rate;
106                                 }
107
108                                 @Override
109                                 protected void feed(byte[] buffer) throws IOException {
110                                         long waitTime = 1000 * buffer.length / rate;
111                                         long now = System.currentTimeMillis();
112                                         pipedOutputStream.write(buffer);
113                                         pipedOutputStream.flush();
114                                         while ((System.currentTimeMillis() - now) < waitTime) {
115                                                 try {
116                                                         long limitDelay = waitTime - (System.currentTimeMillis() - now);
117                                                         logger.finest(String.format("Waiting %d ms...", limitDelay));
118                                                         Thread.sleep(limitDelay);
119                                                 } catch (InterruptedException ie1) {
120                                                         /* ignore, keep looping. */
121                                                 }
122                                         }
123                                 }
124
125                                 @Override
126                                 protected void finish() throws IOException {
127                                         close(pipedInputStream, true);
128                                         close(pipedOutputStream, true);
129                                 }
130                         }).start();
131                 } catch (IOException ioe1) {
132                         throw new ConnectException(ioe1);
133                 }
134         }
135
136 }