KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > server > http > ContentLengthStream


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * 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 JavaDoc;
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 int _length;
45
46   void init(ReadStream next, int length)
47   {
48     _next = next;
49     _length = length;
50   }
51
52   public boolean canRead()
53   {
54     return true;
55   }
56
57   /**
58    * Reads from the buffer, limiting to the content length.
59    *
60    * @param buffer the buffer containing the results.
61    * @param offset the offset into the result buffer
62    * @param length the length of the buffer.
63    *
64    * @return the number of bytes read or -1 for the end of the file.
65    */

66   public int read(byte []buffer, int offset, int length) throws IOException JavaDoc
67   {
68     if (_length < length)
69       length = _length;
70
71     if (length <= 0)
72       return -1;
73
74     int len = _next.read(buffer, offset, length);
75       
76     if (len > 0) {
77       _length -= len;
78     }
79     else
80       _length = -1;
81
82     return len;
83   }
84
85   public int getAvailable()
86     throws IOException JavaDoc
87   {
88     int available = _next.available();
89       
90     if (_length <= 0)
91       return 0;
92     else if (_length < available)
93       return _length;
94     else
95       return available;
96   }
97 }
98
Popular Tags