1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.squareup.okhttp.internal.http;
18
19import java.io.IOException;
20import java.net.ProtocolException;
21import okio.Buffer;
22import okio.Sink;
23import okio.Timeout;
24
25import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
26
27/**
28 * An HTTP request body that's completely buffered in memory. This allows
29 * the post body to be transparently re-sent if the HTTP request must be
30 * sent multiple times.
31 */
32public final class RetryableSink implements Sink {
33  private boolean closed;
34  private final int limit;
35  private final Buffer content = new Buffer();
36
37  public RetryableSink(int limit) {
38    this.limit = limit;
39  }
40
41  public RetryableSink() {
42    this(-1);
43  }
44
45  @Override public void close() throws IOException {
46    if (closed) return;
47    closed = true;
48    if (content.size() < limit) {
49      throw new ProtocolException(
50          "content-length promised " + limit + " bytes, but received " + content.size());
51    }
52  }
53
54  @Override public void write(Buffer source, long byteCount) throws IOException {
55    if (closed) throw new IllegalStateException("closed");
56    checkOffsetAndCount(source.size(), 0, byteCount);
57    if (limit != -1 && content.size() > limit - byteCount) {
58      throw new ProtocolException("exceeded content-length limit of " + limit + " bytes");
59    }
60    content.write(source, byteCount);
61  }
62
63  @Override public void flush() throws IOException {
64  }
65
66  @Override public Timeout timeout() {
67    return Timeout.NONE;
68  }
69
70  public long contentLength() throws IOException {
71    return content.size();
72  }
73
74  public void writeToSocket(Sink socketOut) throws IOException {
75    // Copy the content; otherwise we won't have data to retry.
76    Buffer buffer = new Buffer();
77    content.copyTo(buffer, 0, content.size());
78    socketOut.write(buffer, buffer.size());
79  }
80}
81