From: David ‘Bombe’ Roden Date: Sat, 16 Mar 2013 11:26:19 +0000 (+0100) Subject: Add input stream drainer. X-Git-Url: https://git.pterodactylus.net/?p=sonitus.git;a=commitdiff_plain;h=29d8aff29691b3d2e5ee9afd173966f0206d3187 Add input stream drainer. --- diff --git a/src/main/java/net/pterodactylus/sonitus/io/InputStreamDrainer.java b/src/main/java/net/pterodactylus/sonitus/io/InputStreamDrainer.java new file mode 100644 index 0000000..6c374ad --- /dev/null +++ b/src/main/java/net/pterodactylus/sonitus/io/InputStreamDrainer.java @@ -0,0 +1,81 @@ +/* + * Sonitus - Drainer.java - Copyright © 2013 David Roden + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package net.pterodactylus.sonitus.io; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.logging.Logger; + +/** + * {@link Runnable} implementation that simply reads an {@link InputStream} + * until an {@link IOException} is thrown, or the stream reaches EOF. + * + * @author David ‘Bombe’ Roden + */ +public class InputStreamDrainer implements Runnable { + + /** The logger. */ + private static final Logger logger = Logger.getLogger(InputStreamDrainer.class.getName()); + + /** The input stream to drain. */ + private final InputStream inputStream; + + /** + * Creates a new input stream drainer. + * + * @param inputStream + * The input stream to drain + */ + public InputStreamDrainer(InputStream inputStream) { + this.inputStream = inputStream; + } + + @Override + public void run() { + byte[] buffer = new byte[1024]; + int read; + try { + while ((read = inputStream.read(buffer)) != -1) { + logger.finest(String.format("Drained %d Bytes: %s", read, filteredBuffer(Arrays.copyOf(buffer, read)))); + } + } catch (IOException ioe1) { + /* ignore, just exit. */ + } + } + + /** + * Creates a string from all ASCII characters contained in the buffer. + * + * @param buffer + * The buffer to create a string from + * @return The pure-ASCII string representation of the buffer’s content + */ + private String filteredBuffer(byte[] buffer) { + StringBuilder filteredBuffer = new StringBuilder(); + for (byte b : buffer) { + if (b == 13) { + filteredBuffer.append("\\n"); + } else if ((b == 9) || ((b >= 32) && (b <= 127))) { + filteredBuffer.append((char) b); + } + } + return filteredBuffer.toString(); + } + +}