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