2 * Sonitus - Connection.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sonitus.data;
20 import java.io.IOException;
21 import java.util.logging.Level;
22 import java.util.logging.Logger;
25 * A connection reads bytes from a {@link Source} and feeds it to a sink. This
26 * class is meant to be subclassed by each {@link Sink}, overriding the {@link
27 * #feed(byte[])} method to actually feed the data into the sink. The {@link
28 * #feed(byte[])} method is also responsible for blocking for an appropriate
29 * amount of time; this method determines how fast a {@link Source} is
32 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
34 public abstract class Connection implements Runnable {
37 private static final Logger logger = Logger.getLogger(Connection.class.getName());
39 /** The source to consume. */
40 private final Source source;
43 * Creates a new connection that will read from the given source.
48 public Connection(Source source) {
60 byte[] buffer = source.get(bufferSize());
62 } catch (IOException ioe1) {
63 logger.log(Level.WARNING, "Sink died!", ioe1);
68 logger.info("Connection finished.");
70 } catch (IOException ioe1) {
71 /* well, what can we do? nothing. */
80 * Returns the number of bytes that will be requested from the source.
82 * @return The number of bytes that will be requested from the source
84 protected abstract int bufferSize();
87 * Feeds the read data into the sink. The given buffer is always filled and
88 * never contains excess elements.
93 * if an I/O error occurs
95 protected abstract void feed(byte[] buffer) throws IOException;
98 * Notifies the sink that the source does not deliver any more data.
100 * @throws IOException
101 * if an I/O error occurs
103 protected abstract void finish() throws IOException;