View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.http.protocol;
29  
30  import java.io.IOException;
31  
32  import org.apache.hc.core5.annotation.Contract;
33  import org.apache.hc.core5.annotation.ThreadingBehavior;
34  import org.apache.hc.core5.http.EntityDetails;
35  import org.apache.hc.core5.http.HeaderElements;
36  import org.apache.hc.core5.http.HttpException;
37  import org.apache.hc.core5.http.HttpHeaders;
38  import org.apache.hc.core5.http.HttpResponse;
39  import org.apache.hc.core5.http.HttpResponseInterceptor;
40  import org.apache.hc.core5.http.HttpStatus;
41  import org.apache.hc.core5.http.HttpVersion;
42  import org.apache.hc.core5.http.ProtocolException;
43  import org.apache.hc.core5.http.ProtocolVersion;
44  import org.apache.hc.core5.http.message.MessageSupport;
45  import org.apache.hc.core5.util.Args;
46  
47  /**
48   * This response interceptor is responsible for delimiting the message content
49   * by adding {@code Content-Length} or {@code Transfer-Content} headers based
50   * on the properties of the enclosed entity and the protocol version.
51   * <p>
52   * This interceptor is essential for the HTTP protocol conformance and
53   * the correct operation of the server-side message processing pipeline.
54   * </p>
55   *
56   * @since 4.0
57   */
58  @Contract(threading = ThreadingBehavior.IMMUTABLE)
59  public class ResponseContent implements HttpResponseInterceptor {
60  
61      public static final ResponseContent INSTANCE = new ResponseContent();
62  
63      private final boolean overwrite;
64  
65      /**
66       * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding}
67       * will cause the interceptor to throw {@link ProtocolException} if already present in the
68       * response message.
69       */
70      public ResponseContent() {
71          this(false);
72      }
73  
74      /**
75       * Constructor that can be used to fine-tune behavior of this interceptor.
76       *
77       * @param overwrite If set to {@code true} the {@code Content-Length} and
78       * {@code Transfer-Encoding} headers will be created or updated if already present.
79       * If set to {@code false} the {@code Content-Length} and
80       * {@code Transfer-Encoding} headers will cause the interceptor to throw
81       * {@link ProtocolException} if already present in the response message.
82       *
83       * @since 4.2
84       */
85       public ResponseContent(final boolean overwrite) {
86           super();
87           this.overwrite = overwrite;
88      }
89  
90      /**
91       * Processes the response (possibly updating or inserting) Content-Length and Transfer-Encoding headers.
92       * @param response The HttpResponse to modify.
93       * @param context Unused.
94       * @throws ProtocolException If either the Content-Length or Transfer-Encoding headers are found.
95       * @throws IllegalArgumentException If the response is null.
96       */
97      @Override
98      public void process(final HttpResponse response, final EntityDetails entity, final HttpContext context)
99              throws HttpException, IOException {
100         Args.notNull(response, "HTTP response");
101         if (this.overwrite) {
102             response.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
103             response.removeHeaders(HttpHeaders.CONTENT_LENGTH);
104         } else {
105             if (response.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
106                 throw new ProtocolException("Transfer-encoding header already present");
107             }
108             if (response.containsHeader(HttpHeaders.CONTENT_LENGTH)) {
109                 throw new ProtocolException("Content-Length header already present");
110             }
111         }
112         final ProtocolVersion ver = context.getProtocolVersion();
113         if (entity != null) {
114             final long len = entity.getContentLength();
115             if (len >= 0 && !entity.isChunked()) {
116                 response.addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength()));
117             } else if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
118                 response.addHeader(HttpHeaders.TRANSFER_ENCODING, HeaderElements.CHUNKED_ENCODING);
119                 MessageSupport.addTrailerHeader(response, entity);
120             }
121             MessageSupport.addContentTypeHeader(response, entity);
122             MessageSupport.addContentEncodingHeader(response, entity);
123         } else {
124             final int status = response.getCode();
125             if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED) {
126                 response.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
127             }
128         }
129     }
130 
131 }