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 an underlying reader, simulating eof when
26   * this limit is reached. This stream can typically be used to constrain a client with regard to a readAheadLimit of an
27   * underlying stream, to avoid overrunning this limit and hence lose the opportunity do to reset.
28   */
29  public class BoundedReader extends Reader {
30  
31      private final Reader target;
32  
33      int pos = 0;
34  
35      int readAheadLimit;
36  
37      /**
38       * @param target {@link Reader}
39       * @param readAheadLimit read ahead limit.
40       * @throws IOException in case of a failure.
41       */
42      public BoundedReader(Reader target, int readAheadLimit) throws IOException {
43          this.target = target;
44          target.mark(readAheadLimit);
45          this.readAheadLimit = readAheadLimit;
46      }
47  
48      @Override
49      public void close() throws IOException {
50          target.close();
51      }
52  
53      @Override
54      public void reset() throws IOException {
55          pos = 0;
56          target.reset();
57      }
58  
59      @Override
60      public void mark(int theReadAheadLimit) throws IOException {
61          this.readAheadLimit = theReadAheadLimit;
62          target.mark(theReadAheadLimit);
63      }
64  
65      @Override
66      public int read() throws IOException {
67          if (pos >= readAheadLimit) {
68              return -1;
69          }
70          pos++;
71          return target.read();
72      }
73  
74      @Override
75      public int read(char[] cbuf, int off, int len) throws IOException {
76          int c;
77          for (int i = 0; i < len; i++) {
78              c = read();
79              if (c == -1) {
80                  return i;
81              }
82              cbuf[off + i] = (char) c;
83          }
84          return len;
85      }
86  }