View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.shared.filtering;
20  
21  import java.io.IOException;
22  import java.io.Reader;
23  
24  /**
25   * A reader that imposes a limit to the number of bytes that can be read from
26   * an underlying reader, simulating eof when this limit is reached.
27   *
28   * This stream can typically be used to constrain a client with regard to a readAheadLimit
29   * of an underlying stream, to avoid overrunning this limit and hence
30   * lose the opportunity do to reset.
31   */
32  public class BoundedReader extends Reader {
33  
34  	private final Reader target;
35  
36  	int pos = 0;
37  
38  	int readAheadLimit;
39  
40  	public BoundedReader(Reader target, int readAheadLimit) throws IOException {
41  		this.target = target;
42  		target.mark(readAheadLimit);
43  		this.readAheadLimit = readAheadLimit;
44  	}
45  
46  
47  	@Override public void close() throws IOException {
48  		target.close();
49  	}
50  
51  	@Override public void reset() throws IOException {
52  		pos = 0;
53  		target.reset();
54  	}
55  
56  	@Override public void mark(int readAheadLimit) throws IOException {
57  		this.readAheadLimit = readAheadLimit;
58  		target.mark(readAheadLimit);
59  	}
60  
61  	@Override public int read() throws IOException {
62  		if (pos >= readAheadLimit) return -1;
63  		pos++;
64  		return target.read();
65  	}
66  
67  	@Override public int read(char[] cbuf, int off, int len) throws IOException{
68  		int c;
69  		for (int i = 0; i < len; i++){
70  			c = read();
71  			if (c == -1) return i;
72  			cbuf[off + i] = (char) c;
73  		}
74  		return len;
75  	}
76  }