001/*
002 * Copyright 2002-2014 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.http.client;
018
019import java.io.IOException;
020import java.io.OutputStream;
021
022import org.springframework.http.HttpHeaders;
023import org.springframework.util.Assert;
024
025/**
026 * Abstract base for {@link ClientHttpRequest} that makes sure that headers
027 * and body are not written multiple times.
028 *
029 * @author Arjen Poutsma
030 * @since 3.0
031 */
032public abstract class AbstractClientHttpRequest implements ClientHttpRequest {
033
034        private final HttpHeaders headers = new HttpHeaders();
035
036        private boolean executed = false;
037
038
039        @Override
040        public final HttpHeaders getHeaders() {
041                return (this.executed ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);
042        }
043
044        @Override
045        public final OutputStream getBody() throws IOException {
046                assertNotExecuted();
047                return getBodyInternal(this.headers);
048        }
049
050        @Override
051        public final ClientHttpResponse execute() throws IOException {
052                assertNotExecuted();
053                ClientHttpResponse result = executeInternal(this.headers);
054                this.executed = true;
055                return result;
056        }
057
058        /**
059         * Assert that this request has not been {@linkplain #execute() executed} yet.
060         * @throws IllegalStateException if this request has been executed
061         */
062        protected void assertNotExecuted() {
063                Assert.state(!this.executed, "ClientHttpRequest already executed");
064        }
065
066
067        /**
068         * Abstract template method that returns the body.
069         * @param headers the HTTP headers
070         * @return the body output stream
071         */
072        protected abstract OutputStream getBodyInternal(HttpHeaders headers) throws IOException;
073
074        /**
075         * Abstract template method that writes the given headers and content to the HTTP request.
076         * @param headers the HTTP headers
077         * @return the response object for the executed request
078         */
079        protected abstract ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException;
080
081}