001: /* ***** BEGIN LICENSE BLOCK *****
002: * Version: MPL 1.1
003: * The contents of this file are subject to the Mozilla Public License Version
004: * 1.1 (the "License"); you may not use this file except in compliance with
005: * the License. You may obtain a copy of the License at
006: * http://www.mozilla.org/MPL/
007: *
008: * Software distributed under the License is distributed on an "AS IS" basis,
009: * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
010: * for the specific language governing rights and limitations under the
011: * License.
012: *
013: * The Original Code is Riot.
014: *
015: * The Initial Developer of the Original Code is
016: * Neteye GmbH.
017: * Portions created by the Initial Developer are Copyright (C) 2006
018: * the Initial Developer. All Rights Reserved.
019: *
020: * Contributor(s):
021: * Felix Gnass [fgnass at neteye dot de]
022: *
023: * ***** END LICENSE BLOCK ***** */
024: package org.riotfamily.cachius.support;
025:
026: import java.io.BufferedWriter;
027: import java.io.FilterWriter;
028: import java.io.IOException;
029: import java.io.Writer;
030:
031: /**
032: * A FilterWriter that replaces all occurences of a given token with a
033: * replacement string.
034: *
035: * @author Felix Gnass
036: */
037: public class TokenFilterWriter extends FilterWriter {
038:
039: private final int writeBufferSize = 1024;
040:
041: private char[] writeBuffer;
042:
043: private char[] pattern;
044:
045: private String replacement;
046:
047: private char[] buffer;
048:
049: private int index = 0;
050:
051: public TokenFilterWriter(String token, String replacement,
052: Writer out) {
053: this (token, replacement, new BufferedWriter(out));
054: }
055:
056: public TokenFilterWriter(String token, String replacement,
057: BufferedWriter out) {
058:
059: super (out);
060: this .pattern = token.toCharArray();
061: this .replacement = replacement;
062: this .buffer = new char[pattern.length];
063: }
064:
065: public void write(char[] buf, int offset, int len)
066: throws IOException {
067: for (int i = offset; i < len; i++) {
068: write(buf[i]);
069: }
070: }
071:
072: public synchronized void write(String str, int off, int len)
073: throws IOException {
074:
075: char cbuf[];
076: if (len <= writeBufferSize) {
077: if (writeBuffer == null) {
078: writeBuffer = new char[writeBufferSize];
079: }
080: cbuf = writeBuffer;
081: } else {
082: cbuf = new char[len];
083: }
084: str.getChars(off, (off + len), cbuf, 0);
085: write(cbuf, 0, len);
086: }
087:
088: public void write(int c) throws IOException {
089: if (c == pattern[index]) {
090: buffer[index] = (char) c;
091: index++;
092: if (index == pattern.length) {
093: out.write(replacement);
094: index = 0;
095: }
096: } else {
097: if (index > 0) {
098: out.write(buffer, 0, index);
099: index = 0;
100: }
101: out.write(c);
102: }
103: }
104:
105: }
|