01: /*
02: * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
03: *
04: * This file is part of Resin(R) Open Source
05: *
06: * Each copy or derived work must preserve the copyright notice and this
07: * notice unmodified.
08: *
09: * Resin Open Source is free software; you can redistribute it and/or modify
10: * it under the terms of the GNU General Public License as published by
11: * the Free Software Foundation; either version 2 of the License, or
12: * (at your option) any later version.
13: *
14: * Resin Open Source is distributed in the hope that it will be useful,
15: * but WITHOUT ANY WARRANTY; without even the implied warranty of
16: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17: * of NON-INFRINGEMENT. See the GNU General Public License for more
18: * details.
19: *
20: * You should have received a copy of the GNU General Public License
21: * along with Resin Open Source; if not, write to the
22: * Free SoftwareFoundation, Inc.
23: * 59 Temple Place, Suite 330
24: * Boston, MA 02111-1307 USA
25: *
26: * @author Scott Ferguson
27: */
28:
29: package com.caucho.server.http;
30:
31: import com.caucho.vfs.ReadStream;
32: import com.caucho.vfs.StreamImpl;
33:
34: import java.io.IOException;
35:
36: /**
37: * Filter so POST readers can only read data up to the content length
38: */
39: public class ContentLengthStream extends StreamImpl {
40: // the underlying stream
41: private ReadStream _next;
42:
43: // bytes available in the post contents
44: private long _length;
45:
46: void init(ReadStream next, long length) {
47: _next = next;
48: _length = length;
49: }
50:
51: public boolean canRead() {
52: return true;
53: }
54:
55: /**
56: * Reads from the buffer, limiting to the content length.
57: *
58: * @param buffer the buffer containing the results.
59: * @param offset the offset into the result buffer
60: * @param length the length of the buffer.
61: *
62: * @return the number of bytes read or -1 for the end of the file.
63: */
64: public int read(byte[] buffer, int offset, int length)
65: throws IOException {
66: if (_length < length)
67: length = (int) _length;
68:
69: if (length <= 0)
70: return -1;
71:
72: int len = _next.read(buffer, offset, length);
73:
74: if (len > 0) {
75: _length -= len;
76: } else
77: _length = -1;
78:
79: return len;
80: }
81:
82: public int getAvailable() throws IOException {
83: int available = _next.available();
84:
85: if (_length <= 0)
86: return 0;
87: else if (_length < available)
88: return (int) _length;
89: else
90: return available;
91: }
92: }
|