1/*
2 * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/module-main/src/main/java/org/apache/http/impl/entity/StrictContentLengthStrategy.java $
3 * $Revision: 573949 $
4 * $Date: 2007-09-08 22:46:25 -0700 (Sat, 08 Sep 2007) $
5 *
6 * ====================================================================
7 * Licensed to the Apache Software Foundation (ASF) under one
8 * or more contributor license agreements.  See the NOTICE file
9 * distributed with this work for additional information
10 * regarding copyright ownership.  The ASF licenses this file
11 * to you under the Apache License, Version 2.0 (the
12 * "License"); you may not use this file except in compliance
13 * with the License.  You may obtain a copy of the License at
14 *
15 *   http://www.apache.org/licenses/LICENSE-2.0
16 *
17 * Unless required by applicable law or agreed to in writing,
18 * software distributed under the License is distributed on an
19 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
20 * KIND, either express or implied.  See the License for the
21 * specific language governing permissions and limitations
22 * under the License.
23 * ====================================================================
24 *
25 * This software consists of voluntary contributions made by many
26 * individuals on behalf of the Apache Software Foundation.  For more
27 * information on the Apache Software Foundation, please see
28 * <http://www.apache.org/>.
29 *
30 */
31
32package org.apache.http.impl.entity;
33
34import org.apache.http.Header;
35import org.apache.http.HttpException;
36import org.apache.http.HttpMessage;
37import org.apache.http.HttpVersion;
38import org.apache.http.ProtocolException;
39import org.apache.http.entity.ContentLengthStrategy;
40import org.apache.http.protocol.HTTP;
41
42/**
43 * The strict implementation of the content length strategy.
44 * <p>
45 * This entity generator comforms to the entity transfer rules outlined in the
46 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec4.4">Section 4.4</a>,
47 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6">Section 3.6</a>,
48 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.41">Section 14.41</a>
49 * and <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec14.13">Section 14.13</a>
50 * of <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.txt">RFC 2616</a>
51 * </p>
52 * <h>4.4 Message Length</h>
53 * <p>
54 * The transfer-length of a message is the length of the message-body as it appears in the
55 * message; that is, after any transfer-codings have been applied. When a message-body is
56 * included with a message, the transfer-length of that body is determined by one of the
57 * following (in order of precedence):
58 * </p>
59 * <p>
60 * 1.Any response message which "MUST NOT" include a message-body (such as the 1xx, 204,
61 * and 304 responses and any response to a HEAD request) is always terminated by the first
62 * empty line after the header fields, regardless of the entity-header fields present in the
63 * message.
64 * </p>
65 * <p>
66 * 2.If a Transfer-Encoding header field (section 14.41) is present and has any value other
67 * than "identity", then the transfer-length is defined by use of the "chunked" transfer-
68 * coding (section 3.6), unless the message is terminated by closing the connection.
69 * </p>
70 * <p>
71 * 3.If a Content-Length header field (section 14.13) is present, its decimal value in
72 * OCTETs represents both the entity-length and the transfer-length. The Content-Length
73 * header field MUST NOT be sent if these two lengths are different (i.e., if a
74 * Transfer-Encoding
75 * </p>
76 * <pre>
77 *    header field is present). If a message is received with both a
78 *    Transfer-Encoding header field and a Content-Length header field,
79 *    the latter MUST be ignored.
80 * </pre>
81 * <p>
82 * 4.If the message uses the media type "multipart/byteranges", and the ransfer-length is not
83 * otherwise specified, then this self- elimiting media type defines the transfer-length.
84 * This media type UST NOT be used unless the sender knows that the recipient can arse it; the
85 * presence in a request of a Range header with ultiple byte- range specifiers from a 1.1
86 * client implies that the lient can parse multipart/byteranges responses.
87 * </p>
88 * <pre>
89 *     A range header might be forwarded by a 1.0 proxy that does not
90 *     understand multipart/byteranges; in this case the server MUST
91 *     delimit the message using methods defined in items 1,3 or 5 of
92 *     this section.
93 * </pre>
94 * <p>
95 * 5.By the server closing the connection. (Closing the connection cannot be used to indicate
96 * the end of a request body, since that would leave no possibility for the server to send back
97 * a response.)
98 * </p>
99 * <p>
100 * For compatibility with HTTP/1.0 applications, HTTP/1.1 requests containing a message-body
101 * MUST include a valid Content-Length header field unless the server is known to be HTTP/1.1
102 * compliant. If a request contains a message-body and a Content-Length is not given, the
103 * server SHOULD respond with 400 (bad request) if it cannot determine the length of the
104 * message, or with 411 (length required) if it wishes to insist on receiving a valid
105 * Content-Length.
106 * </p>
107 * <p>All HTTP/1.1 applications that receive entities MUST accept the "chunked" transfer-coding
108 * (section 3.6), thus allowing this mechanism to be used for messages when the message
109 * length cannot be determined in advance.
110 * </p>
111 * <h>3.6 Transfer Codings</h>
112 * <p>
113 * Transfer-coding values are used to indicate an encoding transformation that
114 * has been, can be, or may need to be applied to an entity-body in order to ensure
115 * "safe transport" through the network. This differs from a content coding in that
116 * the transfer-coding is a property of the message, not of the original entity.
117 * </p>
118 * <pre>
119 * transfer-coding         = "chunked" | transfer-extension
120 * transfer-extension      = token *( ";" parameter )
121 * </pre>
122 * <p>
123 * Parameters are in the form of attribute/value pairs.
124 * </p>
125 * <pre>
126 * parameter               = attribute "=" value
127 * attribute               = token
128 * value                   = token | quoted-string
129 * </pre>
130 * <p>
131 * All transfer-coding values are case-insensitive. HTTP/1.1 uses transfer-coding values in
132 * the TE header field (section 14.39) and in the Transfer-Encoding header field (section 14.41).
133 * </p>
134 * <p>
135 * Whenever a transfer-coding is applied to a message-body, the set of transfer-codings MUST
136 * include "chunked", unless the message is terminated by closing the connection. When the
137 * "chunked" transfer-coding is used, it MUST be the last transfer-coding applied to the
138 * message-body. The "chunked" transfer-coding MUST NOT be applied more than once to a
139 * message-body. These rules allow the recipient to determine the transfer-length of the
140 * message (section 4.4).
141 * </p>
142 * <h>14.41 Transfer-Encoding</h>
143 * <p>
144 * The Transfer-Encoding general-header field indicates what (if any) type of transformation has
145 * been applied to the message body in order to safely transfer it between the sender and the
146 * recipient. This differs from the content-coding in that the transfer-coding is a property of
147 * the message, not of the entity.
148 * </p>
149 * <pre>
150 *   Transfer-Encoding       = "Transfer-Encoding" ":" 1#transfer-coding
151 * </pre>
152 * <p>
153 * If multiple encodings have been applied to an entity, the transfer- codings MUST be listed in
154 * the order in which they were applied. Additional information about the encoding parameters
155 * MAY be provided by other entity-header fields not defined by this specification.
156 * </p>
157 * <h>14.13 Content-Length</h>
158 * <p>
159 * The Content-Length entity-header field indicates the size of the entity-body, in decimal
160 * number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of
161 * the entity-body that would have been sent had the request been a GET.
162 * </p>
163 * <pre>
164 *   Content-Length    = "Content-Length" ":" 1*DIGIT
165 * </pre>
166 * <p>
167 * Applications SHOULD use this field to indicate the transfer-length of the message-body,
168 * unless this is prohibited by the rules in section 4.4.
169 * </p>
170 *
171 * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
172 *
173 * @version $Revision: 573949 $
174 *
175 * @since 4.0
176 */
177public class StrictContentLengthStrategy implements ContentLengthStrategy {
178
179    public StrictContentLengthStrategy() {
180        super();
181    }
182
183    public long determineLength(final HttpMessage message) throws HttpException {
184        if (message == null) {
185            throw new IllegalArgumentException("HTTP message may not be null");
186        }
187        // Although Transfer-Encoding is specified as a list, in practice
188        // it is either missing or has the single value "chunked". So we
189        // treat it as a single-valued header here.
190        Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
191        Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
192        if (transferEncodingHeader != null) {
193            String s = transferEncodingHeader.getValue();
194            if (HTTP.CHUNK_CODING.equalsIgnoreCase(s)) {
195                if (message.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) {
196                    throw new ProtocolException(
197                            "Chunked transfer encoding not allowed for " +
198                            message.getProtocolVersion());
199                }
200                return CHUNKED;
201            } else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(s)) {
202                return IDENTITY;
203            } else {
204                throw new ProtocolException(
205                        "Unsupported transfer encoding: " + s);
206            }
207        } else if (contentLengthHeader != null) {
208            String s = contentLengthHeader.getValue();
209            try {
210                long len = Long.parseLong(s);
211                return len;
212            } catch (NumberFormatException e) {
213                throw new ProtocolException("Invalid content length: " + s);
214            }
215        } else {
216            return IDENTITY;
217        }
218    }
219
220}
221