1 45 package org.exolab.jms.net.http; 46 47 import java.io.IOException ; 48 import java.io.InputStream ; 49 import java.net.HttpURLConnection ; 50 import java.net.URL ; 51 52 import org.apache.commons.logging.Log; 53 import org.apache.commons.logging.LogFactory; 54 55 56 62 class HTTPInputStream extends InputStream { 63 64 67 private final String _id; 68 69 72 private final URL _url; 73 74 77 private final HTTPRequestInfo _info; 78 79 82 private InputStream _in; 83 84 87 private byte[] _data = new byte[1024]; 88 89 92 private final byte[] _byte = new byte[1]; 93 94 97 private int _index = 0; 98 99 102 private int _available = 0; 103 104 107 private static final Log _log = LogFactory.getLog(HTTPInputStream.class); 108 109 116 public HTTPInputStream(String id, URL url, HTTPRequestInfo info) { 117 _id = id; 118 _url = url; 119 _info = info; 120 } 121 122 136 public int read() throws IOException { 137 final int mask = 0xFF; 138 int count = read(_byte, 0, 1); 139 return (count == 1) ? _byte[0] & mask : -1; 140 } 141 142 166 public int read(byte[] buffer, int offset, int length) throws IOException { 167 int count = 0; 168 if (offset < 0 || length < 0) { 169 throw new IndexOutOfBoundsException (); 170 } 171 if (length > 0) { 172 if (_available == 0) { 173 try { 174 doRead(); 175 } catch (IOException exception) { 176 _log.debug(exception, exception); 177 throw exception; 178 } 179 } 180 count = (length <= _available) ? length : _available; 181 if (_log.isDebugEnabled()) { 182 _log.debug("read(length=" + length + "), [id=" + _id 183 + ", available=" + _available + "]"); 184 } 185 186 if (count > 0) { 187 System.arraycopy(_data, _index, buffer, offset, count); 189 _index += count; 190 _available -= count; 191 } 192 } 193 return count; 194 } 195 196 204 protected int doRead() throws IOException { 205 int count = 0; 206 boolean done = false; 207 while (!done) { 208 if (_in == null) { 209 connect(); 210 done = true; 211 } 212 count = _in.read(_data); 213 if (count != -1) { 214 _available = count; 215 _index = 0; 216 done = true; 217 } else { 218 _in.close(); 219 _in = null; 220 } 221 } 222 return count; 223 } 224 225 230 private void connect() throws IOException { 231 int length = 0; 232 HttpURLConnection connection = null; 233 while (length == 0) { 234 connection = TunnelHelper.connect(_url, _id, "read", _info); 237 length = connection.getContentLength(); 238 if (length == -1) { 239 } else if (length == 0) { 243 try { 244 Thread.sleep(1000); 246 } catch (InterruptedException ignore) { 247 } 248 } 249 } 250 _in = connection.getInputStream(); 251 if (_log.isDebugEnabled()) { 252 _log.debug("connect(), [id=" + _id 253 + ", contentLength=" + length + "]"); 254 } 255 } 256 } 257 | Popular Tags |