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.BufferedSink;
22import okio.Deadline;
23import okio.OkBuffer;
24import okio.Sink;
25
26import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
27
28/**
29 * An HTTP request body that's completely buffered in memory. This allows
30 * the post body to be transparently re-sent if the HTTP request must be
31 * sent multiple times.
32 */
33final class RetryableSink implements Sink {
34  private boolean closed;
35  private final int limit;
36  private final OkBuffer content = new OkBuffer();
37
38  public RetryableSink(int limit) {
39    this.limit = limit;
40  }
41
42  public RetryableSink() {
43    this(-1);
44  }
45
46  @Override public void close() throws IOException {
47    if (closed) return;
48    closed = true;
49    if (content.size() < limit) {
50      throw new ProtocolException(
51          "content-length promised " + limit + " bytes, but received " + content.size());
52    }
53  }
54
55  @Override public void write(OkBuffer source, long byteCount) throws IOException {
56    if (closed) throw new IllegalStateException("closed");
57    checkOffsetAndCount(source.size(), 0, byteCount);
58    if (limit != -1 && content.size() > limit - byteCount) {
59      throw new ProtocolException("exceeded content-length limit of " + limit + " bytes");
60    }
61    content.write(source, byteCount);
62  }
63
64  @Override public void flush() throws IOException {
65  }
66
67  @Override public Sink deadline(Deadline deadline) {
68    return this;
69  }
70
71  public long contentLength() throws IOException {
72    return content.size();
73  }
74
75  public void writeToSocket(BufferedSink socketOut) throws IOException {
76    // Clone the content; otherwise we won't have data to retry.
77    socketOut.write(content.clone(), content.size());
78  }
79}
80