1 18 package org.apache.tools.ant.filters; 19 20 import java.io.IOException ; 21 import java.io.Reader ; 22 import org.apache.tools.ant.util.LineTokenizer; 23 import org.apache.tools.ant.types.Parameter; 24 25 37 public final class HeadFilter extends BaseParamFilterReader 38 implements ChainableReader { 39 40 private static final String LINES_KEY = "lines"; 41 42 43 private static final String SKIP_KEY = "skip"; 44 45 46 private long linesRead = 0; 47 48 49 private static final int DEFAULT_NUM_LINES = 10; 50 51 52 private long lines = DEFAULT_NUM_LINES; 53 54 55 private long skip = 0; 56 57 58 private LineTokenizer lineTokenizer = null; 59 60 61 private String line = null; 62 63 private int linePos = 0; 64 65 70 public HeadFilter() { 71 super(); 72 } 73 74 80 public HeadFilter(final Reader in) { 81 super(in); 82 lineTokenizer = new LineTokenizer(); 83 lineTokenizer.setIncludeDelims(true); 84 } 85 86 98 public int read() throws IOException { 99 if (!getInitialized()) { 100 initialize(); 101 setInitialized(true); 102 } 103 104 while (line == null || line.length() == 0) { 105 line = lineTokenizer.getToken(in); 106 if (line == null) { 107 return -1; 108 } 109 line = headFilter(line); 110 linePos = 0; 111 } 112 113 int ch = line.charAt(linePos); 114 linePos++; 115 if (linePos == line.length()) { 116 line = null; 117 } 118 return ch; 119 } 120 121 126 public void setLines(final long lines) { 127 this.lines = lines; 128 } 129 130 135 private long getLines() { 136 return lines; 137 } 138 139 144 public void setSkip(final long skip) { 145 this.skip = skip; 146 } 147 148 153 private long getSkip() { 154 return skip; 155 } 156 157 167 public Reader chain(final Reader rdr) { 168 HeadFilter newFilter = new HeadFilter(rdr); 169 newFilter.setLines(getLines()); 170 newFilter.setSkip(getSkip()); 171 newFilter.setInitialized(true); 172 return newFilter; 173 } 174 175 180 private void initialize() { 181 Parameter[] params = getParameters(); 182 if (params != null) { 183 for (int i = 0; i < params.length; i++) { 184 if (LINES_KEY.equals(params[i].getName())) { 185 lines = new Long (params[i].getValue()).longValue(); 186 continue; 187 } 188 if (SKIP_KEY.equals(params[i].getName())) { 189 skip = new Long (params[i].getValue()).longValue(); 190 continue; 191 } 192 } 193 } 194 } 195 196 199 private String headFilter(String line) { 200 linesRead++; 201 if (skip > 0) { 202 if ((linesRead - 1) < skip) { 203 return null; 204 } 205 } 206 207 if (lines > 0) { 208 if (linesRead > (lines + skip)) { 209 return null; 210 } 211 } 212 return line; 213 } 214 } 215 | Popular Tags |