1 /*
2 * Copyright (C) The Apache Software Foundation. All rights reserved.
3 *
4 * This software is published under the terms of the Apache Software License
5 * version 1.1, a copy of which has been included with this distribution in
6 * the LICENSE file.
7 */
8 package org.apache.james.smtpserver;
9
10 import java.io.IOException;
11 import java.io.InputStream;
12
13 /***
14 * Wraps an underlying input stream, limiting the allowable size
15 * of incoming data. The size limit is configured in the conf file,
16 * and when the limit is reached, a MessageSizeException is thrown.
17 * @author Matthew Pangaro <mattp@lokitech.com>
18 */
19 public class SizeLimitedInputStream extends InputStream {
20 /***
21 * Maximum number of bytes to read.
22 */
23 private long maxmessagesize = 0;
24 /***
25 * Running total of bytes read from wrapped stream.
26 */
27 private long bytesread = 0;
28
29 /***
30 * InputStream that will be wrapped.
31 */
32 private InputStream in = null;
33
34 /***
35 * Constructor for the stream. Wraps an underlying stream.
36 * @param in InputStream to use as basis for new Stream.
37 * @param maxmessagesize Message size limit, in Kilobytes
38 */
39 public SizeLimitedInputStream(InputStream in, long maxmessagesize) {
40 this.in = in;
41 this.maxmessagesize = maxmessagesize;
42 }
43
44 /***
45 * Overrides the read method of InputStream to call the read() method of the
46 * wrapped input stream.
47 * @throws IOException Throws a MessageSizeException, which is a sub-type of IOException
48 * @return Returns the number of bytes read.
49 */
50 public int read(byte[] b, int off, int len) throws IOException {
51 int l = in.read(b, off, len);
52
53 bytesread += l;
54
55 if (maxmessagesize > 0 && bytesread > maxmessagesize) {
56 throw new MessageSizeException();
57 }
58
59 return l;
60 }
61
62 /***
63 * Overrides the read method of InputStream to call the read() method of the
64 * wrapped input stream.
65 * @throws IOException Throws a MessageSizeException, which is a sub-type of IOException.
66 * @return Returns the int character value of the byte read.
67 */
68 public int read() throws IOException {
69 if (maxmessagesize > 0 && bytesread <= maxmessagesize) {
70 bytesread++;
71 return in.read();
72 } else {
73 throw new MessageSizeException();
74 }
75 }
76 }
This page was automatically generated by Maven