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