2 * XdccDownloader - DuplicateLineSuppressingWriter.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.xdcc.util.io;
20 import java.io.IOException;
21 import java.io.Writer;
24 * {@link Writer} implementation that suppreses multiple identical lines written to it.
26 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
28 public class DuplicateLineSuppressingWriter extends Writer {
30 private final Writer writer;
31 private String lastLine;
32 private final StringBuilder currentLine = new StringBuilder();
34 public DuplicateLineSuppressingWriter(Writer writer) {
39 public void write(char[] cbuf) throws IOException {
40 write(cbuf, 0, cbuf.length);
44 public void write(String str) throws IOException {
45 write(str, 0, str.length());
49 public Writer append(CharSequence csq) throws IOException {
50 write(String.valueOf(csq));
55 public Writer append(CharSequence csq, int start, int end) throws IOException {
56 write(String.valueOf(csq).substring(start, end));
61 public Writer append(char c) throws IOException {
67 public void flush() throws IOException {
72 public void close() throws IOException {
77 public void write(int c) throws IOException {
78 currentLine.append((char) c);
79 writeCollectedLines();
83 public void write(char[] cbuf, int off, int len) throws IOException {
84 currentLine.append(cbuf, off, len);
85 writeCollectedLines();
89 public void write(String str, int off, int len) throws IOException {
90 currentLine.append(str, off, len);
91 writeCollectedLines();
98 private void writeCollectedLines() throws IOException {
99 while (currentLineContainsLineBreak()) {
100 String nextLine = cutNextLine();
101 maybeWriteNextLine(nextLine);
105 private void maybeWriteNextLine(String nextLine) throws IOException {
106 if (!nextLine.equals(lastLine)) {
107 writer.write(nextLine);
112 private String cutNextLine() {
113 int indexOfLineBreak = currentLine.indexOf("\n");
114 String nextLine = currentLine.substring(0, indexOfLineBreak + 1);
115 currentLine.delete(0, indexOfLineBreak + 1);
119 private boolean currentLineContainsLineBreak() {
120 return currentLine.indexOf("\n") > -1;