Skip to content

Commit

Permalink
Merge pull request square#1127 from square/jw/consolidate-response-bo…
Browse files Browse the repository at this point in the history
…dies

Consolidate response body specializations as inner classes.
  • Loading branch information
swankjesse committed Sep 26, 2015
2 parents f7b6595 + 8a70ac1 commit 7e6bd27
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 104 deletions.
61 changes: 0 additions & 61 deletions retrofit/src/main/java/retrofit/ExceptionCatchingRequestBody.java

This file was deleted.

43 changes: 0 additions & 43 deletions retrofit/src/main/java/retrofit/NoContentResponseBody.java

This file was deleted.

79 changes: 79 additions & 0 deletions retrofit/src/main/java/retrofit/OkHttpCall.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,14 @@
*/
package retrofit;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;

import static retrofit.Utils.closeQuietly;

Expand Down Expand Up @@ -157,4 +162,78 @@ public void cancel() {
rawCall.cancel();
}
}

static final class NoContentResponseBody extends ResponseBody {
private final MediaType contentType;
private final long contentLength;

NoContentResponseBody(MediaType contentType, long contentLength) {
this.contentType = contentType;
this.contentLength = contentLength;
}

@Override public MediaType contentType() {
return contentType;
}

@Override public long contentLength() throws IOException {
return contentLength;
}

@Override public BufferedSource source() throws IOException {
throw new IllegalStateException("Cannot read raw response body of a converted body.");
}
}

static final class ExceptionCatchingRequestBody extends ResponseBody {
private final ResponseBody delegate;
private IOException thrownException;

ExceptionCatchingRequestBody(ResponseBody delegate) {
this.delegate = delegate;
}

@Override public MediaType contentType() {
return delegate.contentType();
}

@Override public long contentLength() throws IOException {
try {
return delegate.contentLength();
} catch (IOException e) {
thrownException = e;
throw e;
}
}

@Override public BufferedSource source() throws IOException {
BufferedSource delegateSource;
try {
delegateSource = delegate.source();
} catch (IOException e) {
thrownException = e;
throw e;
}
return Okio.buffer(new ForwardingSource(delegateSource) {
@Override public long read(Buffer sink, long byteCount) throws IOException {
try {
return super.read(sink, byteCount);
} catch (IOException e) {
thrownException = e;
throw e;
}
}
});
}

@Override public void close() throws IOException {
delegate.close();
}

void throwIfCaught() throws IOException {
if (thrownException != null) {
throw thrownException;
}
}
}
}

0 comments on commit 7e6bd27

Please sign in to comment.