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 17 package libcore.net.http; 18 19 import java.io.ByteArrayOutputStream; 20 import java.io.IOException; 21 import java.io.OutputStream; 22 import java.util.Arrays; 23 24 /** 25 * An HTTP request body that's completely buffered in memory. This allows 26 * the post body to be transparently re-sent if the HTTP request must be 27 * sent multiple times. 28 */ 29 final class RetryableOutputStream extends AbstractHttpOutputStream { 30 private final int limit; 31 private final ByteArrayOutputStream content; 32 RetryableOutputStream(int limit)33 public RetryableOutputStream(int limit) { 34 this.limit = limit; 35 this.content = new ByteArrayOutputStream(limit); 36 } 37 RetryableOutputStream()38 public RetryableOutputStream() { 39 this.limit = -1; 40 this.content = new ByteArrayOutputStream(); 41 } 42 close()43 @Override public synchronized void close() throws IOException { 44 if (closed) { 45 return; 46 } 47 closed = true; 48 if (content.size() < limit) { 49 throw new IOException("content-length promised " 50 + limit + " bytes, but received " + content.size()); 51 } 52 } 53 write(byte[] buffer, int offset, int count)54 @Override public synchronized void write(byte[] buffer, int offset, int count) 55 throws IOException { 56 checkNotClosed(); 57 Arrays.checkOffsetAndCount(buffer.length, offset, count); 58 if (limit != -1 && content.size() > limit - count) { 59 throw new IOException("exceeded content-length limit of " + limit + " bytes"); 60 } 61 content.write(buffer, offset, count); 62 } 63 contentLength()64 public synchronized int contentLength() throws IOException { 65 close(); 66 return content.size(); 67 } 68 writeToSocket(OutputStream socketOut)69 public void writeToSocket(OutputStream socketOut) throws IOException { 70 content.writeTo(socketOut); 71 } 72 } 73