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