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   * ResponseContent is the most important interceptor for outgoing responses.
49   * It is responsible for delimiting content length by adding
50   * {@code Content-Length} or {@code Transfer-Content} headers based
51   * on the properties of the enclosed entity and the protocol version.
52   * This interceptor is required for correct functioning of server side protocol
53   * processors.
54   *
55   * @since 4.0
56   */
57  @Contract(threading = ThreadingBehavior.IMMUTABLE)
58  public class ResponseContent implements HttpResponseInterceptor {
59  
60      private final boolean overwrite;
61  
62      /**
63       * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding}
64       * will cause the interceptor to throw {@link ProtocolException} if already present in the
65       * response message.
66       */
67      public ResponseContent() {
68          this(false);
69      }
70  
71      /**
72       * Constructor that can be used to fine-tune behavior of this interceptor.
73       *
74       * @param overwrite If set to {@code true} the {@code Content-Length} and
75       * {@code Transfer-Encoding} headers will be created or updated if already present.
76       * If set to {@code false} the {@code Content-Length} and
77       * {@code Transfer-Encoding} headers will cause the interceptor to throw
78       * {@link ProtocolException} if already present in the response message.
79       *
80       * @since 4.2
81       */
82       public ResponseContent(final boolean overwrite) {
83           super();
84           this.overwrite = overwrite;
85      }
86  
87      /**
88       * Processes the response (possibly updating or inserting) Content-Length and Transfer-Encoding headers.
89       * @param response The HttpResponse to modify.
90       * @param context Unused.
91       * @throws ProtocolException If either the Content-Length or Transfer-Encoding headers are found.
92       * @throws IllegalArgumentException If the response is null.
93       */
94      @Override
95      public void process(final HttpResponse response, final EntityDetails entity, final HttpContext context)
96              throws HttpException, IOException {
97          Args.notNull(response, "HTTP response");
98          if (this.overwrite) {
99              response.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
100             response.removeHeaders(HttpHeaders.CONTENT_LENGTH);
101         } else {
102             if (response.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
103                 throw new ProtocolException("Transfer-encoding header already present");
104             }
105             if (response.containsHeader(HttpHeaders.CONTENT_LENGTH)) {
106                 throw new ProtocolException("Content-Length header already present");
107             }
108         }
109         final ProtocolVersion ver = context.getProtocolVersion();
110         if (entity != null) {
111             final long len = entity.getContentLength();
112             if (len >= 0 && !entity.isChunked()) {
113                 response.addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength()));
114             } else if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
115                 response.addHeader(HttpHeaders.TRANSFER_ENCODING, HeaderElements.CHUNKED_ENCODING);
116                 MessageSupport.addTrailerHeader(response, entity);
117             }
118             MessageSupport.addContentTypeHeader(response, entity);
119             MessageSupport.addContentEncodingHeader(response, entity);
120         } else {
121             final int status = response.getCode();
122             if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED) {
123                 response.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
124             }
125         }
126     }
127 
128 }