2 * Sonitus - Drainer.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sonitus.io;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.Arrays;
23 import java.util.logging.Logger;
26 * {@link Runnable} implementation that simply reads an {@link InputStream}
27 * until an {@link IOException} is thrown, or the stream reaches EOF.
29 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
31 public class InputStreamDrainer implements Runnable {
34 private static final Logger logger = Logger.getLogger(InputStreamDrainer.class.getName());
36 /** The input stream to drain. */
37 private final InputStream inputStream;
40 * Creates a new input stream drainer.
43 * The input stream to drain
45 public InputStreamDrainer(InputStream inputStream) {
46 this.inputStream = inputStream;
51 byte[] buffer = new byte[1024];
54 while ((read = inputStream.read(buffer)) != -1) {
55 logger.finest(String.format("Drained %d Bytes: %s", read, filteredBuffer(Arrays.copyOf(buffer, read))));
57 } catch (IOException ioe1) {
58 /* ignore, just exit. */
63 * Creates a string from all ASCII characters contained in the buffer.
66 * The buffer to create a string from
67 * @return The pure-ASCII string representation of the buffer’s content
69 private String filteredBuffer(byte[] buffer) {
70 StringBuilder filteredBuffer = new StringBuilder();
71 for (byte b : buffer) {
73 filteredBuffer.append("\\n");
74 } else if ((b == 9) || ((b >= 32) && (b <= 127))) {
75 filteredBuffer.append((char) b);
78 return filteredBuffer.toString();