1 45 package org.exolab.jms.net.http; 46 47 import java.io.IOException ; 48 import java.io.OutputStream ; 49 import java.net.HttpURLConnection ; 50 import java.net.URL ; 51 import java.net.URLConnection ; 52 53 import org.apache.commons.logging.Log; 54 import org.apache.commons.logging.LogFactory; 55 56 57 63 class HTTPOutputStream extends OutputStream { 64 65 68 private final String _id; 69 70 73 private final URL _url; 74 75 78 private final HTTPRequestInfo _info; 79 80 83 private final byte[] _data; 84 85 88 private int _index; 89 90 93 private static final Log _log = LogFactory.getLog(HTTPOutputStream.class); 94 95 96 104 public HTTPOutputStream(String id, URL url, int size, HTTPRequestInfo info) { 105 _id = id; 106 _url = url; 107 _data = new byte[size]; 108 _info = info; 109 } 110 111 117 public void flush() throws IOException { 118 while (_index > 0) { 119 doWrite(); 120 } 121 } 122 123 132 public void write(byte[] buffer, int offset, int length) 133 throws IOException { 134 135 int space = _data.length - _index; 136 if (space >= length) { 137 System.arraycopy(buffer, offset, _data, _index, length); 139 _index += length; 140 } else { 141 flush(); 142 doWrite(buffer, offset, length); 143 } 144 } 145 146 152 public void write(int value) throws IOException { 153 while (_index >= _data.length) { 154 flush(); 155 } 156 _data[_index++] = (byte) value; 157 } 158 159 164 private void doWrite() throws IOException { 165 try { 166 doWrite(_data, 0, _index); 167 _index = 0; 168 } catch (IOException exception) { 169 _log.debug(exception, exception); 170 throw exception; 171 } 172 } 173 174 183 private void doWrite(byte[] buffer, int offset, int length) 184 throws IOException { 185 186 HttpURLConnection connection = 187 TunnelHelper.create(_url, _id, "write", _info); 188 connection.setDoOutput(true); 189 OutputStream out = connection.getOutputStream(); 190 out.write(buffer, offset, length); 191 out.close(); 192 if (_log.isDebugEnabled()) { 193 _log.debug("doWrite(length=" + length + "), [id=" + _id + "]"); 194 } 195 196 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 197 throw new IOException (connection.getResponseCode() + " " 198 + connection.getResponseMessage()); 199 } 200 201 } 202 203 } 204
| Popular Tags
|