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