1 24 package org.riotfamily.cachius.support; 25 26 import java.io.BufferedWriter ; 27 import java.io.FilterWriter ; 28 import java.io.IOException ; 29 import java.io.Writer ; 30 31 37 public class TokenFilterWriter extends FilterWriter { 38 39 private final int writeBufferSize = 1024; 40 41 private char[] writeBuffer; 42 43 private char[] pattern; 44 45 private String replacement; 46 47 private char[] buffer; 48 49 private int index = 0; 50 51 52 public TokenFilterWriter(String token, String replacement, Writer out) { 53 this(token, replacement, new BufferedWriter (out)); 54 } 55 56 public TokenFilterWriter(String token, String replacement, 57 BufferedWriter out) { 58 59 super(out); 60 this.pattern = token.toCharArray(); 61 this.replacement = replacement; 62 this.buffer = new char[pattern.length]; 63 } 64 65 public void write(char[] buf, int offset, int len) throws IOException { 66 for (int i = offset; i < len; i++) { 67 write(buf[i]); 68 } 69 } 70 71 public synchronized void write(String str, int off, int len) 72 throws IOException { 73 74 char cbuf[]; 75 if (len <= writeBufferSize) { 76 if (writeBuffer == null) { 77 writeBuffer = new char[writeBufferSize]; 78 } 79 cbuf = writeBuffer; 80 } 81 else { 82 cbuf = new char[len]; 83 } 84 str.getChars(off, (off + len), cbuf, 0); 85 write(cbuf, 0, len); 86 } 87 88 public void write(int c) throws IOException { 89 if (c == pattern[index]) { 90 buffer[index] = (char) c; 91 index++; 92 if (index == pattern.length) { 93 out.write(replacement); 94 index = 0; 95 } 96 } 97 else { 98 if (index > 0) { 99 out.write(buffer, 0, index); 100 index = 0; 101 } 102 out.write(c); 103 } 104 } 105 106 } 107 | Popular Tags |