/[classpath]/inetlib/source/gnu/inet/http/HTTPConnection.java
ViewVC logotype

Diff of /inetlib/source/gnu/inet/http/HTTPConnection.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.17 by dog, Thu Nov 25 12:45:43 2004 UTC revision 1.18 by dog, Thu Nov 25 22:15:05 2004 UTC
# Line 1  Line 1 
1  /*  /*
2   * $Id$   * HTTPConnection.java
3   * Copyright (C) 2004 The Free Software Foundation   * Copyright (C) 2004 The Free Software Foundation
4   *   *
5   * This file is part of GNU inetlib, a library.   * This file is part of GNU inetlib, a library.
# Line 81  public class HTTPConnection Line 81  public class HTTPConnection
81     */     */
82    public static final int HTTPS_PORT = 443;    public static final int HTTPS_PORT = 443;
83    
84    private static final String userAgent = initUserAgent ();    private static final String userAgent = initUserAgent();
85    
86    private static String initUserAgent ()    private static String initUserAgent()
87    {    {
88      try      try
89        {        {
90          StringBuffer buf = new StringBuffer("inetlib/1.1 (");          StringBuffer buf = new StringBuffer("inetlib/1.1 (");
91          buf.append (System.getProperty ("os.name"));          buf.append(System.getProperty("os.name"));
92          buf.append ("; ");          buf.append("; ");
93          buf.append (System.getProperty ("os.arch"));          buf.append(System.getProperty("os.arch"));
94          buf.append ("; ");          buf.append("; ");
95          buf.append (System.getProperty ("user.language"));          buf.append(System.getProperty("user.language"));
96          buf.append (")");          buf.append(")");
97          return buf.toString ();          return buf.toString();
98        }        }
99      catch (SecurityException e)      catch (SecurityException e)
100        {        {
# Line 179  public class HTTPConnection Line 179  public class HTTPConnection
179     * Creates a new HTTP connection.     * Creates a new HTTP connection.
180     * @param hostname the name of the host to connect to     * @param hostname the name of the host to connect to
181     */     */
182    public HTTPConnection (String hostname)    public HTTPConnection(String hostname)
183    {    {
184      this (hostname, HTTP_PORT, false, 0, 0);      this(hostname, HTTP_PORT, false, 0, 0);
185    }    }
186    
187    /**    /**
# Line 189  public class HTTPConnection Line 189  public class HTTPConnection
189     * @param hostname the name of the host to connect to     * @param hostname the name of the host to connect to
190     * @param secure whether to use a secure connection     * @param secure whether to use a secure connection
191     */     */
192    public HTTPConnection (String hostname, boolean secure)    public HTTPConnection(String hostname, boolean secure)
193    {    {
194      this (hostname, secure ? HTTPS_PORT : HTTP_PORT, secure, 0, 0);      this(hostname, secure ? HTTPS_PORT : HTTP_PORT, secure, 0, 0);
195    }    }
196    
197    /**    /**
# Line 201  public class HTTPConnection Line 201  public class HTTPConnection
201     * @param connectionTimeout the connection timeout     * @param connectionTimeout the connection timeout
202     * @param timeout the socket read timeout     * @param timeout the socket read timeout
203     */     */
204    public HTTPConnection (String hostname, boolean secure,    public HTTPConnection(String hostname, boolean secure,
205                           int connectionTimeout, int timeout)                          int connectionTimeout, int timeout)
206    {    {
207      this (hostname, secure ? HTTPS_PORT : HTTP_PORT, secure,      this(hostname, secure ? HTTPS_PORT : HTTP_PORT, secure,
208            connectionTimeout, timeout);           connectionTimeout, timeout);
209    }    }
210        
211    /**    /**
# Line 213  public class HTTPConnection Line 213  public class HTTPConnection
213     * @param hostname the name of the host to connect to     * @param hostname the name of the host to connect to
214     * @param port the port on the host to connect to     * @param port the port on the host to connect to
215     */     */
216    public HTTPConnection (String hostname, int port)    public HTTPConnection(String hostname, int port)
217    {    {
218      this (hostname, port, false, 0, 0);      this(hostname, port, false, 0, 0);
219    }    }
220    
221    /**    /**
# Line 224  public class HTTPConnection Line 224  public class HTTPConnection
224     * @param port the port on the host to connect to     * @param port the port on the host to connect to
225     * @param secure whether to use a secure connection     * @param secure whether to use a secure connection
226     */     */
227    public HTTPConnection (String hostname, int port, boolean secure)    public HTTPConnection(String hostname, int port, boolean secure)
228    {    {
229      this (hostname, port, secure, 0, 0);      this(hostname, port, secure, 0, 0);
230    }    }
231        
232    /**    /**
# Line 237  public class HTTPConnection Line 237  public class HTTPConnection
237     * @param connectionTimeout the connection timeout     * @param connectionTimeout the connection timeout
238     * @param timeout the socket read timeout     * @param timeout the socket read timeout
239     */     */
240    public HTTPConnection (String hostname, int port, boolean secure,    public HTTPConnection(String hostname, int port, boolean secure,
241                           int connectionTimeout, int timeout)                          int connectionTimeout, int timeout)
242    {    {
243      this.hostname = hostname;      this.hostname = hostname;
244      this.port = port;      this.port = port;
# Line 246  public class HTTPConnection Line 246  public class HTTPConnection
246      this.connectionTimeout = connectionTimeout;      this.connectionTimeout = connectionTimeout;
247      this.timeout = timeout;      this.timeout = timeout;
248      majorVersion = minorVersion = 1;      majorVersion = minorVersion = 1;
249      connectionListeners = Collections.synchronizedList (new ArrayList (4));      connectionListeners = Collections.synchronizedList(new ArrayList(4));
250      requestListeners = Collections.synchronizedList (new ArrayList (4));      requestListeners = Collections.synchronizedList(new ArrayList(4));
251    }    }
252    
253    /**    /**
254     * Returns the name of the host to connect to.     * Returns the name of the host to connect to.
255     */     */
256    public String getHostName ()    public String getHostName()
257    {    {
258      return hostname;      return hostname;
259    }    }
# Line 261  public class HTTPConnection Line 261  public class HTTPConnection
261    /**    /**
262     * Returns the port on the host to connect to.     * Returns the port on the host to connect to.
263     */     */
264    public int getPort ()    public int getPort()
265    {    {
266      return port;      return port;
267    }    }
# Line 269  public class HTTPConnection Line 269  public class HTTPConnection
269    /**    /**
270     * Indicates whether to use a secure connection or not.     * Indicates whether to use a secure connection or not.
271     */     */
272    public boolean isSecure ()    public boolean isSecure()
273    {    {
274      return secure;      return secure;
275    }    }
# Line 278  public class HTTPConnection Line 278  public class HTTPConnection
278     * Returns the HTTP version string supported by this connection.     * Returns the HTTP version string supported by this connection.
279     * @see #version     * @see #version
280     */     */
281    public String getVersion ()    public String getVersion()
282    {    {
283      return "HTTP/" + majorVersion + '.' + minorVersion;      return "HTTP/" + majorVersion + '.' + minorVersion;
284    }    }
# Line 288  public class HTTPConnection Line 288  public class HTTPConnection
288     * @param majorVersion the major version     * @param majorVersion the major version
289     * @param minorVersion the minor version     * @param minorVersion the minor version
290     */     */
291    public void setVersion (int majorVersion, int minorVersion)    public void setVersion(int majorVersion, int minorVersion)
292    {    {
293      if (majorVersion != 1)      if (majorVersion != 1)
294        {        {
295          throw new IllegalArgumentException ("major version not supported: " +          throw new IllegalArgumentException("major version not supported: " +
296                                              majorVersion);                                             majorVersion);
297        }        }
298      if (minorVersion < 0 || minorVersion > 1)      if (minorVersion < 0 || minorVersion > 1)
299        {        {
300          throw new IllegalArgumentException ("minor version not supported: " +          throw new IllegalArgumentException("minor version not supported: " +
301                                              minorVersion);                                             minorVersion);
302        }        }
303      this.majorVersion = majorVersion;      this.majorVersion = majorVersion;
304      this.minorVersion = minorVersion;      this.minorVersion = minorVersion;
# Line 309  public class HTTPConnection Line 309  public class HTTPConnection
309     * @param hostname the proxy host name     * @param hostname the proxy host name
310     * @param port the port on the proxy to connect to     * @param port the port on the proxy to connect to
311     */     */
312    public void setProxy (String hostname, int port)    public void setProxy(String hostname, int port)
313    {    {
314      proxyHostname = hostname;      proxyHostname = hostname;
315      proxyPort = port;      proxyPort = port;
# Line 318  public class HTTPConnection Line 318  public class HTTPConnection
318    /**    /**
319     * Indicates whether this connection is using an HTTP proxy.     * Indicates whether this connection is using an HTTP proxy.
320     */     */
321    public boolean isUsingProxy ()    public boolean isUsingProxy()
322    {    {
323      return (proxyHostname != null && proxyPort > 0);      return (proxyHostname != null && proxyPort > 0);
324    }    }
# Line 327  public class HTTPConnection Line 327  public class HTTPConnection
327     * Sets the cookie manager to use for this connection.     * Sets the cookie manager to use for this connection.
328     * @param cookieManager the cookie manager     * @param cookieManager the cookie manager
329     */     */
330    public void setCookieManager (CookieManager cookieManager)    public void setCookieManager(CookieManager cookieManager)
331    {    {
332      this.cookieManager = cookieManager;      this.cookieManager = cookieManager;
333    }    }
# Line 335  public class HTTPConnection Line 335  public class HTTPConnection
335    /**    /**
336     * Returns the cookie manager in use for this connection.     * Returns the cookie manager in use for this connection.
337     */     */
338    public CookieManager getCookieManager ()    public CookieManager getCookieManager()
339    {    {
340      return cookieManager;      return cookieManager;
341    }    }
# Line 346  public class HTTPConnection Line 346  public class HTTPConnection
346     * @param path the URI-escaped RFC2396 <code>abs_path</code> with     * @param path the URI-escaped RFC2396 <code>abs_path</code> with
347     * optional query part     * optional query part
348     */     */
349    public Request newRequest (String method, String path)    public Request newRequest(String method, String path)
350    {    {
351      if (method == null || method.length() == 0)      if (method == null || method.length() == 0)
352        {        {
# Line 356  public class HTTPConnection Line 356  public class HTTPConnection
356        {        {
357          throw new IllegalArgumentException("path must have non-zero length");          throw new IllegalArgumentException("path must have non-zero length");
358        }        }
359      Request ret = new Request (this, method, path);      Request ret = new Request(this, method, path);
360      ret.setHeader ("Host", hostname);      ret.setHeader("Host", hostname);
361      ret.setHeader ("User-Agent", userAgent);      ret.setHeader("User-Agent", userAgent);
362      ret.setHeader ("Accept-Encoding",      ret.setHeader("Connection", "keep-alive");
363                     "gzip;q=1.0, deflate;q=0.8, identity;q=0.6, *;q=0");      ret.setHeader("Accept-Encoding",
364                      "chunked;q=1.0, gzip;q=0.9, deflate;q=0.8, " +
365                      "identity;q=0.6, *;q=0");
366      if (cookieManager != null)      if (cookieManager != null)
367        {        {
368          Cookie[] cookies = cookieManager.getCookies (hostname, secure, path);          Cookie[] cookies = cookieManager.getCookies(hostname, secure, path);
369          if (cookies != null && cookies.length > 0)          if (cookies != null && cookies.length > 0)
370            {            {
371              StringBuffer buf = new StringBuffer ();              StringBuffer buf = new StringBuffer();
372              buf.append ("$Version=1");              buf.append("$Version=1");
373              for (int i = 0; i < cookies.length; i++)              for (int i = 0; i < cookies.length; i++)
374                {                {
375                  buf.append (',');                  buf.append(',');
376                  buf.append (' ');                  buf.append(' ');
377                  buf.append (cookies[i].toString ());                  buf.append(cookies[i].toString());
378                }                }
379              ret.setHeader ("Cookie", buf.toString ());              ret.setHeader("Cookie", buf.toString());
380            }            }
381        }        }
382      fireRequestEvent (RequestEvent.REQUEST_CREATED, ret);      fireRequestEvent(RequestEvent.REQUEST_CREATED, ret);
383      return ret;      return ret;
384    }    }
385    
386    /**    /**
387     * Closes this connection.     * Closes this connection.
388     */     */
389    public void close ()    public void close()
390      throws IOException      throws IOException
391    {    {
392      try      try
393        {        {
394          closeConnection ();          closeConnection();
395        }        }
396      finally      finally
397        {        {
398          fireConnectionEvent (ConnectionEvent.CONNECTION_CLOSED);          fireConnectionEvent(ConnectionEvent.CONNECTION_CLOSED);
399        }        }
400    }    }
401    
# Line 401  public class HTTPConnection Line 403  public class HTTPConnection
403     * Retrieves the socket associated with this connection.     * Retrieves the socket associated with this connection.
404     * This creates the socket if necessary.     * This creates the socket if necessary.
405     */     */
406    protected Socket getSocket ()    protected Socket getSocket()
407      throws IOException      throws IOException
408    {    {
409      if (socket == null)      if (socket == null)
410        {        {
411          String connectHostname = hostname;          String connectHostname = hostname;
412          int connectPort = port;          int connectPort = port;
413          if (isUsingProxy ())          if (isUsingProxy())
414            {            {
415              connectHostname = proxyHostname;              connectHostname = proxyHostname;
416              connectPort = proxyPort;              connectPort = proxyPort;
417            }            }
418          socket = new Socket ();          socket = new Socket();
419          InetSocketAddress address =          InetSocketAddress address =
420            new InetSocketAddress (connectHostname, connectPort);            new InetSocketAddress(connectHostname, connectPort);
421          if (connectionTimeout > 0)          if (connectionTimeout > 0)
422            {            {
423              socket.connect (address, connectionTimeout);              socket.connect(address, connectionTimeout);
424            }            }
425          else          else
426            {            {
427              socket.connect (address);              socket.connect(address);
428            }            }
429          if (timeout > 0)          if (timeout > 0)
430            {            {
431              socket.setSoTimeout (timeout);              socket.setSoTimeout(timeout);
432            }            }
433          if (secure)          if (secure)
434            {            {
435              try              try
436                {                {
437                  TrustManager tm = new EmptyX509TrustManager ();                  TrustManager tm = new EmptyX509TrustManager();
438                  SSLContext context = SSLContext.getInstance ("SSL");                  SSLContext context = SSLContext.getInstance("SSL");
439                  TrustManager[] trust = new TrustManager[] { tm };                  TrustManager[] trust = new TrustManager[] { tm };
440                  context.init (null, trust, null);                  context.init(null, trust, null);
441                  SSLSocketFactory factory =  context.getSocketFactory ();                  SSLSocketFactory factory =  context.getSocketFactory();
442                  SSLSocket ss =                  SSLSocket ss =
443                    (SSLSocket) factory.createSocket (socket, connectHostname,                    (SSLSocket) factory.createSocket(socket, connectHostname,
444                                                      connectPort, true);                                                     connectPort, true);
445                  String[] protocols = { "TLSv1", "SSLv3" };                  String[] protocols = { "TLSv1", "SSLv3" };
446                  ss.setEnabledProtocols (protocols);                  ss.setEnabledProtocols(protocols);
447                  ss.setUseClientMode (true);                  ss.setUseClientMode(true);
448                  ss.startHandshake ();                  ss.startHandshake();
449                  socket = ss;                  socket = ss;
450                }                }
451              catch (GeneralSecurityException e)              catch (GeneralSecurityException e)
452                {                {
453                  throw new IOException (e.getMessage ());                  throw new IOException(e.getMessage());
454                }                }
455            }            }
456          in = socket.getInputStream ();          in = socket.getInputStream();
457          in = new BufferedInputStream (in);          in = new BufferedInputStream(in);
458          out = socket.getOutputStream ();          out = socket.getOutputStream();
459          out = new BufferedOutputStream (out);          out = new BufferedOutputStream(out);
460        }        }
461      return socket;      return socket;
462    }    }
463    
464    protected InputStream getInputStream ()    protected InputStream getInputStream()
465      throws IOException      throws IOException
466    {    {
467      if (socket == null)      if (socket == null)
468        {        {
469          getSocket ();          getSocket();
470        }        }
471      return in;      return in;
472    }    }
473    
474    protected OutputStream getOutputStream ()    protected OutputStream getOutputStream()
475      throws IOException      throws IOException
476    {    {
477      if (socket == null)      if (socket == null)
478        {        {
479          getSocket ();          getSocket();
480        }        }
481      return out;      return out;
482    }    }
# Line 482  public class HTTPConnection Line 484  public class HTTPConnection
484    /**    /**
485     * Closes the underlying socket, if any.     * Closes the underlying socket, if any.
486     */     */
487    protected void closeConnection ()    protected void closeConnection()
488      throws IOException      throws IOException
489    {    {
490      if (socket != null)      if (socket != null)
491        {        {
492          try          try
493            {            {
494              socket.close ();              socket.close();
495            }            }
496          finally          finally
497            {            {
# Line 502  public class HTTPConnection Line 504  public class HTTPConnection
504     * Returns a URI representing the connection.     * Returns a URI representing the connection.
505     * This does not include any request path component.     * This does not include any request path component.
506     */     */
507    protected String getURI ()    protected String getURI()
508    {    {
509      StringBuffer buf = new StringBuffer ();      StringBuffer buf = new StringBuffer();
510      buf.append (secure ? "https://" : "http://");      buf.append(secure ? "https://" : "http://");
511      buf.append (hostname);      buf.append(hostname);
512      if (secure)      if (secure)
513        {        {
514          if (port != HTTPConnection.HTTPS_PORT)          if (port != HTTPConnection.HTTPS_PORT)
515            {            {
516              buf.append (':');              buf.append(':');
517              buf.append (port);              buf.append(port);
518            }            }
519        }        }
520      else      else
521        {        {
522          if (port != HTTPConnection.HTTP_PORT)          if (port != HTTPConnection.HTTP_PORT)
523            {            {
524              buf.append (':');              buf.append(':');
525              buf.append (port);              buf.append(port);
526            }            }
527        }        }
528      return buf.toString ();      return buf.toString();
529    }    }
530    
531    /**    /**
532     * Get the number of times the specified nonce has been seen by this     * Get the number of times the specified nonce has been seen by this
533     * connection.     * connection.
534     */     */
535    int getNonceCount (String nonce)    int getNonceCount(String nonce)
536    {    {
537      if (nonceCounts == null)      if (nonceCounts == null)
538        {        {
539          return 0;          return 0;
540        }        }
541      return ((Integer) nonceCounts.get (nonce)).intValue ();      return((Integer) nonceCounts.get(nonce)).intValue();
542    }    }
543    
544    /**    /**
545     * Increment the number of times the specified nonce has been seen.     * Increment the number of times the specified nonce has been seen.
546     */     */
547    void incrementNonce (String nonce)    void incrementNonce(String nonce)
548    {    {
549      int current = getNonceCount (nonce);      int current = getNonceCount(nonce);
550      if (nonceCounts == null)      if (nonceCounts == null)
551        {        {
552          nonceCounts = new HashMap ();          nonceCounts = new HashMap();
553        }        }
554      nonceCounts.put (nonce, new Integer (current + 1));      nonceCounts.put(nonce, new Integer(current + 1));
555    }    }
556    
557    // -- Events --    // -- Events --
558        
559    public void addConnectionListener (ConnectionListener l)    public void addConnectionListener(ConnectionListener l)
560    {    {
561      synchronized (connectionListeners)      synchronized (connectionListeners)
562        {        {
563          connectionListeners.add (l);          connectionListeners.add(l);
564        }        }
565    }    }
566    
567    public void removeConnectionListener (ConnectionListener l)    public void removeConnectionListener(ConnectionListener l)
568    {    {
569      synchronized (connectionListeners)      synchronized (connectionListeners)
570        {        {
571          connectionListeners.remove (l);          connectionListeners.remove(l);
572        }        }
573    }    }
574    
575    protected void fireConnectionEvent (int type)    protected void fireConnectionEvent(int type)
576    {    {
577      ConnectionEvent event = new ConnectionEvent (this, type);      ConnectionEvent event = new ConnectionEvent(this, type);
578      ConnectionListener[] l = null;      ConnectionListener[] l = null;
579      synchronized (connectionListeners)      synchronized (connectionListeners)
580        {        {
581          l = new ConnectionListener[connectionListeners.size ()];          l = new ConnectionListener[connectionListeners.size()];
582          connectionListeners.toArray (l);          connectionListeners.toArray(l);
583        }        }
584      for (int i = 0; i < l.length; i++)      for (int i = 0; i < l.length; i++)
585        {        {
586          switch (type)          switch (type)
587            {            {
588            case ConnectionEvent.CONNECTION_CLOSED:            case ConnectionEvent.CONNECTION_CLOSED:
589              l[i].connectionClosed (event);              l[i].connectionClosed(event);
590              break;              break;
591            }            }
592        }        }
593    }    }
594    
595    public void addRequestListener (RequestListener l)    public void addRequestListener(RequestListener l)
596    {    {
597      synchronized (requestListeners)      synchronized (requestListeners)
598        {        {
599          requestListeners.add (l);          requestListeners.add(l);
600        }        }
601    }    }
602    
603    public void removeRequestListener (RequestListener l)    public void removeRequestListener(RequestListener l)
604    {    {
605      synchronized (requestListeners)      synchronized (requestListeners)
606        {        {
607          requestListeners.remove (l);          requestListeners.remove(l);
608        }        }
609    }    }
610    
611    protected void fireRequestEvent (int type, Request request)    protected void fireRequestEvent(int type, Request request)
612    {    {
613      RequestEvent event = new RequestEvent (this, type, request);      RequestEvent event = new RequestEvent(this, type, request);
614      RequestListener[] l = null;      RequestListener[] l = null;
615      synchronized (requestListeners)      synchronized (requestListeners)
616        {        {
617          l = new RequestListener[requestListeners.size ()];          l = new RequestListener[requestListeners.size()];
618          requestListeners.toArray (l);          requestListeners.toArray(l);
619        }        }
620      for (int i = 0; i < l.length; i++)      for (int i = 0; i < l.length; i++)
621        {        {
622          switch (type)          switch (type)
623            {            {
624            case RequestEvent.REQUEST_CREATED:            case RequestEvent.REQUEST_CREATED:
625              l[i].requestCreated (event);              l[i].requestCreated(event);
626              break;              break;
627            case RequestEvent.REQUEST_SENDING:            case RequestEvent.REQUEST_SENDING:
628              l[i].requestSent (event);              l[i].requestSent(event);
629              break;              break;
630            case RequestEvent.REQUEST_SENT:            case RequestEvent.REQUEST_SENT:
631              l[i].requestSent (event);              l[i].requestSent(event);
632              break;              break;
633            }            }
634        }        }
635    }    }
636    
637  }  }
638    

Legend:
Removed from v.1.17  
changed lines
  Added in v.1.18

savannah-hackers-public@gnu.org
ViewVC Help
Powered by ViewVC 1.1.26