Add filter that can pipe a source through an external binary.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / filter / ExternalFilter.java
1 /*
2  * Sonitus - ExternalFilter.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 java.io.EOFException;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.io.PipedInputStream;
25 import java.io.PipedOutputStream;
26 import java.util.Arrays;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sonitus.data.ConnectException;
30 import net.pterodactylus.sonitus.data.Connection;
31 import net.pterodactylus.sonitus.data.Filter;
32 import net.pterodactylus.sonitus.data.Format;
33 import net.pterodactylus.sonitus.data.Source;
34
35 import com.google.common.base.Preconditions;
36 import com.google.common.collect.ImmutableList;
37 import com.google.common.collect.Iterables;
38 import com.google.common.io.ByteStreams;
39
40 /**
41  * {@link Filter} implementation that runs its {@link Source} through an
42  * external program.
43  *
44  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45  */
46 public abstract class ExternalFilter implements Filter {
47
48         /** The logger. */
49         private static final Logger logger = Logger.getLogger(ExternalFilter.class.getName());
50
51         /** The binary to execute. */
52         private final String binary;
53
54         /** The parameters for the binary. */
55         private final Iterable<String> parameters;
56
57         /** The format of the source. */
58         private Format format;
59
60         /** The input stream that will hold the converted source. */
61         private PipedInputStream pipedInputStream;
62
63         /**
64          * Creates a new external filter.
65          *
66          * @param binary
67          *              The binary to execute
68          * @param parameters
69          *              The parameter for the binary
70          */
71         public ExternalFilter(String binary, Iterable<String> parameters) {
72                 this.binary = binary;
73                 this.parameters = parameters;
74         }
75
76         //
77         // FILTER METHODS
78
79         @Override
80         public Format format() {
81                 return format;
82         }
83
84         @Override
85         public byte[] get(int bufferSize) throws EOFException, IOException {
86                 byte[] buffer = new byte[bufferSize];
87                 int read = pipedInputStream.read(buffer);
88                 return Arrays.copyOf(buffer, read);
89         }
90
91         @Override
92         public void connect(Source source) throws ConnectException {
93                 Preconditions.checkNotNull(source, "source must not be null");
94
95                 format = source.format();
96                 try {
97                         Process process = Runtime.getRuntime().exec(Iterables.toArray(ImmutableList.<String>builder().add(binary).addAll(parameters).build(), String.class));
98                         final InputStream processOutput = process.getInputStream();
99                         final OutputStream processInput = process.getOutputStream();
100                         final InputStream processError = process.getErrorStream();
101                         final PipedOutputStream pipedOutputStream = new PipedOutputStream();
102                         pipedInputStream = new PipedInputStream(pipedOutputStream);
103                         new Thread(new Runnable() {
104
105                                 @Override
106                                 public void run() {
107                                         try {
108                                                 drainInputStream(processError);
109                                         } catch (IOException ioe1) {
110                                                 /* ignore, just let the thread exit. */
111                                         }
112                                         logger.finest("ExternalFilter: Reading stderr finished.");
113                                 }
114                         }).start();
115                         new Thread(new Runnable() {
116
117                                 @Override
118                                 public void run() {
119                                         try {
120                                                 ByteStreams.copy(processOutput, pipedOutputStream);
121                                         } catch (IOException ioe1) {
122                                                 /* okay, just exit. */
123                                         }
124                                         logger.finest("ExternalFilter: Reading stdout finished.");
125                                 }
126                         }).start();
127                         new Thread(new Connection(source) {
128
129                                 @Override
130                                 protected int bufferSize() {
131                                         return 4096;
132                                 }
133
134                                 @Override
135                                 protected void feed(byte[] buffer) throws IOException {
136                                         processInput.write(buffer);
137                                 }
138                         }).start();
139                 } catch (IOException ioe1) {
140
141                 }
142         }
143
144         //
145         // STATIC METHODS
146         //
147
148         private static void drainInputStream(InputStream inputStream) throws IOException {
149                 byte[] buffer = new byte[4096];
150                 int read;
151                 while ((read = inputStream.read(buffer)) != -1) {
152                         logger.finest(String.format("ExternalFilter: Drained %d Bytes.", read));
153                         /* do nothing, just read the damn thing. */
154                 }
155         }
156
157 }