1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.flatfile.util;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21
22 import org.apache.commons.io.input.CountingInputStream;
23
24 /**
25 * FilterInputStream that limits the data returned from the proxy.
26 * @version $Revision: 1301244 $ $Date: 2012-03-15 17:16:23 -0500 (Thu, 15 Mar 2012) $
27 */
28 public class ThresholdingInputStream extends CountingInputStream {
29 private static final int EOF = -1;
30
31 private final int maximum;
32 private boolean closed;
33
34 /**
35 * Create a new ThresholdingInputStream.
36 * @param in the filtered stream
37 * @param maximum length
38 */
39 public ThresholdingInputStream(InputStream in, int maximum) {
40 super(in);
41 this.maximum = maximum;
42 }
43
44 /*
45 * NOTICE: implementing all three read(...) methods such that corresponding
46 * super methods are called
47 */
48
49 /**
50 * {@inheritDoc}
51 */
52 public synchronized int read() throws IOException {
53 assertNotClosed();
54 if (getCount() >= maximum) {
55 return EOF;
56 }
57 return super.read();
58 }
59
60 /**
61 * {@inheritDoc}
62 */
63 public synchronized int read(byte[] b, int off, int len) throws IOException {
64 assertNotClosed();
65 int n = maximum - getCount();
66 return n == 0 ? EOF : super.read(b, off, n < len ? n : len);
67 }
68
69 /**
70 * {@inheritDoc}
71 */
72 public synchronized int read(byte[] b) throws IOException {
73 assertNotClosed();
74 int n = maximum - getCount();
75 if (n == 0) {
76 return EOF;
77 }
78 if (n < b.length) {
79 byte[] buf = new byte[n];
80 System.arraycopy(b, 0, buf, 0, n);
81 try {
82 return super.read(buf);
83 } finally {
84 System.arraycopy(buf, 0, b, 0, n);
85 }
86 }
87 return super.read(b);
88 }
89
90 /**
91 * {@inheritDoc}
92 */
93 public synchronized void close() throws IOException {
94 this.closed = true;
95 super.close();
96 }
97
98 /**
99 * Make sure the stream is not closed.
100 * @throws IOException if stream has been closed.
101 */
102 private synchronized void assertNotClosed() throws IOException {
103 if (closed) {
104 throw new IOException("Stream closed");
105 }
106 }
107 }