3 * Copyright (C) 2006 David Roden
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 package de.todesbaum.util.io;
22 import java.io.FilterOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import java.util.HashMap;
26 import java.util.Iterator;
28 import java.util.Map.Entry;
32 * @author David Roden <droden@gmail.com>
35 public class ReplacingOutputStream extends FilterOutputStream {
37 private Map<String, String> replacements = new HashMap<String, String>();
38 private StringBuffer ringBuffer = new StringBuffer();
43 public ReplacingOutputStream(OutputStream out) {
47 public void addReplacement(String token, String value) {
48 replacements.put(token, value);
55 public void write(int b) throws IOException {
56 ringBuffer.append((char) b);
57 Iterator<Entry<String, String>> entries = replacements.entrySet().iterator();
58 boolean found = false;
59 Entry<String, String> entry = null;
60 while (!found && entries.hasNext()) {
61 entry = entries.next();
62 if (entry.getKey().startsWith(ringBuffer.toString())) {
67 String buffer = ringBuffer.toString();
68 for (int index = 0, size = buffer.length(); index < size; index++) {
69 super.write(buffer.charAt(index));
71 ringBuffer.setLength(0);
73 if (entry.getKey().equals(ringBuffer.toString())) {
74 String buffer = entry.getValue();
75 for (int index = 0, size = buffer.length(); index < size; index++) {
76 super.write(buffer.charAt(index));
78 ringBuffer.setLength(0);