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