1 32 package org.apache.commons.httpclient.methods; 33 34 import java.io.ByteArrayOutputStream ; 35 import java.io.IOException ; 36 import java.io.InputStream ; 37 import java.io.OutputStream ; 38 39 import org.apache.commons.logging.Log; 40 import org.apache.commons.logging.LogFactory; 41 42 47 public class InputStreamRequestEntity implements RequestEntity { 48 49 53 public static final int CONTENT_LENGTH_AUTO = -2; 54 55 private static final Log LOG = LogFactory.getLog(InputStreamRequestEntity.class); 56 57 private long contentLength; 58 59 private InputStream content; 60 61 62 private byte[] buffer = null; 63 64 65 private String contentType; 66 67 72 public InputStreamRequestEntity(InputStream content) { 73 this(content, null); 74 } 75 76 82 public InputStreamRequestEntity(InputStream content, String contentType) { 83 this(content, CONTENT_LENGTH_AUTO, contentType); 84 } 85 86 93 public InputStreamRequestEntity(InputStream content, long contentLength) { 94 this(content, contentLength, null); 95 } 96 97 106 public InputStreamRequestEntity(InputStream content, long contentLength, String contentType) { 107 if (content == null) { 108 throw new IllegalArgumentException ("The content cannot be null"); 109 } 110 this.content = content; 111 this.contentLength = contentLength; 112 this.contentType = contentType; 113 } 114 115 118 public String getContentType() { 119 return contentType; 120 } 121 122 125 private void bufferContent() { 126 127 if (this.buffer != null) { 128 return; 130 } 131 if (this.content != null) { 132 try { 133 ByteArrayOutputStream tmp = new ByteArrayOutputStream (); 134 byte[] data = new byte[4096]; 135 int l = 0; 136 while ((l = this.content.read(data)) >= 0) { 137 tmp.write(data, 0, l); 138 } 139 this.buffer = tmp.toByteArray(); 140 this.content = null; 141 this.contentLength = buffer.length; 142 } catch (IOException e) { 143 LOG.error(e.getMessage(), e); 144 this.buffer = null; 145 this.content = null; 146 this.contentLength = 0; 147 } 148 } 149 } 150 151 157 public boolean isRepeatable() { 158 return buffer != null; 159 } 160 161 164 public void writeRequest(OutputStream out) throws IOException { 165 166 if (content != null) { 167 byte[] tmp = new byte[4096]; 168 int total = 0; 169 int i = 0; 170 while ((i = content.read(tmp)) >= 0) { 171 out.write(tmp, 0, i); 172 total += i; 173 } 174 } else if (buffer != null) { 175 out.write(buffer); 176 } else { 177 throw new IllegalStateException ("Content must be set before entity is written"); 178 } 179 } 180 181 185 public long getContentLength() { 186 if (contentLength == CONTENT_LENGTH_AUTO && buffer == null) { 187 bufferContent(); 188 } 189 return contentLength; 190 } 191 192 195 public InputStream getContent() { 196 return content; 197 } 198 199 } 200 | Popular Tags |