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.wss4j.stax.utils;
20  
21  import org.apache.xml.security.utils.I18n;
22  
23  import java.io.FilterInputStream;
24  import java.io.IOException;
25  import java.io.InputStream;
26  
27  /**
28   */
29  public final class LimitingInputStream extends FilterInputStream {
30  
31      private long limit;
32      private long count;
33  
34      public LimitingInputStream(InputStream in, long limit) {
35          super(in);
36          this.limit = limit;
37      }
38  
39      @Override
40      public int read() throws IOException {
41          int r = super.read();
42          if (r >= 0) {
43              incrementCountAndTestLimit(r);
44          }
45          return r;
46      }
47  
48      @Override
49      public int read(byte[] b) throws IOException {
50          return read(b, 0, b.length);
51      }
52  
53      @Override
54      public int read(byte[] b, int off, int len) throws IOException {
55          int r = super.read(b, off, len);
56          if (r >= 0) {
57              incrementCountAndTestLimit(r);
58          }
59          return r;
60      }
61  
62      private void incrementCountAndTestLimit(long read) throws IOException {
63          this.count += read;
64          if (this.count > this.limit) {
65              throw new IOException(I18n.getExceptionMessage("secureProcessing.inputStreamLimitReached", new Object[]{this.limit}));
66          }
67      }
68  }