57c313e1257070c626c8b36566006f1fbd10944f
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / filter / MultiSourceFilter.java
1 /*
2  * Sonitus - MultiSource.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.base.Preconditions.*;
21
22 import java.io.EOFException;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.io.PipedInputStream;
27 import java.io.PipedOutputStream;
28 import java.util.Arrays;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
32 import net.pterodactylus.sonitus.data.ConnectException;
33 import net.pterodactylus.sonitus.data.Filter;
34 import net.pterodactylus.sonitus.data.Format;
35 import net.pterodactylus.sonitus.data.ReusableSink;
36 import net.pterodactylus.sonitus.data.Source;
37
38 /**
39  * {@link ReusableSink} implementation that supports changing the source without
40  * letting the {@link net.pterodactylus.sonitus.data.Sink} know.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class MultiSourceFilter implements Filter, ReusableSink {
45
46         /** The logger. */
47         private static final Logger logger = Logger.getLogger(MultiSourceFilter.class.getName());
48
49         /** Object used for synchronization. */
50         private final Object syncObject = new Object();
51
52         /** The connection. */
53         private Connection connection;
54
55         /** The format. */
56         private Format format;
57
58         @Override
59         public Format format() {
60                 return format;
61         }
62
63         @Override
64         public byte[] get(int bufferSize) throws EOFException, IOException {
65                 byte[] buffer = new byte[bufferSize];
66                 InputStream inputStream;
67                 synchronized (syncObject) {
68                         inputStream = connection.pipedInputStream;
69                 }
70                 int read = inputStream.read(buffer);
71                 return Arrays.copyOf(buffer, read);
72         }
73
74         @Override
75         public void connect(Source source) throws ConnectException {
76                 checkNotNull(source, "source must not be null");
77                 if (format != null) {
78                         checkArgument(format.equals(source.format()), "source’s format must equal this sink’s format");
79                 } else {
80                         format = source.format();
81                 }
82
83                 if (connection == null) {
84                         connection = new Connection();
85                         new Thread(connection).start();
86                 }
87                 try {
88                         connection.source(source);
89                 } catch (IOException ioe1) {
90                         throw new ConnectException(ioe1);
91                 }
92         }
93
94         /**
95          * The connection feeds the input from the currently connected source to the
96          * input stream that {@link #get(int)} will get its data from.
97          *
98          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
99          */
100         private class Connection implements Runnable {
101
102                 /** The currently connected source. */
103                 /* synchronized by syncObject. */
104                 private Source source;
105
106                 /** The input stream that {@link #get(int)} will read from. */
107                 /* synchronized by syncObject. */
108                 private PipedInputStream pipedInputStream;
109
110                 /** The output stream that the source will be fed into. */
111                 /* synchronized by syncObject. */
112                 private PipedOutputStream pipedOutputStream;
113
114                 /**
115                  * Changes the source of the connection.
116                  *
117                  * @param source
118                  *              The new source of the connection
119                  * @return This connection
120                  * @throws IOException
121                  *              if an I/O error occurs
122                  */
123                 public Connection source(Source source) throws IOException {
124                         synchronized (syncObject) {
125                                 this.source = source;
126                                 pipedInputStream = new PipedInputStream();
127                                 pipedOutputStream = new PipedOutputStream(pipedInputStream);
128                                 syncObject.notifyAll();
129                         }
130                         return this;
131                 }
132
133                 @Override
134                 public void run() {
135                         while (true) {
136                                 /* wait for source to be set. */
137                                 OutputStream outputStream;
138                                 logger.finest("Entering synchronized block...");
139                                 synchronized (syncObject) {
140                                         logger.finest("Entered synchronized block.");
141                                         while (source == null) {
142                                                 try {
143                                                         logger.finest("Waiting for source to connect...");
144                                                         syncObject.wait();
145                                                 } catch (InterruptedException ie1) {
146                                                         /* ignore, keep waiting. */
147                                                 }
148                                         }
149                                         outputStream = pipedOutputStream;
150                                 }
151                                 logger.finest("Exited synchronized block.");
152
153                                 byte[] buffer = null;
154                                 boolean readSuccessful = false;
155                                 while (!readSuccessful) {
156                                         try {
157                                                 buffer = source.get(4096);
158                                                 logger.finest(String.format("Read %d Bytes.", buffer.length));
159                                                 if (buffer.length > 0) {
160                                                         readSuccessful = true;
161                                                 }
162                                         } catch (IOException e) {
163                                                 /* TODO - notify & wait */
164                                         }
165                                 }
166
167                                 try {
168                                         outputStream.write(buffer);
169                                         logger.finest(String.format("Wrote %d Bytes.", buffer.length));
170                                 } catch (IOException ioe1) {
171                                         /* okay, the sink has died, exit. */
172                                         logger.log(Level.WARNING, "Could not write to pipe!", ioe1);
173                                         break;
174                                 }
175                         }
176
177                         logger.info("Exiting.");
178                 }
179
180         }
181
182 }