You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by js...@apache.org on 2002/12/16 04:51:04 UTC

cvs commit: jakarta-commons/httpclient/src/java/org/apache/commons/httpclient Protocol.java HostConfiguration.java HttpClient.java HttpConnection.java HttpMethodBase.java MultiThreadedHttpConnectionManager.java SimpleHttpConnectionManager.java

jsdever     2002/12/15 19:51:04

  Modified:    httpclient/src/java/org/apache/commons/httpclient
                        HostConfiguration.java HttpClient.java
                        HttpConnection.java HttpMethodBase.java
                        MultiThreadedHttpConnectionManager.java
                        SimpleHttpConnectionManager.java
  Added:       httpclient/src/java/org/apache/commons/httpclient
                        Protocol.java
  Log:
  Add a new Protocol class.
  
  Contributed by: Michael Becke
  Committed by: Jeff Dever
  
  Revision  Changes    Path
  1.3       +24 -9     jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HostConfiguration.java
  
  Index: HostConfiguration.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HostConfiguration.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- HostConfiguration.java	3 Dec 2002 14:45:48 -0000	1.2
  +++ HostConfiguration.java	16 Dec 2002 03:51:03 -0000	1.3
  @@ -71,7 +71,7 @@
   
       private String host;
       private int port;
  -    private String protocol;
  +    private Protocol protocol;
       private boolean hostSet;
       
       private String proxyHost;
  @@ -141,7 +141,7 @@
               return ( 
                   host.equalsIgnoreCase(connection.getHost())
                   && port == connection.getPort()
  -                && protocol.equalsIgnoreCase(connection.getProtocol())
  +                && protocol.equals(connection.getProtocol())
               );
               
           } else {
  @@ -177,10 +177,25 @@
           return hostSet;
       }
   
  +    public synchronized void setHost(
  +        String host,
  +        int port,
  +        String protocol
  +    ) {
  +        setHost( host, port, Protocol.getProtocol(protocol) );
  +    }
  +    
  +    /**
  +     * Sets this configuration's host infomation.
  +     * 
  +     * @param host the host, IP or DNS name
  +     * @param port the host port or -1 to use protocol default
  +     * @param protocol the protocol
  +     */
       public synchronized void setHost( 
           String host, 
           int port, 
  -        String protocol 
  +        Protocol protocol 
       ) {
           if ( host == null ) {
               throw new IllegalArgumentException( "host must not be null" );   
  @@ -205,9 +220,9 @@
               );   
           }
           
  -        String url = protocol + "://" + host;
  +        String url = protocol.getScheme() + "://" + host;
           
  -        if ( port != -1 ) {
  +        if ( port != -1 && port != protocol.getDefaultPort() ) {
               url += ":" + port;
           }
           
  @@ -235,7 +250,7 @@
        * Returns the protocol.
        * @return String
        */
  -    public synchronized String getProtocol() {
  +    public synchronized Protocol getProtocol() {
           return protocol;
       }
       
  
  
  
  1.63      +17 -41    jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpClient.java
  
  Index: HttpClient.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpClient.java,v
  retrieving revision 1.62
  retrieving revision 1.63
  diff -u -r1.62 -r1.63
  --- HttpClient.java	3 Dec 2002 15:28:18 -0000	1.62
  +++ HttpClient.java	16 Dec 2002 03:51:03 -0000	1.63
  @@ -65,8 +65,6 @@
   import java.io.IOException;
   import java.net.URL;
   
  -import javax.net.ssl.SSLSocketFactory;
  -
   import org.apache.commons.logging.Log;
   import org.apache.commons.logging.LogFactory;
   
  @@ -131,8 +129,6 @@
        */
       private HttpState state;
   
  -    private SSLSocketFactory sslSocketFactory = null;
  -
       /** the timout when waiting for a connection from the connectionManager */
       private long httpConnectionTimeout = 0;
   
  @@ -187,15 +183,6 @@
       public synchronized boolean isStrictMode() {
           return strictMode;
       }
  -    
  -    /**
  -     * Specifies an alternative factory for SSL sockets.
  -     * @see HttpConnection#setSSLSocketFactory(SSLSocketFactory) HttpConnection.setSSLSocketFactory
  -     * @param sslSocketFactory a living instance of the alternative SSLSocketFactory
  -     */
  -    public synchronized void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
  -        this.sslSocketFactory = sslSocketFactory;
  -    }
   
       /**
        * Sets the SO_TIMEOUT which is the timeout for waiting for data.
  @@ -352,12 +339,9 @@
               log.error("no scheme to start a session");
               throw new IllegalStateException("no scheme to start a session");
           }
  -        boolean secure = scheme.equalsIgnoreCase("https") ? true : false;
  -        if (!(secure || scheme.equalsIgnoreCase("http"))) {
  -            log.error("http and https scheme only supported");
  -            throw new IllegalStateException
  -                ("http and https scheme only supported");
  -        }
  +
  +        Protocol protocol = Protocol.getProtocol( scheme );
  +
           String userinfo = uri.getUserinfo();
           if (userinfo != null) {
               getState().setCredentials(null,
  @@ -374,11 +358,7 @@
               throw new IllegalStateException
                   ("HttpURL or HttpsURL instance required");
           }
  -        this.hostConfiguration.setHost(
  -            host,
  -            port,
  -            secure ? "https" : "http"
  -        );
  +        this.hostConfiguration.setHost( host, port, protocol );
       }
   
       /**
  @@ -399,16 +379,15 @@
       public void startSession(URL url) {
           log.trace("enter HttpClient.startSession(String, int, Credentials, boolean)");
   
  -        if ("https".equalsIgnoreCase(url.getProtocol())) {
  -        startSession(url.getHost(), url.getPort() == -1 ? 443
  -          : url.getPort(), true);
  -        } else if ("http".equalsIgnoreCase(url.getProtocol())) {
  -            startSession(url.getHost(), url.getPort() == -1 ? 80
  -          : url.getPort(), false);
  -        } else {
  -            throw new IllegalArgumentException("Protocol " + url.getProtocol()
  -          + " not supported in URL " + url);
  -        }
  +        int port = url.getPort();
  +        Protocol protocol = Protocol.getProtocol( url.getProtocol() );
  +
  +        hostConfiguration.setHost( 
  +            url.getHost(), 
  +            port,
  +            protocol
  +        );
  +
       }
   
       /**
  @@ -515,7 +494,6 @@
   
           int soTimeout = 0;
           boolean strictMode = false;
  -        SSLSocketFactory socketFactory = null;
           int connectionTimeout = 0;
           long httpConnectionTimeout = 0;
           HttpState state = null;
  @@ -528,7 +506,6 @@
           synchronized ( this ) {
               soTimeout = this.timeoutInMilliseconds;
               strictMode = this.strictMode;
  -            socketFactory = this.sslSocketFactory;
               connectionTimeout = this.connectionTimeout;
               httpConnectionTimeout = this.httpConnectionTimeout;
               state = getState();
  @@ -562,7 +539,6 @@
           method.setStrictMode(strictMode);
           
           if (!connection.isOpen()) {
  -            connection.setSSLSocketFactory(socketFactory);
               connection.setSoTimeout(soTimeout);
               connection.setConnectionTimeout(connectionTimeout);
               connection.open();
  
  
  
  1.28      +108 -84   jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpConnection.java
  
  Index: HttpConnection.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpConnection.java,v
  retrieving revision 1.27
  retrieving revision 1.28
  diff -u -r1.27 -r1.28
  --- HttpConnection.java	9 Dec 2002 09:16:16 -0000	1.27
  +++ HttpConnection.java	16 Dec 2002 03:51:04 -0000	1.28
  @@ -72,6 +72,8 @@
   import java.lang.reflect.Method;
   import java.net.Socket;
   import java.net.SocketException;
  +
  +import javax.net.SocketFactory;
   import javax.net.ssl.SSLSocketFactory;
   
   
  @@ -113,6 +115,17 @@
       /**
        * Constructor.
        *
  +     * @param host the host I should connect to
  +     * @param port the port I should connect to
  +     * @param protocol the protocol to use
  +     */
  +    public HttpConnection(String host, int port, Protocol protocol) {
  +        this(null, -1, host, port, protocol);
  +    }
  +
  +    /**
  +     * Constructor.
  +     *
        * @param proxyHost the host I should proxy via
        * @param proxyPort the port I should proxy via
        * @param host the host I should connect to
  @@ -133,37 +146,49 @@
        */
       public HttpConnection(String proxyHost, int proxyPort, String host,
       int port, boolean secure) {
  -        if  (log.isDebugEnabled()){
  -            log.debug("HttpConnectionManager.getConnection:  creating "
  +        this( 
  +            proxyHost, 
  +            proxyPort, 
  +            host, 
  +            port, 
  +            Protocol.getProtocol( secure ? "https" : "http" )
  +        );
  +    }
  +
  +    public HttpConnection(
  +        String proxyHost, 
  +        int proxyPort, 
  +        String host,
  +        int port, 
  +        Protocol protocol
  +    ) {
  +
  +        if( log.isDebugEnabled() ){
  +            log.debug(
  +                "HttpConnectionManager.getConnection:  creating "
                   + " connection for " + host + ":" + port + " via " + proxyHost
  -                + ":" + proxyPort);
  +                + ":" + proxyPort + " using protocol: " + protocol
  +            );
           }
  -
  -        if (host == null) {
  -            throw new NullPointerException("host parameter is null");
  +        
  +        if ( host == null ) {
  +            throw new IllegalArgumentException("host parameter is null");
  +        }        
  +        if ( protocol == null ) {
  +            throw new IllegalArgumentException( "protocol is null" );
           }
  +        
           _proxyHost = proxyHost;
           _proxyPort = proxyPort;
           _host = host;
  -        _port = port;
  -        _ssl = secure;
  +        _port = protocol.resolvePort( port );
  +        _protocol = protocol;
  +        
       }
   
       // ------------------------------------------ Attribute Setters and Getters
   
       /**
  -     * Specifies an alternative factory for SSL sockets. If <code>factory</code>
  -     * is <code>null</code> the default implementation is used.
  -     *
  -     * @param factory An instance of a SSLSocketFactory or <code>null</code>.
  -     * @throws IllegalStateException If called after the connection was opened
  -     */
  -    public void setSSLSocketFactory(SSLSocketFactory factory) {
  -        assertNotOpen();
  -        sslSocketFactory = factory;
  -    }
  -
  -    /**
        * Return my host.
        *
        * @return my host.
  @@ -261,28 +286,50 @@
        *         secure (HTTPS/SSL) protocol.
        */
       public boolean isSecure() {
  -        return _ssl;
  +        return _protocol.isSecure();
       }
   
       /**
        * Get the protocol.
        * @return HTTPS if secure, HTTP otherwise
        */
  -    public String getProtocol() {
  -        return (isSecure() ? "HTTPS" : "HTTP");
  +    public Protocol getProtocol() {
  +        return _protocol;
       }
   
  -
  -
       /**
        * Set whether or not I should connect over HTTPS (SSL).
        *
        * @param secure whether or not I should connect over HTTPS (SSL).
        * @throws IllegalStateException if I am already connected
  +     * 
  +     * @deprecated use setProtocol(Protocol)
  +     * 
  +     * @see #setProtocol(Protocol)
        */
       public void setSecure(boolean secure) throws IllegalStateException {
           assertNotOpen();
  -        _ssl = secure;
  +        _protocol = (
  +            secure 
  +            ? Protocol.getProtocol( "https" ) 
  +            : Protocol.getProtocol( "http" )
  +        );
  +    }
  +
  +    /**
  +     * Sets the protocol used by this connection.
  +     * 
  +     * @param protocol
  +     */
  +    public void setProtocol( Protocol protocol ) {
  +        assertNotOpen();
  +        
  +        if ( protocol == null ) {
  +            throw new IllegalArgumentException( "protocol is null" );
  +        }
  +        
  +        _protocol = protocol;
  +        
       }
   
       /**
  @@ -382,40 +429,31 @@
           assertNotOpen(); // ??? is this worth doing?
           try {
               if (null == _socket) {
  +                
                   final String host = (null == _proxyHost) ? _host : _proxyHost;
                   final int port = (null == _proxyHost) ? _port : _proxyPort;
  -                if (isSecure() && !isProxied()) {
  -                    if (sslSocketFactory == null) {
  -                        sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  -                    }
  -                    if (connect_timeout == 0) {
  -                        _socket = (new SocketCreator()).createSocket(host,port);
  -                    } else {
  -                        SocketTask task = new SocketTask() {
  -                            public void doit() throws IOException {
  -                                s = (new SocketCreator()).createSocket(host,port);
  -                            }
  -                        };
  -                        TimeoutController.execute(task, connect_timeout);
  -                        _socket = task.s;
  -                        if (task.exception != null) throw task.exception;
  -                    }
  -                    _usingSecureSocket = true;
  +                
  +                _usingSecureSocket = _protocol.isSecure();                
  +                
  +                final SocketFactory socketFactory = (
  +                    isSecure() && !isProxied()
  +                    ? _protocol.getSocketFactory()
  +                    : SocketFactory.getDefault()
  +                );
  +                
  +                if (connect_timeout == 0) {
  +                    _socket = socketFactory.createSocket(host,port);
                   } else {
  -                    if (connect_timeout == 0) {
  -                        _socket = new Socket(host,port);
  -                    } else {
  -                        SocketTask task = new SocketTask() {
  -                            public void doit() throws IOException {
  -                                s = new Socket(host,port);
  -                            }
  -                        };
  -                        TimeoutController.execute(task, connect_timeout);
  -                        _socket = task.s;
  -                        if (task.exception != null) throw task.exception;
  -                    }
  -                    _usingSecureSocket = false;
  +                    SocketTask task = new SocketTask() {
  +                        public void doit() throws IOException {
  +                            s = socketFactory.createSocket(host,port);
  +                        }
  +                    };
  +                    TimeoutController.execute(task, connect_timeout);
  +                    _socket = task.s;
  +                    if (task.exception != null) throw task.exception;
                   }
  +                
               }
               _socket.setSoTimeout(_so_timeout);
               _input = _socket.getInputStream();
  @@ -451,16 +489,16 @@
           log.trace("enter HttpConnection.tunnelCreated()");
   
           if (!isSecure() || !isProxied()) {
  -        throw new IllegalStateException("Connection must be secure and proxied to use this feature");
  -    }
  +            throw new IllegalStateException("Connection must be secure and proxied to use this feature");
  +        }
  +        
           if (_usingSecureSocket) {
  -        throw new IllegalStateException("Already using a secure socket");
  -    }
  -
  -        if (sslSocketFactory == null) {
  -            sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  +            throw new IllegalStateException("Already using a secure socket");
           }
  -        _socket = (new SocketCreator()).createSocket(_socket, _host, _port, true);
  +
  +        SSLSocketFactory socketFactory = (SSLSocketFactory)_protocol.getSocketFactory();
  +
  +        _socket = socketFactory.createSocket(_socket, _host, _port, true);
           _input = _socket.getInputStream();
           _output = _socket.getOutputStream();
           _usingSecureSocket = true;
  @@ -892,18 +930,6 @@
               }
           }
       }
  -
  -    // -- javax.net binary isolation
  -
  -    private class SocketCreator {
  -        public Socket createSocket(Socket socket, String host, int port, boolean auto) throws IOException {
  -            return sslSocketFactory.createSocket(socket, host, port, auto);
  -        }
  -
  -        public Socket createSocket(String host, int port) throws IOException {
  -            return sslSocketFactory.createSocket(host, port);
  -        }
  -    }
       
       // ------------------------------------------------------------- Attributes
   
  @@ -929,14 +955,12 @@
       private InputStream _lastResponseInput = null;
       /** Whether or not I am connected. */
       private boolean _open = false;
  -    /** Whether or not I am/should connect via SSL. */
  -    private boolean _ssl = false;
  +    /** the protocol being used */
  +    private Protocol _protocol;
       /** <tt>"\r\n"</tt>, as bytes. */
       private static final byte[] CRLF = "\r\n".getBytes();
       /** SO_TIMEOUT value */
       private int _so_timeout = 0;
  -    /** An alternative factory for SSL sockets to use */
  -    private SSLSocketFactory sslSocketFactory = null;
       /** Whether or not the _socket is a secure one. Note the difference to _ssl */
       private boolean _usingSecureSocket = false;
       /** Whether I am tunneling a proxy or not */
  
  
  
  1.89      +9 -9      jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java
  
  Index: HttpMethodBase.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java,v
  retrieving revision 1.88
  retrieving revision 1.89
  diff -u -r1.88 -r1.89
  --- HttpMethodBase.java	16 Dec 2002 01:40:51 -0000	1.88
  +++ HttpMethodBase.java	16 Dec 2002 03:51:04 -0000	1.89
  @@ -936,7 +936,7 @@
           URL currentUrl = null;
   
           try {
  -            currentUrl = new URL(conn.getProtocol().toLowerCase(),
  +            currentUrl = new URL(conn.getProtocol().getScheme(),
                   conn.getHost(), conn.getPort(), "");
               redirectUrl = new URL(location);
           } catch (MalformedURLException e) {
  @@ -1268,11 +1268,11 @@
           }
   
           //appends the port only if not using the default port for the protocol
  -        if (conn.isSecure()) {
  -            setRequestHeader("Host", (port == 443) ? host : host + ':' + port);
  -        } else {
  -            setRequestHeader("Host", (port == 80) ? host : host + ':' + port);
  +        if ( conn.getProtocol().getDefaultPort() != port ) {
  +            host += (":" + port);
           }
  +            
  +        setRequestHeader("Host", host);
       }
   
       /**
  
  
  
  1.3       +9 -38     jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java
  
  Index: MultiThreadedHttpConnectionManager.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- MultiThreadedHttpConnectionManager.java	9 Dec 2002 09:16:16 -0000	1.2
  +++ MultiThreadedHttpConnectionManager.java	16 Dec 2002 03:51:04 -0000	1.3
  @@ -148,32 +148,6 @@
       }
   
       /**
  -     * Return the port provided if not -1 (default), return 443 if the
  -     * protocol is HTTPS, otherwise 80.
  -     *
  -     * This functionality is a URLUtil and may be better off in URIUtils
  -     *
  -     * @param protocol the protocol to use to get the port for, e.g. http or
  -     *      https
  -     * @param port the port provided with the url (could be -1)
  -     * @return the port for the specified port and protocol.
  -     */
  -    private static int getPort(String protocol, int port) {
  -        log.trace("HttpConnectionManager.getPort(String, port)");
  -
  -        // default to provided port
  -        int portForProtocol = port;
  -        if (portForProtocol == -1) {
  -            if (protocol.equalsIgnoreCase("HTTPS")) {
  -                portForProtocol = 443;
  -            } else {
  -                portForProtocol = 80;
  -            }
  -        }
  -        return portForProtocol;
  -    }
  -
  -    /**
        * @see HttpConnectionManager#getConnection(HostConfiguration, long)
        */
       public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
  @@ -185,12 +159,10 @@
           }
   
           // Get the protocol and port (use default port if not specified)
  -        String protocol = hostConfiguration.getProtocol();
  +        Protocol protocol = hostConfiguration.getProtocol();
           String host = hostConfiguration.getHost();
  -        int port = MultiThreadedHttpConnectionManager.getPort(
  -            protocol,
  -            hostConfiguration.getPort()
  -        );
  +        int port = protocol.resolvePort( hostConfiguration.getPort() );
  +            
           String hostAndPort = host + ":" + port;
   
           if (log.isDebugEnabled()) {
  @@ -205,7 +177,7 @@
               connectionPool,
               host,
               port,
  -            protocol.equalsIgnoreCase("HTTPS"),
  +            protocol,
               hostConfiguration.getProxyHost(),
               hostConfiguration.getProxyPort(),
               timeout
  @@ -222,7 +194,6 @@
        * @param connectionPool
        * @param host
        * @param port
  -     * @param useHttps
        * @param proxyHost
        * @param proxyPort
        * @param timeout the number of milliseconds to wait for a connection, 0 to
  @@ -237,7 +208,7 @@
           HostConnectionPool connectionPool,
           String host,
           int port,
  -        boolean useHttps,
  +        Protocol protocol,
           String proxyHost,
           int proxyPort,
           long timeout
  @@ -262,7 +233,7 @@
                               proxyPort,
                               host,
                               port,
  -                            useHttps
  +                            protocol
                           );
                           connection.setHttpConnectionManager( this );
                           connectionPool.numConnections++;
  
  
  
  1.3       +7 -8      jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/SimpleHttpConnectionManager.java
  
  Index: SimpleHttpConnectionManager.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/SimpleHttpConnectionManager.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- SimpleHttpConnectionManager.java	9 Dec 2002 09:16:16 -0000	1.2
  +++ SimpleHttpConnectionManager.java	16 Dec 2002 03:51:04 -0000	1.3
  @@ -102,10 +102,9 @@
       public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
           throws MalformedURLException {
   
  -        String protocol = hostConfiguration.getProtocol();
  +        Protocol protocol = hostConfiguration.getProtocol();
           String host = hostConfiguration.getHost();
           int port = hostConfiguration.getPort();
  -        boolean isSecure = protocol.equalsIgnoreCase("HTTPS");
   
           if ( httpConnection == null ) {
   
  @@ -115,10 +114,10 @@
                       hostConfiguration.getProxyPort(),
                       host,
                       port,
  -                    isSecure
  +                    protocol
                   );
               } else {
  -                httpConnection = new HttpConnection(host, port, isSecure);
  +                httpConnection = new HttpConnection(host, port, protocol);
               }
   
           } else {
  @@ -135,7 +134,7 @@
   
                   httpConnection.setHost(host);
                   httpConnection.setPort(port);
  -                httpConnection.setSecure(isSecure);
  +                httpConnection.setProtocol(protocol);
   
                   httpConnection.setProxyHost(hostConfiguration.getProxyHost());
                   httpConnection.setProxyPort(hostConfiguration.getProxyPort());
  
  
  
  1.1                  jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Protocol.java
  
  Index: Protocol.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Protocol.java,v 1.1 2002/12/16 03:51:04 jsdever Exp $
   * $Revision: 1.1 $
   * $Date: 2002/12/16 03:51:04 $
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2002 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowlegement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  package org.apache.commons.httpclient;
  
  import java.util.Collections;
  import java.util.HashMap;
  import java.util.Map;
  
  import javax.net.SocketFactory;
  import javax.net.ssl.SSLSocketFactory;
  
  
  /**
   * A class to encapsulate the specifics of a protocol.  This class class also
   * provides the ability to customize the set and characteristics of the
   * protocols used.
   * 
   * <p>One use case for modifying the default set of protocols would be to set a
   * custom SSL socket factory.  This would look something like the following:
   * <pre> 
   * Protocol myHTTPS = new Protocol( "https", new MySSLSocketFactory(), 443 );
   * 
   * Protocol.registerProtocol( "https", myHTTPS );
   * </pre>
   *
   * @author Michael Becke 
   * @author Jeff Dever
   *  
   * @since 2.0 
   */
  public class Protocol {
  
      private static Map protocols = Collections.synchronizedMap( new HashMap() );
  
      /**
       * Registers a new protocol with the given identifier.  If a protocol with
       * the given ID already exists it will be overridden.  This ID is the same
       * one used to retrieve the protocol from getProtocol(String).
       * 
       * @param id the identifier for this protocol
       * @param protocol the protocol to register
       * 
       * @see #getProtocol(String)
       */
      public static void registerProtocol( String id, Protocol protocol ) {
  
          if ( id == null ) {
              throw new IllegalArgumentException( "id is null" );
          }
          if ( protocol == null ) {
              throw new IllegalArgumentException( "protocol is null" );
          }
  
          protocols.put( id, protocol );
  
      }
  
      /**
       * Unregisters the protocol with the given ID.
       * 
       * @param id the ID of the protocol to remove
       */
      public static void unregisterProtocol( String id ) {
  
          if ( id == null ) {
              throw new IllegalArgumentException( "id is null" );
          }
  
          protocols.remove( id );
  
      }
  
      /**
       * Gets the protocol with the given ID.
       * 
       * @param id the protocol ID
       * 
       * @return Protocol a protocol
       * 
       * @throws IllegalStateException if a protocol with the ID cannot be found
       */
      public static Protocol getProtocol( String id ) {
  
          if ( id == null ) {
              throw new IllegalArgumentException( "id is null" );
          }
  
          Protocol protocol = (Protocol)protocols.get( id );
  
          if ( protocol == null ) {
              protocol = lazyRegisterProtocol(id);
          }
  
          return protocol;
  
      } 
  
      /**
       * Lazily registers the protocol with the given id.
       * 
       * @param id the protocol ID
       * 
       * @return the lazily registered protocol
       * 
       * @throws IllegalStateException if the protocol with id is not recognized
       */
      private static Protocol lazyRegisterProtocol(String id) {
  
          if ("http".equals(id)) {
              Protocol HTTP = new Protocol(
                      "http",
                      SocketFactory.getDefault(),
                      80
                      );
              Protocol.registerProtocol( "http", HTTP );
              return HTTP;
          }
  
          if ("https".equals(id)) {
              Protocol HTTPS = new Protocol(
                      "https",
                      (SSLSocketFactory)SSLSocketFactory.getDefault(),
                      443
                      );
              Protocol.registerProtocol( "https", HTTPS );
              return HTTPS;
          }
  
          throw new IllegalStateException( "unsupported protocol: '" + id + "'");
  
      }
      
  
      /** the scheme of this protocol (e.g. http, https) */
      private String scheme;
      
      private SocketFactory socketFactory;
      
      private int defaultPort;
      
      private boolean secure;
    
      /**
       * Constructs a new Protocol.  The created protcol is insecure.
       * 
       * @param scheme the scheme (e.g. http, https)
       * @param factory the factory for creating sockets for communication using
       * this protocol
       * @param defaultPort the port this protocol defaults to
       */
      public Protocol( String scheme, SocketFactory factory, int defaultPort ) {
          
          if ( scheme == null ) {
              throw new IllegalArgumentException( "scheme is null" );
          }
          if ( factory == null ) {
              throw new IllegalArgumentException( "socketFactory is null" );
          }
          if ( defaultPort <= 0 ) {
              throw new IllegalArgumentException( "port is invalid: " + defaultPort );
          }
          
          this.scheme = scheme;
          this.socketFactory = factory;
          this.defaultPort = defaultPort;
          this.secure = false;
          
      }
      
      /**
       * Constructs a new Protocol.  The created protcol is secure.
       *
       * @param scheme the scheme (e.g. http, https)
       * @param factory the factory for creating sockets for communication using
       * this protocol
       * @param defaultPort the port this protocol defaults to
       */
      public Protocol( String scheme, SSLSocketFactory factory, int defaultPort ) {
          
          if ( scheme == null ) {
              throw new IllegalArgumentException( "scheme is null" );
          }
          if ( factory == null ) {
              throw new IllegalArgumentException( "socketFactory is null" );
          }
          if ( defaultPort <= 0 ) {
              throw new IllegalArgumentException( "port is invalid: " + defaultPort );
          }
  
          this.scheme = scheme;
          this.socketFactory = factory;
          this.defaultPort = defaultPort;
          this.secure = true;        
          
      }
  
      /**
       * Returns the defaultPort.
       * @return int
       */
      public int getDefaultPort() {
          return defaultPort;
      }
  
      /**
       * Returns the socketFactory.  If secure the factory is a SSLSocketFactory.
       * @return SocketFactory
       */
      public SocketFactory getSocketFactory() {
          return socketFactory;
      }
  
      /**
       * Returns the scheme.
       * @return String
       */
      public String getScheme() {
          return scheme;
      }
  
      /**
       * Returns the secure.
       * @return boolean
       */
      public boolean isSecure() {
          return secure;
      }
      
      /**
       * Resolves the correct port for this protocol.  Returns the given port if
       * valid or the default port otherwise.
       * 
       * @param port the port to be resolved
       * 
       * @return the given port or the defaultPort
       */
      public int resolvePort( int port ) {
          return port <= 0 ? getDefaultPort() : port;
      }
  
      /**
       * @see java.lang.Object#toString()
       */
      public String toString() {
          return scheme + ":" + defaultPort;
      }
  
  }
  
  
  

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>