View Javadoc

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpConnection.java,v 1.107 2005/01/14 21:30:59 olegk Exp $
3    * $Revision: 156935 $
4    * $Date: 2005-03-10 05:38:29 -0500 (Thu, 10 Mar 2005) $
5    *
6    * ====================================================================
7    *
8    *  Copyright 1999-2004 The Apache Software Foundation
9    *
10   *  Licensed under the Apache License, Version 2.0 (the "License");
11   *  you may not use this file except in compliance with the License.
12   *  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import java.io.BufferedInputStream;
33  import java.io.BufferedOutputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  import java.io.InterruptedIOException;
37  import java.io.OutputStream;
38  import java.lang.reflect.Method;
39  import java.net.InetAddress;
40  import java.net.Socket;
41  import java.net.SocketException;
42  
43  import org.apache.commons.httpclient.params.HttpConnectionParams;
44  import org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory;
45  import org.apache.commons.httpclient.protocol.Protocol;
46  import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
47  import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
48  import org.apache.commons.httpclient.util.EncodingUtil;
49  import org.apache.commons.httpclient.util.ExceptionUtil;
50  import org.apache.commons.logging.Log;
51  import org.apache.commons.logging.LogFactory;
52  
53  /***
54   * An abstraction of an HTTP {@link InputStream} and {@link OutputStream}
55   * pair, together with the relevant attributes.
56   * <p>
57   * The following options are set on the socket before getting the input/output 
58   * streams in the {@link #open()} method:
59   * <table border=1><tr>
60   *    <th>Socket Method
61   *    <th>Sockets Option
62   *    <th>Configuration
63   * </tr><tr>
64   *    <td>{@link java.net.Socket#setTcpNoDelay(boolean)}
65   *    <td>SO_NODELAY
66   *    <td>{@link HttpConnectionParams#setTcpNoDelay(boolean)}
67   * </tr><tr>
68   *    <td>{@link java.net.Socket#setSoTimeout(int)}
69   *    <td>SO_TIMEOUT
70   *    <td>{@link HttpConnectionParams#setSoTimeout(int)}
71   * </tr><tr>
72   *    <td>{@link java.net.Socket#setSendBufferSize(int)}
73   *    <td>SO_SNDBUF
74   *    <td>{@link HttpConnectionParams#setSendBufferSize(int)}
75   * </tr><tr>
76   *    <td>{@link java.net.Socket#setReceiveBufferSize(int)}
77   *    <td>SO_RCVBUF
78   *    <td>{@link HttpConnectionParams#setReceiveBufferSize(int)}
79   * </tr></table>
80   *
81   * @author Rod Waldhoff
82   * @author Sean C. Sullivan
83   * @author Ortwin Glueck
84   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
85   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
86   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
87   * @author Michael Becke
88   * @author Eric E Johnson
89   * @author Laura Werner
90   * 
91   * @version   $Revision: 156935 $ $Date: 2005-03-10 05:38:29 -0500 (Thu, 10 Mar 2005) $
92   */
93  public class HttpConnection {
94  
95      // ----------------------------------------------------------- Constructors
96  
97      /***
98       * Creates a new HTTP connection for the given host and port.
99       *
100      * @param host the host to connect to
101      * @param port the port to connect to
102      */
103     public HttpConnection(String host, int port) {
104         this(null, -1, host, null, port, Protocol.getProtocol("http"));
105     }
106 
107     /***
108      * Creates a new HTTP connection for the given host and port
109      * using the given protocol.
110      *
111      * @param host the host to connect to
112      * @param port the port to connect to
113      * @param protocol the protocol to use
114      */
115     public HttpConnection(String host, int port, Protocol protocol) {
116         this(null, -1, host, null, port, protocol);
117     }
118 
119     /***
120      * Creates a new HTTP connection for the given host with the virtual 
121      * alias and port using given protocol.
122      *
123      * @param host the host to connect to
124      * @param virtualHost the virtual host requests will be sent to
125      * @param port the port to connect to
126      * @param protocol the protocol to use
127      */
128     public HttpConnection(String host, String virtualHost, int port, Protocol protocol) {
129         this(null, -1, host, virtualHost, port, protocol);
130     }
131 
132     /***
133      * Creates a new HTTP connection for the given host and port via the 
134      * given proxy host and port using the default protocol.
135      *
136      * @param proxyHost the host to proxy via
137      * @param proxyPort the port to proxy via
138      * @param host the host to connect to
139      * @param port the port to connect to
140      */
141     public HttpConnection(
142         String proxyHost,
143         int proxyPort,
144         String host,
145         int port) {
146         this(proxyHost, proxyPort, host, null, port, Protocol.getProtocol("http"));
147     }
148 
149     /***
150      * Creates a new HTTP connection for the given host configuration.
151      * 
152      * @param hostConfiguration the host/proxy/protocol to use
153      */
154     public HttpConnection(HostConfiguration hostConfiguration) {
155         this(hostConfiguration.getProxyHost(),
156              hostConfiguration.getProxyPort(),
157              hostConfiguration.getHost(),
158              hostConfiguration.getPort(),
159              hostConfiguration.getProtocol());
160         this.localAddress = hostConfiguration.getLocalAddress();
161     }
162 
163     /***
164      * Creates a new HTTP connection for the given host with the virtual 
165      * alias and port via the given proxy host and port using the given 
166      * protocol.
167      * 
168      * @param proxyHost the host to proxy via
169      * @param proxyPort the port to proxy via
170      * @param host the host to connect to. Parameter value must be non-null.
171      * @param virtualHost No longer applicable. 
172      * @param port the port to connect to
173      * @param protocol The protocol to use. Parameter value must be non-null.
174      * 
175      * @deprecated use #HttpConnection(String, int, String, int, Protocol)
176      */
177     public HttpConnection(
178         String proxyHost,
179         int proxyPort,
180         String host,
181         String virtualHost,
182         int port,
183         Protocol protocol) {
184     	this(proxyHost, proxyPort, host, port, protocol);
185     }
186 
187     /***
188      * Creates a new HTTP connection for the given host with the virtual 
189      * alias and port via the given proxy host and port using the given 
190      * protocol.
191      * 
192      * @param proxyHost the host to proxy via
193      * @param proxyPort the port to proxy via
194      * @param host the host to connect to. Parameter value must be non-null.
195      * @param port the port to connect to
196      * @param protocol The protocol to use. Parameter value must be non-null.
197      */
198     public HttpConnection(
199         String proxyHost,
200         int proxyPort,
201         String host,
202         int port,
203         Protocol protocol) {
204 
205         if (host == null) {
206             throw new IllegalArgumentException("host parameter is null");
207         }
208         if (protocol == null) {
209             throw new IllegalArgumentException("protocol is null");
210         }
211 
212         proxyHostName = proxyHost;
213         proxyPortNumber = proxyPort;
214         hostName = host;
215         portNumber = protocol.resolvePort(port);
216         protocolInUse = protocol;
217     }
218 
219     // ------------------------------------------ Attribute Setters and Getters
220 
221     /***
222      * Returns the connection socket.
223      *
224      * @return the socket.
225      * 
226      * @since 3.0
227      */
228     protected Socket getSocket() {
229         return this.socket;
230     }
231 
232     /***
233      * Returns the host.
234      *
235      * @return the host.
236      */
237     public String getHost() {
238         return hostName;
239     }
240 
241     /***
242      * Sets the host to connect to.
243      *
244      * @param host the host to connect to. Parameter value must be non-null.
245      * @throws IllegalStateException if the connection is already open
246      */
247     public void setHost(String host) throws IllegalStateException {
248         if (host == null) {
249             throw new IllegalArgumentException("host parameter is null");
250         }
251         assertNotOpen();
252         hostName = host;
253     }
254 
255     /***
256      * Returns the target virtual host.
257      *
258      * @return the virtual host.
259      * 
260      * @deprecated no longer applicable
261      */
262 
263     public String getVirtualHost() {
264         return this.hostName;
265     }
266 
267     /***
268      * Sets the virtual host to target.
269      *
270      * @param host the virtual host name that should be used instead of 
271      *        physical host name when sending HTTP requests. Virtual host 
272      *        name can be set to <tt> null</tt> if virtual host name is not
273      *        to be used
274      * 
275      * @throws IllegalStateException if the connection is already open
276      * 
277      * @deprecated no longer applicable
278      */
279 
280     public void setVirtualHost(String host) throws IllegalStateException {
281         assertNotOpen();
282     }
283 
284     /***
285      * Returns the port of the host.
286      *
287      * If the port is -1 (or less than 0) the default port for
288      * the current protocol is returned.
289      *
290      * @return the port.
291      */
292     public int getPort() {
293         if (portNumber < 0) {
294             return isSecure() ? 443 : 80;
295         } else {
296             return portNumber;
297         }
298     }
299 
300     /***
301      * Sets the port to connect to.
302      *
303      * @param port the port to connect to
304      * 
305      * @throws IllegalStateException if the connection is already open
306      */
307     public void setPort(int port) throws IllegalStateException {
308         assertNotOpen();
309         portNumber = port;
310     }
311 
312     /***
313      * Returns the proxy host.
314      *
315      * @return the proxy host.
316      */
317     public String getProxyHost() {
318         return proxyHostName;
319     }
320 
321     /***
322      * Sets the host to proxy through.
323      *
324      * @param host the host to proxy through.
325      * 
326      * @throws IllegalStateException if the connection is already open
327      */
328     public void setProxyHost(String host) throws IllegalStateException {
329         assertNotOpen();
330         proxyHostName = host;
331     }
332 
333     /***
334      * Returns the port of the proxy host.
335      *
336      * @return the proxy port.
337      */
338     public int getProxyPort() {
339         return proxyPortNumber;
340     }
341 
342     /***
343      * Sets the port of the host to proxy through.
344      *
345      * @param port the port of the host to proxy through.
346      * 
347      * @throws IllegalStateException if the connection is already open
348      */
349     public void setProxyPort(int port) throws IllegalStateException {
350         assertNotOpen();
351         proxyPortNumber = port;
352     }
353 
354     /***
355      * Returns <tt>true</tt> if the connection is established over 
356      * a secure protocol.
357      *
358      * @return <tt>true</tt> if connected over a secure protocol.
359      */
360     public boolean isSecure() {
361         return protocolInUse.isSecure();
362     }
363 
364     /***
365      * Returns the protocol used to establish the connection.
366      * @return The protocol
367      */
368     public Protocol getProtocol() {
369         return protocolInUse;
370     }
371 
372     /***
373      * Sets the protocol used to establish the connection
374      * 
375      * @param protocol The protocol to use.
376      * 
377      * @throws IllegalStateException if the connection is already open
378      */
379     public void setProtocol(Protocol protocol) {
380         assertNotOpen();
381 
382         if (protocol == null) {
383             throw new IllegalArgumentException("protocol is null");
384         }
385 
386         protocolInUse = protocol;
387 
388     }
389 
390     /***
391      * Return the local address used when creating the connection.
392      * If <tt>null</tt>, the default address is used.
393      * 
394      * @return InetAddress the local address to be used when creating Sockets
395      */
396     public InetAddress getLocalAddress() {
397         return this.localAddress;
398     }
399     
400     /***
401      * Set the local address used when creating the connection.
402      * If unset or <tt>null</tt>, the default address is used.
403      * 
404      * @param localAddress the local address to use
405      */
406     public void setLocalAddress(InetAddress localAddress) {
407         assertNotOpen();
408         this.localAddress = localAddress;
409     }
410 
411     /***
412      * Tests if the connection is open. 
413      *
414      * @return <code>true</code> if the connection is open
415      */
416     public boolean isOpen() {
417         return isOpen;
418     }
419 
420     /***
421      * Closes the connection if stale.
422      * 
423      * @return <code>true</code> if the connection was stale and therefore closed, 
424      * <code>false</code> otherwise.
425      * 
426      * @see #isStale()
427      * 
428      * @since 3.0
429      */
430     public boolean closeIfStale() throws IOException {
431         if (isOpen && isStale()) {
432             LOG.debug("Connection is stale, closing...");
433             close();
434             return true;
435         }
436         return false;
437     }
438     
439     /***
440      * Tests if stale checking is enabled.
441      * 
442      * @return <code>true</code> if enabled
443      * 
444      * @see #isStale()
445      * 
446      * @deprecated Use {@link HttpConnectionParams#isStaleCheckingEnabled()},
447      * {@link HttpConnection#getParams()}.
448      */
449     public boolean isStaleCheckingEnabled() {
450         return this.params.isStaleCheckingEnabled();
451     }
452 
453     /***
454      * Sets whether or not isStale() will be called when testing if this connection is open.
455      * 
456      * <p>Setting this flag to <code>false</code> will increase performance when reusing
457      * connections, but it will also make them less reliable.  Stale checking ensures that
458      * connections are viable before they are used.  When set to <code>false</code> some
459      * method executions will result in IOExceptions and they will have to be retried.</p>
460      * 
461      * @param staleCheckEnabled <code>true</code> to enable isStale()
462      * 
463      * @see #isStale()
464      * @see #isOpen()
465      * 
466      * @deprecated Use {@link HttpConnectionParams#setStaleCheckingEnabled(boolean)},
467      * {@link HttpConnection#getParams()}.
468      */
469     public void setStaleCheckingEnabled(boolean staleCheckEnabled) {
470         this.params.setStaleCheckingEnabled(staleCheckEnabled);
471     }
472 
473     /***
474      * Determines whether this connection is "stale", which is to say that either
475      * it is no longer open, or an attempt to read the connection would fail.
476      *
477      * <p>Unfortunately, due to the limitations of the JREs prior to 1.4, it is
478      * not possible to test a connection to see if both the read and write channels
479      * are open - except by reading and writing.  This leads to a difficulty when
480      * some connections leave the "write" channel open, but close the read channel
481      * and ignore the request.  This function attempts to ameliorate that
482      * problem by doing a test read, assuming that the caller will be doing a
483      * write followed by a read, rather than the other way around.
484      * </p>
485      *
486      * <p>To avoid side-effects, the underlying connection is wrapped by a
487      * {@link BufferedInputStream}, so although data might be read, what is visible
488      * to clients of the connection will not change with this call.</p.
489      *
490      * @throws IOException if the stale connection test is interrupted.
491      * 
492      * @return <tt>true</tt> if the connection is already closed, or a read would
493      * fail.
494      */
495     protected boolean isStale() throws IOException {
496         boolean isStale = true;
497         if (isOpen) {
498             // the connection is open, but now we have to see if we can read it
499             // assume the connection is not stale.
500             isStale = false;
501             try {
502                 if (inputStream.available() == 0) {
503                     try {
504                         socket.setSoTimeout(1);
505                         inputStream.mark(1);
506                         int byteRead = inputStream.read();
507                         if (byteRead == -1) {
508                             // again - if the socket is reporting all data read,
509                             // probably stale
510                             isStale = true;
511                         } else {
512                             inputStream.reset();
513                         }
514                     } finally {
515                         socket.setSoTimeout(this.params.getSoTimeout());
516                     }
517                 }
518             } catch (InterruptedIOException e) {
519                 if (!ExceptionUtil.isSocketTimeoutException(e)) {
520                     throw e;
521                 }
522                 // aha - the connection is NOT stale - continue on!
523             } catch (IOException e) {
524                 // oops - the connection is stale, the read or soTimeout failed.
525                 LOG.debug(
526                     "An error occurred while reading from the socket, is appears to be stale",
527                     e
528                 );
529                 isStale = true;
530             }
531         }
532 
533         return isStale;
534     }
535 
536     /***
537      * Returns <tt>true</tt> if the connection is established via a proxy,
538      * <tt>false</tt> otherwise.
539      *
540      * @return <tt>true</tt> if a proxy is used to establish the connection, 
541      * <tt>false</tt> otherwise.
542      */
543     public boolean isProxied() {
544         return (!(null == proxyHostName || 0 >= proxyPortNumber));
545     }
546 
547     /***
548      * Set the state to keep track of the last response for the last request.
549      *
550      * <p>The connection managers use this to ensure that previous requests are
551      * properly closed before a new request is attempted.  That way, a GET
552      * request need not be read in its entirety before a new request is issued.
553      * Instead, this stream can be closed as appropriate.</p>
554      *
555      * @param inStream  The stream associated with an HttpMethod.
556      */
557     public void setLastResponseInputStream(InputStream inStream) {
558         lastResponseInputStream = inStream;
559     }
560 
561     /***
562      * Returns the stream used to read the last response's body.
563      *
564      * <p>Clients will generally not need to call this function unless
565      * using HttpConnection directly, instead of calling {@link HttpClient#executeMethod}.
566      * For those clients, call this function, and if it returns a non-null stream,
567      * close the stream before attempting to execute a method.  Note that
568      * calling "close" on the stream returned by this function <i>may</i> close
569      * the connection if the previous response contained a "Connection: close" header. </p>
570      *
571      * @return An {@link InputStream} corresponding to the body of the last
572      *  response.
573      */
574     public InputStream getLastResponseInputStream() {
575         return lastResponseInputStream;
576     }
577 
578     // --------------------------------------------------- Other Public Methods
579 
580     /***
581      * Returns {@link HttpConnectionParams HTTP protocol parameters} associated with this method.
582      *
583      * @return HTTP parameters.
584      *
585      * @since 3.0
586      */
587     public HttpConnectionParams getParams() {
588         return this.params;
589     }
590 
591     /***
592      * Assigns {@link HttpConnectionParams HTTP protocol parameters} for this method.
593      * 
594      * @since 3.0
595      * 
596      * @see HttpConnectionParams
597      */
598     public void setParams(final HttpConnectionParams params) {
599         if (params == null) {
600             throw new IllegalArgumentException("Parameters may not be null");
601         }
602         this.params = params;
603     }
604 
605     /***
606      * Set the {@link Socket}'s timeout, via {@link Socket#setSoTimeout}.  If the
607      * connection is already open, the SO_TIMEOUT is changed.  If no connection
608      * is open, then subsequent connections will use the timeout value.
609      * <p>
610      * Note: This is not a connection timeout but a timeout on network traffic!
611      *
612      * @param timeout the timeout value
613      * @throws SocketException - if there is an error in the underlying
614      * protocol, such as a TCP error.
615      * 
616      * @deprecated Use {@link HttpConnectionParams#setSoTimeout(int)},
617      * {@link HttpConnection#getParams()}.
618      */
619     public void setSoTimeout(int timeout)
620         throws SocketException, IllegalStateException {
621         this.params.setSoTimeout(timeout);
622         if (this.socket != null) {
623             this.socket.setSoTimeout(timeout);
624         }
625     }
626 
627     /***
628      * Sets <code>SO_TIMEOUT</code> value directly on the underlying {@link Socket socket}. 
629      * This method does not change the default read timeout value set via 
630      * {@link HttpConnectionParams}.
631      *
632      * @param timeout the timeout value
633      * @throws SocketException - if there is an error in the underlying
634      * protocol, such as a TCP error.
635      * @throws IllegalStateException if not connected
636      * 
637      * @since 3.0
638      */
639     public void setSocketTimeout(int timeout)
640         throws SocketException, IllegalStateException {
641         assertOpen();
642         if (this.socket != null) {
643             this.socket.setSoTimeout(timeout);
644         }
645     }
646 
647     /***
648      * Returns the {@link Socket}'s timeout, via {@link Socket#getSoTimeout}, if the
649      * connection is already open. If no connection is open, return the value subsequent 
650      * connection will use.
651      * <p>
652      * Note: This is not a connection timeout but a timeout on network traffic!
653      *
654      * @return the timeout value
655      * 
656      * @deprecated Use {@link HttpConnectionParams#getSoTimeout()},
657      * {@link HttpConnection#getParams()}.
658      */
659     public int getSoTimeout() throws SocketException {
660         return this.params.getSoTimeout();
661     }
662 
663     /***
664      * Sets the connection timeout. This is the maximum time that may be spent
665      * until a connection is established. The connection will fail after this
666      * amount of time.
667      * @param timeout The timeout in milliseconds. 0 means timeout is not used.
668      * 
669      * @deprecated Use {@link HttpConnectionParams#setConnectionTimeout(int)},
670      * {@link HttpConnection#getParams()}.
671      */
672     public void setConnectionTimeout(int timeout) {
673         this.params.setConnectionTimeout(timeout);
674     }
675 
676     /***
677      * Establishes a connection to the specified host and port
678      * (via a proxy if specified).
679      * The underlying socket is created from the {@link ProtocolSocketFactory}.
680      *
681      * @throws IOException if an attempt to establish the connection results in an
682      *   I/O error.
683      */
684     public void open() throws IOException {
685         LOG.trace("enter HttpConnection.open()");
686 
687         final String host = (proxyHostName == null) ? hostName : proxyHostName;
688         final int port = (proxyHostName == null) ? portNumber : proxyPortNumber;
689         assertNotOpen();
690         
691         if (LOG.isDebugEnabled()) {
692             LOG.debug("Open connection to " + host + ":" + port);
693         }
694         
695         try {
696             if (this.socket == null) {
697                 usingSecureSocket = isSecure() && !isProxied();
698                 // use the protocol's socket factory unless this is a secure
699                 // proxied connection
700                 final ProtocolSocketFactory socketFactory =
701                     (isSecure() && isProxied()
702                             ? new DefaultProtocolSocketFactory()
703                             : protocolInUse.getSocketFactory());
704                 this.socket = socketFactory.createSocket(
705                             host, port, 
706                             localAddress, 0,
707                             this.params);
708             }
709 
710             /*
711             "Nagling has been broadly implemented across networks, 
712             including the Internet, and is generally performed by default 
713             - although it is sometimes considered to be undesirable in 
714             highly interactive environments, such as some client/server 
715             situations. In such cases, nagling may be turned off through 
716             use of the TCP_NODELAY sockets option." */
717 
718             socket.setTcpNoDelay(this.params.getTcpNoDelay());
719             socket.setSoTimeout(this.params.getSoTimeout());
720             
721             int linger = this.params.getLinger();
722             if (linger >= 0) {
723                 socket.setSoLinger(linger > 0, linger);
724             }
725             
726             int sndBufSize = this.params.getSendBufferSize();
727             if (sndBufSize >= 0) {
728                 socket.setSendBufferSize(sndBufSize);
729             }        
730             int rcvBufSize = this.params.getReceiveBufferSize();
731             if (rcvBufSize >= 0) {
732                 socket.setReceiveBufferSize(rcvBufSize);
733             }        
734             int outbuffersize = socket.getSendBufferSize();
735             if ((outbuffersize > 2048) || (outbuffersize <= 0)) {
736                 outbuffersize = 2048;
737             }
738             int inbuffersize = socket.getReceiveBufferSize();
739             if ((inbuffersize > 2048) || (inbuffersize <= 0)) {
740                 inbuffersize = 2048;
741             }
742             inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
743             outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
744             isOpen = true;
745         } catch (IOException e) {
746             // Connection wasn't opened properly
747             // so close everything out
748             closeSocketAndStreams();
749             throw e;
750         }
751     }
752 
753     /***
754      * Instructs the proxy to establish a secure tunnel to the host. The socket will 
755      * be switched to the secure socket. Subsequent communication is done via the secure 
756      * socket. The method can only be called once on a proxied secure connection.
757      *
758      * @throws IllegalStateException if connection is not secure and proxied or
759      * if the socket is already secure.
760      * @throws IOException if an attempt to establish the secure tunnel results in an
761      *   I/O error.
762      */
763     public void tunnelCreated() throws IllegalStateException, IOException {
764         LOG.trace("enter HttpConnection.tunnelCreated()");
765 
766         if (!isSecure() || !isProxied()) {
767             throw new IllegalStateException(
768                 "Connection must be secure "
769                     + "and proxied to use this feature");
770         }
771 
772         if (usingSecureSocket) {
773             throw new IllegalStateException("Already using a secure socket");
774         }
775         
776         if (LOG.isDebugEnabled()) {
777             LOG.debug("Secure tunnel to " + this.hostName + ":" + this.portNumber);
778         }
779 
780         SecureProtocolSocketFactory socketFactory =
781             (SecureProtocolSocketFactory) protocolInUse.getSocketFactory();
782 
783         socket = socketFactory.createSocket(socket, hostName, portNumber, true);
784         int sndBufSize = this.params.getSendBufferSize();
785         if (sndBufSize >= 0) {
786             socket.setSendBufferSize(sndBufSize);
787         }        
788         int rcvBufSize = this.params.getReceiveBufferSize();
789         if (rcvBufSize >= 0) {
790             socket.setReceiveBufferSize(rcvBufSize);
791         }        
792         int outbuffersize = socket.getSendBufferSize();
793         if (outbuffersize > 2048) {
794             outbuffersize = 2048;
795         }
796         int inbuffersize = socket.getReceiveBufferSize();
797         if (inbuffersize > 2048) {
798             inbuffersize = 2048;
799         }
800         inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
801         outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
802         usingSecureSocket = true;
803         tunnelEstablished = true;
804     }
805 
806     /***
807      * Indicates if the connection is completely transparent from end to end.
808      *
809      * @return true if conncetion is not proxied or tunneled through a transparent
810      * proxy; false otherwise.
811      */
812     public boolean isTransparent() {
813         return !isProxied() || tunnelEstablished;
814     }
815 
816     /***
817      * Flushes the output request stream.  This method should be called to 
818      * ensure that data written to the request OutputStream is sent to the server.
819      * 
820      * @throws IOException if an I/O problem occurs
821      */
822     public void flushRequestOutputStream() throws IOException {
823         LOG.trace("enter HttpConnection.flushRequestOutputStream()");
824         assertOpen();
825         outputStream.flush();
826     }
827 
828     /***
829      * Returns an {@link OutputStream} suitable for writing the request.
830      *
831      * @throws IllegalStateException if the connection is not open
832      * @throws IOException if an I/O problem occurs
833      * @return a stream to write the request to
834      */
835     public OutputStream getRequestOutputStream()
836         throws IOException, IllegalStateException {
837         LOG.trace("enter HttpConnection.getRequestOutputStream()");
838         assertOpen();
839         OutputStream out = this.outputStream;
840         if (Wire.CONTENT_WIRE.enabled()) {
841             out = new WireLogOutputStream(out, Wire.CONTENT_WIRE);
842         }
843         return out;
844     }
845 
846     /***
847      * Return a {@link InputStream} suitable for reading the response.
848      * @return InputStream The response input stream.
849      * @throws IOException If an IO problem occurs
850      * @throws IllegalStateException If the connection isn't open.
851      */
852     public InputStream getResponseInputStream()
853         throws IOException, IllegalStateException {
854         LOG.trace("enter HttpConnection.getResponseInputStream()");
855         assertOpen();
856         return inputStream;
857     }
858 
859     /***
860      * Tests if input data avaialble. This method returns immediately
861      * and does not perform any read operations on the input socket
862      * 
863      * @return boolean <tt>true</tt> if input data is available, 
864      *                 <tt>false</tt> otherwise.
865      * 
866      * @throws IOException If an IO problem occurs
867      * @throws IllegalStateException If the connection isn't open.
868      */
869     public boolean isResponseAvailable() 
870         throws IOException {
871         LOG.trace("enter HttpConnection.isResponseAvailable()");
872         assertOpen();
873         return this.inputStream.available() > 0;
874     }
875 
876     /***
877      * Tests if input data becomes available within the given period time in milliseconds.
878      * 
879      * @param timeout The number milliseconds to wait for input data to become available 
880      * @return boolean <tt>true</tt> if input data is availble, 
881      *                 <tt>false</tt> otherwise.
882      * 
883      * @throws IOException If an IO problem occurs
884      * @throws IllegalStateException If the connection isn't open.
885      */
886     public boolean isResponseAvailable(int timeout) 
887         throws IOException {
888         LOG.trace("enter HttpConnection.isResponseAvailable(int)");
889         assertOpen();
890         boolean result = false;
891         if (this.inputStream.available() > 0) {
892             result = true;
893         } else {
894             try {
895                 this.socket.setSoTimeout(timeout);
896                 inputStream.mark(1);
897                 int byteRead = inputStream.read();
898                 if (byteRead != -1) {
899                     inputStream.reset();
900                     LOG.debug("Input data available");
901                     result = true;
902                 } else {
903                     LOG.debug("Input data not available");
904                 }
905             } catch (InterruptedIOException e) {
906                 if (!ExceptionUtil.isSocketTimeoutException(e)) {
907                     throw e;
908                 }
909                 if (LOG.isDebugEnabled()) {
910                     LOG.debug("Input data not available after " + timeout + " ms");
911                 }
912             } finally {
913                 try {
914                     socket.setSoTimeout(this.params.getSoTimeout());
915                 } catch (IOException ioe) {
916                     LOG.debug("An error ocurred while resetting soTimeout, we will assume that"
917                         + " no response is available.",
918                         ioe);
919                     result = false;
920                 }
921             }
922         }
923         return result;
924     }
925 
926     /***
927      * Writes the specified bytes to the output stream.
928      *
929      * @param data the data to be written
930      * @throws IllegalStateException if not connected
931      * @throws IOException if an I/O problem occurs
932      * @see #write(byte[],int,int)
933      */
934     public void write(byte[] data)
935         throws IOException, IllegalStateException {
936         LOG.trace("enter HttpConnection.write(byte[])");
937         this.write(data, 0, data.length);
938     }
939 
940     /***
941      * Writes <i>length</i> bytes in <i>data</i> starting at
942      * <i>offset</i> to the output stream.
943      *
944      * The general contract for
945      * write(b, off, len) is that some of the bytes in the array b are written
946      * to the output stream in order; element b[off] is the first byte written
947      * and b[off+len-1] is the last byte written by this operation.
948      *
949      * @param data array containing the data to be written.
950      * @param offset the start offset in the data.
951      * @param length the number of bytes to write.
952      * @throws IllegalStateException if not connected
953      * @throws IOException if an I/O problem occurs
954      */
955     public void write(byte[] data, int offset, int length)
956         throws IOException, IllegalStateException {
957         LOG.trace("enter HttpConnection.write(byte[], int, int)");
958 
959         if (offset < 0) {
960             throw new IllegalArgumentException("Array offset may not be negative");
961         }
962         if (length < 0) {
963             throw new IllegalArgumentException("Array length may not be negative");
964         }
965         if (offset + length > data.length) {
966             throw new IllegalArgumentException("Given offset and length exceed the array length");
967         }
968         assertOpen();
969         this.outputStream.write(data, offset, length);
970     }
971 
972     /***
973      * Writes the specified bytes, followed by <tt>"\r\n".getBytes()</tt> to the
974      * output stream.
975      *
976      * @param data the bytes to be written
977      * @throws IllegalStateException if the connection is not open
978      * @throws IOException if an I/O problem occurs
979      */
980     public void writeLine(byte[] data)
981         throws IOException, IllegalStateException {
982         LOG.trace("enter HttpConnection.writeLine(byte[])");
983         write(data);
984         writeLine();
985     }
986 
987     /***
988      * Writes <tt>"\r\n".getBytes()</tt> to the output stream.
989      *
990      * @throws IllegalStateException if the connection is not open
991      * @throws IOException if an I/O problem occurs
992      */
993     public void writeLine()
994         throws IOException, IllegalStateException {
995         LOG.trace("enter HttpConnection.writeLine()");
996         write(CRLF);
997     }
998 
999     /***
1000      * @deprecated Use {@link #print(String, String)}
1001      * 
1002      * Writes the specified String (as bytes) to the output stream.
1003      *
1004      * @param data the string to be written
1005      * @throws IllegalStateException if the connection is not open
1006      * @throws IOException if an I/O problem occurs
1007      */
1008     public void print(String data)
1009         throws IOException, IllegalStateException {
1010         LOG.trace("enter HttpConnection.print(String)");
1011         write(EncodingUtil.getBytes(data, "ISO-8859-1"));
1012     }
1013 
1014     /***
1015      * Writes the specified String (as bytes) to the output stream.
1016      *
1017      * @param data the string to be written
1018      * @param charset the charset to use for writing the data
1019      * @throws IllegalStateException if the connection is not open
1020      * @throws IOException if an I/O problem occurs
1021      * 
1022      * @since 3.0
1023      */
1024     public void print(String data, String charset)
1025     	throws IOException, IllegalStateException {
1026         LOG.trace("enter HttpConnection.print(String)");
1027         write(EncodingUtil.getBytes(data, charset));
1028     }
1029     
1030     /***
1031      * @deprecated Use {@link #printLine(String, String)}
1032      * 
1033      * Writes the specified String (as bytes), followed by
1034      * <tt>"\r\n".getBytes()</tt> to the output stream.
1035      *
1036      * @param data the data to be written
1037      * @throws IllegalStateException if the connection is not open
1038      * @throws IOException if an I/O problem occurs
1039      */
1040     public void printLine(String data)
1041         throws IOException, IllegalStateException {
1042         LOG.trace("enter HttpConnection.printLine(String)");
1043         writeLine(EncodingUtil.getBytes(data, "ISO-8859-1"));
1044     }
1045 
1046     /***
1047      * Writes the specified String (as bytes), followed by
1048      * <tt>"\r\n".getBytes()</tt> to the output stream.
1049      *
1050      * @param data the data to be written
1051      * @param charset the charset to use for writing the data
1052      * @throws IllegalStateException if the connection is not open
1053      * @throws IOException if an I/O problem occurs
1054      * 
1055      * @since 3.0
1056      */
1057     public void printLine(String data, String charset)
1058     	throws IOException, IllegalStateException {
1059         LOG.trace("enter HttpConnection.printLine(String)");
1060         writeLine(EncodingUtil.getBytes(data, charset));
1061     }    
1062     
1063     /***
1064      * Writes <tt>"\r\n".getBytes()</tt> to the output stream.
1065      *
1066      * @throws IllegalStateException if the connection is not open
1067      * @throws IOException if an I/O problem occurs
1068      */
1069     public void printLine()
1070         throws IOException, IllegalStateException {
1071         LOG.trace("enter HttpConnection.printLine()");
1072         writeLine();
1073     }
1074 
1075     /***
1076      * Reads up to <tt>"\n"</tt> from the (unchunked) input stream.
1077      * If the stream ends before the line terminator is found,
1078      * the last part of the string will still be returned.
1079      *
1080      * @throws IllegalStateException if the connection is not open
1081      * @throws IOException if an I/O problem occurs
1082      * @return a line from the response
1083      * 
1084      * @deprecated use #readLine(String)
1085      */
1086     public String readLine() throws IOException, IllegalStateException {
1087         LOG.trace("enter HttpConnection.readLine()");
1088 
1089         assertOpen();
1090         return HttpParser.readLine(inputStream);
1091     }
1092 
1093     /***
1094      * Reads up to <tt>"\n"</tt> from the (unchunked) input stream.
1095      * If the stream ends before the line terminator is found,
1096      * the last part of the string will still be returned.
1097      * 
1098      * @param charset the charset to use for reading the data
1099      *
1100      * @throws IllegalStateException if the connection is not open
1101      * @throws IOException if an I/O problem occurs
1102      * @return a line from the response
1103      * 
1104      * @since 3.0
1105      */
1106     public String readLine(final String charset) throws IOException, IllegalStateException {
1107         LOG.trace("enter HttpConnection.readLine()");
1108 
1109         assertOpen();
1110         return HttpParser.readLine(inputStream, charset);
1111     }
1112 
1113     /***
1114      * Attempts to shutdown the {@link Socket}'s output, via Socket.shutdownOutput()
1115      * when running on JVM 1.3 or higher.
1116      * 
1117      * @deprecated unused
1118      */
1119     public void shutdownOutput() {
1120         LOG.trace("enter HttpConnection.shutdownOutput()");
1121 
1122         try {
1123             // Socket.shutdownOutput is a JDK 1.3
1124             // method. We'll use reflection in case
1125             // we're running in an older VM
1126             Class[] paramsClasses = new Class[0];
1127             Method shutdownOutput =
1128                 socket.getClass().getMethod("shutdownOutput", paramsClasses);
1129             Object[] params = new Object[0];
1130             shutdownOutput.invoke(socket, params);
1131         } catch (Exception ex) {
1132             LOG.debug("Unexpected Exception caught", ex);
1133             // Ignore, and hope everything goes right
1134         }
1135         // close output stream?
1136     }
1137 
1138     /***
1139      * Closes the socket and streams.
1140      */
1141     public void close() {
1142         LOG.trace("enter HttpConnection.close()");
1143         closeSocketAndStreams();
1144     }
1145 
1146     /***
1147      * Returns the httpConnectionManager.
1148      * @return HttpConnectionManager
1149      */
1150     public HttpConnectionManager getHttpConnectionManager() {
1151         return httpConnectionManager;
1152     }
1153 
1154     /***
1155      * Sets the httpConnectionManager.
1156      * @param httpConnectionManager The httpConnectionManager to set
1157      */
1158     public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) {
1159         this.httpConnectionManager = httpConnectionManager;
1160     }
1161 
1162     /***
1163      * Releases the connection. If the connection is locked or does not have a connection
1164      * manager associated with it, this method has no effect. Note that it is completely safe 
1165      * to call this method multiple times.
1166      */
1167     public void releaseConnection() {
1168         LOG.trace("enter HttpConnection.releaseConnection()");
1169         if (locked) {
1170             LOG.debug("Connection is locked.  Call to releaseConnection() ignored.");
1171         } else if (httpConnectionManager != null) {
1172             LOG.debug("Releasing connection back to connection manager.");
1173             httpConnectionManager.releaseConnection(this);
1174         } else {
1175             LOG.warn("HttpConnectionManager is null.  Connection cannot be released.");
1176         }
1177     }
1178 
1179     /***
1180      * Tests if the connection is locked. Locked connections cannot be released. 
1181      * An attempt to release a locked connection will have no effect.
1182      * 
1183      * @return <tt>true</tt> if the connection is locked, <tt>false</tt> otherwise.
1184      * 
1185      * @since 3.0
1186      */
1187     protected boolean isLocked() {
1188         return locked;
1189     }
1190 
1191     /***
1192      * Locks or unlocks the connection. Locked connections cannot be released. 
1193      * An attempt to release a locked connection will have no effect.
1194      * 
1195      * @param locked <tt>true</tt> to lock the connection, <tt>false</tt> to unlock
1196      *  the connection.
1197      * 
1198      * @since 3.0
1199      */
1200     protected void setLocked(boolean locked) {
1201         this.locked = locked;
1202     }
1203     // ------------------------------------------------------ Protected Methods
1204 
1205     /***
1206      * Closes everything out.
1207      */
1208     protected void closeSocketAndStreams() {
1209         LOG.trace("enter HttpConnection.closeSockedAndStreams()");
1210 
1211         // no longer care about previous responses...
1212         lastResponseInputStream = null;
1213 
1214         if (null != outputStream) {
1215             OutputStream temp = outputStream;
1216             outputStream = null;
1217             try {
1218                 temp.close();
1219             } catch (Exception ex) {
1220                 LOG.debug("Exception caught when closing output", ex);
1221                 // ignored
1222             }
1223         }
1224 
1225         if (null != inputStream) {
1226             InputStream temp = inputStream;
1227             inputStream = null;
1228             try {
1229                 temp.close();
1230             } catch (Exception ex) {
1231                 LOG.debug("Exception caught when closing input", ex);
1232                 // ignored
1233             }
1234         }
1235 
1236         if (null != socket) {
1237             Socket temp = socket;
1238             socket = null;
1239             try {
1240                 temp.close();
1241             } catch (Exception ex) {
1242                 LOG.debug("Exception caught when closing socket", ex);
1243                 // ignored
1244             }
1245         }
1246         isOpen = false;
1247         tunnelEstablished = false;
1248         usingSecureSocket = false;
1249     }
1250 
1251     /***
1252      * Throws an {@link IllegalStateException} if the connection is already open.
1253      *
1254      * @throws IllegalStateException if connected
1255      */
1256     protected void assertNotOpen() throws IllegalStateException {
1257         if (isOpen) {
1258             throw new IllegalStateException("Connection is open");
1259         }
1260     }
1261 
1262     /***
1263      * Throws an {@link IllegalStateException} if the connection is not open.
1264      *
1265      * @throws IllegalStateException if not connected
1266      */
1267     protected void assertOpen() throws IllegalStateException {
1268         if (!isOpen) {
1269             throw new IllegalStateException("Connection is not open");
1270         }
1271     }
1272 
1273     /***
1274      * Gets the socket's sendBufferSize.
1275      * 
1276      * @return the size of the buffer for the socket OutputStream, -1 if the value
1277      * has not been set and the socket has not been opened
1278      * 
1279      * @throws SocketException if an error occurs while getting the socket value
1280      * 
1281      * @see Socket#getSendBufferSize()
1282      */
1283     public int getSendBufferSize() throws SocketException {
1284         if (socket == null) {
1285             return -1;
1286         } else {
1287             return socket.getSendBufferSize();
1288         }
1289     }
1290 
1291     /***
1292      * Sets the socket's sendBufferSize.
1293      * 
1294      * @param sendBufferSize the size to set for the socket OutputStream
1295      * 
1296      * @throws SocketException if an error occurs while setting the socket value
1297      * 
1298      * @see Socket#setSendBufferSize(int)
1299      * 
1300      * @deprecated Use {@link HttpConnectionParams#setSendBufferSize(int)},
1301      * {@link HttpConnection#getParams()}.
1302      */
1303     public void setSendBufferSize(int sendBufferSize) throws SocketException {
1304         this.params.setSendBufferSize(sendBufferSize);
1305     }
1306 
1307     // ------------------------------------------------------- Static Variable
1308 
1309     /*** <tt>"\r\n"</tt>, as bytes. */
1310     private static final byte[] CRLF = new byte[] {(byte) 13, (byte) 10};
1311 
1312     /*** Log object for this class. */
1313     private static final Log LOG = LogFactory.getLog(HttpConnection.class);
1314     
1315     // ----------------------------------------------------- Instance Variables
1316     
1317     /*** My host. */
1318     private String hostName = null;
1319     
1320     /*** My port. */
1321     private int portNumber = -1;
1322     
1323     /*** My proxy host. */
1324     private String proxyHostName = null;
1325     
1326     /*** My proxy port. */
1327     private int proxyPortNumber = -1;
1328     
1329     /*** My client Socket. */
1330     private Socket socket = null;
1331     
1332     /*** My InputStream. */
1333     private InputStream inputStream = null;
1334 
1335     /*** My OutputStream. */
1336     private OutputStream outputStream = null;
1337     
1338     /*** An {@link InputStream} for the response to an individual request. */
1339     private InputStream lastResponseInputStream = null;
1340     
1341     /*** Whether or not the connection is connected. */
1342     protected boolean isOpen = false;
1343     
1344     /*** the protocol being used */
1345     private Protocol protocolInUse;
1346     
1347     /*** Collection of HTTP parameters associated with this HTTP connection*/
1348     private HttpConnectionParams params = new HttpConnectionParams();
1349     
1350     /*** flag to indicate if this connection can be released, if locked the connection cannot be 
1351      * released */
1352     private boolean locked = false;
1353     
1354     /*** Whether or not the socket is a secure one. */
1355     private boolean usingSecureSocket = false;
1356     
1357     /*** Whether the connection is open via a secure tunnel or not */
1358     private boolean tunnelEstablished = false;
1359     
1360     /*** the connection manager that created this connection or null */
1361     private HttpConnectionManager httpConnectionManager;
1362     
1363     /*** The local interface on which the connection is created, or null for the default */
1364     private InetAddress localAddress;
1365 }