1 24 package org.riotfamily.common.io; 25 26 import java.io.FilterReader ; 27 import java.io.IOException ; 28 import java.io.Reader ; 29 30 36 public abstract class AbstractTokenFilterReader extends FilterReader { 37 38 private String replacement = null; 39 40 private int replaceIndex = -1; 41 42 public AbstractTokenFilterReader(Reader in) { 43 super(in); 44 } 45 46 public int read() throws IOException { 47 48 if (replaceIndex != -1) { 49 int i = replacement.charAt(replaceIndex++); 51 if (replaceIndex == replacement.length()) { 52 replaceIndex = -1; 53 } 54 return i; 55 } 56 57 int i = super.read(); 58 if (i != '$') { 59 return i; 61 } 62 63 char c = (char) super.read(); 65 if (c != '{') { 66 replacement = Character.toString(c); 68 replaceIndex = 0; 69 return '$'; 70 } 71 72 StringBuffer buffer = new StringBuffer (); 74 boolean endReached = false; 75 while (!endReached) { 76 c = (char) super.read(); 77 endReached = c == -1 || c == '}'; 78 if (!endReached) { 79 buffer.append(c); 80 } 81 } 82 83 if (c == -1) { 84 throw new IOException ("EOF encountered but '}' was expected."); 85 } 86 87 String key = buffer.toString(); 88 replacement = getReplacement(key); 89 if (replacement != null && replacement.length() > 0) { 90 replaceIndex = 0; 91 } 92 return read(); 93 } 94 95 98 public final int read(char[] cbuf, int off, int len) throws IOException { 99 for (int i = 0; i < len; i++) { 100 final int ch = read(); 101 if (ch == -1) { 102 return i == 0 ? -1 : i; 103 } 104 cbuf[off + i] = (char) ch; 105 } 106 return len; 107 } 108 109 protected abstract String getReplacement(String key); 110 111 } 112 | Popular Tags |