source: contrib/MailArchiver/sources/vendor/mime4j/apache-mime4j-0.7-SNAPSHOT-20110327.010440-17/core/src/main/java/org/apache/james/mime4j/io/LimitedInputStream.java @ 6785

Revision 6785, 2.3 KB checked in by rafaelraymundo, 12 years ago (diff)

Ticket #2946 - Liberado codigo do MailArchiver?. Documentação na subpasta DOCS.

Line 
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
20package org.apache.james.mime4j.io;
21
22import java.io.InputStream;
23import java.io.IOException;
24
25public class LimitedInputStream extends PositionInputStream {
26
27    private final long limit;
28
29    public LimitedInputStream(InputStream instream, long limit) {
30        super(instream);
31        if (limit < 0) {
32            throw new IllegalArgumentException("Limit may not be negative");
33        }
34        this.limit = limit;
35    }
36
37    private void enforceLimit() throws IOException {
38        if (position >= limit) {
39            throw new IOException("Input stream limit exceeded");
40        }
41    }
42   
43    @Override
44    public int read() throws IOException {
45        enforceLimit();
46        return super.read();
47    }
48
49    @Override
50    public int read(byte b[], int off, int len) throws IOException {
51        enforceLimit();
52        len = Math.min(len, getBytesLeft());
53        return super.read(b, off, len);
54    }
55
56    @Override
57    public long skip(long n) throws IOException {
58        enforceLimit();
59        n = Math.min(n, getBytesLeft());
60        return super.skip(n);
61    }
62
63    private int getBytesLeft() {
64        return (int)Math.min(Integer.MAX_VALUE, limit - position);
65    }
66   
67}
Note: See TracBrowser for help on using the repository browser.