001/*
002 * ====================================================================
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *   http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing,
014 * software distributed under the License is distributed on an
015 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
016 * KIND, either express or implied.  See the License for the
017 * specific language governing permissions and limitations
018 * under the License.
019 * ====================================================================
020 *
021 * This software consists of voluntary contributions made by many
022 * individuals on behalf of the Apache Software Foundation.  For more
023 * information on the Apache Software Foundation, please see
024 * <http://www.apache.org/>.
025 *
026 */
027
028package org.apache.http.protocol;
029
030import java.io.IOException;
031
032import org.apache.http.HttpEntity;
033import org.apache.http.HttpException;
034import org.apache.http.HttpResponse;
035import org.apache.http.HttpResponseInterceptor;
036import org.apache.http.HttpStatus;
037import org.apache.http.HttpVersion;
038import org.apache.http.ProtocolException;
039import org.apache.http.ProtocolVersion;
040import org.apache.http.annotation.ThreadingBehavior;
041import org.apache.http.annotation.Contract;
042import org.apache.http.util.Args;
043
044/**
045 * ResponseContent is the most important interceptor for outgoing responses.
046 * It is responsible for delimiting content length by adding
047 * {@code Content-Length} or {@code Transfer-Content} headers based
048 * on the properties of the enclosed entity and the protocol version.
049 * This interceptor is required for correct functioning of server side protocol
050 * processors.
051 *
052 * @since 4.0
053 */
054@Contract(threading = ThreadingBehavior.IMMUTABLE)
055public class ResponseContent implements HttpResponseInterceptor {
056
057    private final boolean overwrite;
058
059    /**
060     * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding}
061     * will cause the interceptor to throw {@link ProtocolException} if already present in the
062     * response message.
063     */
064    public ResponseContent() {
065        this(false);
066    }
067
068    /**
069     * Constructor that can be used to fine-tune behavior of this interceptor.
070     *
071     * @param overwrite If set to {@code true} the {@code Content-Length} and
072     * {@code Transfer-Encoding} headers will be created or updated if already present.
073     * If set to {@code false} the {@code Content-Length} and
074     * {@code Transfer-Encoding} headers will cause the interceptor to throw
075     * {@link ProtocolException} if already present in the response message.
076     *
077     * @since 4.2
078     */
079     public ResponseContent(final boolean overwrite) {
080         super();
081         this.overwrite = overwrite;
082    }
083
084    /**
085     * Processes the response (possibly updating or inserting) Content-Length and Transfer-Encoding headers.
086     * @param response The HttpResponse to modify.
087     * @param context Unused.
088     * @throws ProtocolException If either the Content-Length or Transfer-Encoding headers are found.
089     * @throws IllegalArgumentException If the response is null.
090     */
091    @Override
092    public void process(final HttpResponse response, final HttpContext context)
093            throws HttpException, IOException {
094        Args.notNull(response, "HTTP response");
095        if (this.overwrite) {
096            response.removeHeaders(HTTP.TRANSFER_ENCODING);
097            response.removeHeaders(HTTP.CONTENT_LEN);
098        } else {
099            if (response.containsHeader(HTTP.TRANSFER_ENCODING)) {
100                throw new ProtocolException("Transfer-encoding header already present");
101            }
102            if (response.containsHeader(HTTP.CONTENT_LEN)) {
103                throw new ProtocolException("Content-Length header already present");
104            }
105        }
106        final ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
107        final HttpEntity entity = response.getEntity();
108        if (entity != null) {
109            final long len = entity.getContentLength();
110            if (entity.isChunked() && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
111                response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
112            } else if (len >= 0) {
113                response.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
114            }
115            // Specify a content type if known
116            if (entity.getContentType() != null && !response.containsHeader(
117                    HTTP.CONTENT_TYPE )) {
118                response.addHeader(entity.getContentType());
119            }
120            // Specify a content encoding if known
121            if (entity.getContentEncoding() != null && !response.containsHeader(
122                    HTTP.CONTENT_ENCODING)) {
123                response.addHeader(entity.getContentEncoding());
124            }
125        } else {
126            final int status = response.getStatusLine().getStatusCode();
127            if (status != HttpStatus.SC_NO_CONTENT
128                    && status != HttpStatus.SC_NOT_MODIFIED
129                    && status != HttpStatus.SC_RESET_CONTENT) {
130                response.addHeader(HTTP.CONTENT_LEN, "0");
131            }
132        }
133    }
134
135}