commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ol...@apache.org
Subject cvs commit: jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server SimpleConnList.java SimpleConnManager.java SimpleConnSet.java SimpleHost.java ErrorResponse.java HttpServiceHandler.java ProxyAuthRequestHandler.java ProxyRequestHandler.java SimpleConnectionThread.java SimpleHttpServer.java SimpleHttpServerConnection.java SimpleProxy.java SimpleRequest.java SimpleResponse.java SimpleConnPool.java
Date Sat, 13 Nov 2004 12:21:29 GMT
olegk       2004/11/13 04:21:29

  Modified:    httpclient/src/test/org/apache/commons/httpclient
                        TestProxy.java TestRedirects.java
               httpclient/src/test/org/apache/commons/httpclient/server
                        ErrorResponse.java HttpServiceHandler.java
                        ProxyAuthRequestHandler.java
                        ProxyRequestHandler.java
                        SimpleConnectionThread.java SimpleHttpServer.java
                        SimpleHttpServerConnection.java SimpleProxy.java
                        SimpleRequest.java SimpleResponse.java
  Added:       httpclient/src/test/org/apache/commons/httpclient/server
                        SimpleConnList.java SimpleConnManager.java
                        SimpleConnSet.java SimpleHost.java
  Removed:     httpclient/src/test/org/apache/commons/httpclient/server
                        SimpleConnPool.java
  Log:
  Changelog:
  
  * A complete rewrite of the SimpleProxy framework
  * SimpleProxy now supports connection persistence (keep-alive support)
  
  Contributed by Oleg Kalnichevski
  
  Revision  Changes    Path
  1.7       +39 -5     jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/TestProxy.java
  
  Index: TestProxy.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/TestProxy.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- TestProxy.java	13 Jun 2004 12:13:08 -0000	1.6
  +++ TestProxy.java	13 Nov 2004 12:21:28 -0000	1.7
  @@ -24,13 +24,13 @@
    * 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 org.apache.commons.httpclient.auth.AuthScope;
   import org.apache.commons.httpclient.methods.GetMethod;
  +import org.apache.commons.httpclient.methods.PostMethod;
  +import org.apache.commons.httpclient.methods.StringRequestEntity;
   import org.apache.commons.httpclient.protocol.Protocol;
   import org.apache.commons.httpclient.server.SimpleProxy;
   
  @@ -95,4 +95,38 @@
           get.releaseConnection();
       }
   
  +        public void testSimplePost() throws Exception {
  +        SimpleProxy proxy = new SimpleProxy();
  +
  +        HttpClient client = new HttpClient();
  +        HostConfiguration hc = new HostConfiguration();
  +        hc.setHost(TARGET_HOST, TARGET_PORT, Protocol.getProtocol("http"));
  +        hc.setProxy(proxy.getLocalAddress(), proxy.getLocalPort());
  +        client.setHostConfiguration(hc);
  +
  +        PostMethod post = new PostMethod("/httpclienttest/body");
  +        post.setRequestEntity(new StringRequestEntity("Like tons of stuff"));
  +        client.executeMethod(post);
  +        assertEquals(200, post.getStatusCode());
  +        post.releaseConnection();
  +    }
  +
  +    public void testAuthPost() throws Exception {
  +        Credentials creds = new UsernamePasswordCredentials("user", "password");
  +        SimpleProxy proxy = new SimpleProxy();
  +        proxy.requireCredentials(creds);
  +
  +        HttpClient client = new HttpClient();
  +        HostConfiguration hc = new HostConfiguration();
  +        hc.setHost(TARGET_HOST, TARGET_PORT, Protocol.getProtocol("http"));
  +        hc.setProxy(proxy.getLocalAddress(), proxy.getLocalPort());
  +        client.setHostConfiguration(hc);
  +        client.getState().setProxyCredentials(AuthScope.ANY, creds);
  +
  +        PostMethod post = new PostMethod("/httpclienttest/body");
  +        post.setRequestEntity(new StringRequestEntity("Like tons of stuff"));
  +        client.executeMethod(post);
  +        assertEquals(200, post.getStatusCode());
  +        post.releaseConnection();
  +    }
   }
  
  
  
  1.8       +4 -30     jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/TestRedirects.java
  
  Index: TestRedirects.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/TestRedirects.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- TestRedirects.java	7 Nov 2004 12:31:42 -0000	1.7
  +++ TestRedirects.java	13 Nov 2004 12:21:28 -0000	1.8
  @@ -37,7 +37,6 @@
   import org.apache.commons.httpclient.methods.PostMethod;
   import org.apache.commons.httpclient.methods.StringRequestEntity;
   import org.apache.commons.httpclient.params.HttpClientParams;
  -import org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory;
   import org.apache.commons.httpclient.protocol.Protocol;
   import org.apache.commons.httpclient.server.HttpService;
   import org.apache.commons.httpclient.server.RequestLine;
  @@ -458,31 +457,6 @@
           }
           thatserver.destroy();
       }
  -
  -    public void testCrossProtocolRedirect() throws IOException {
  -    	
  -        String host = this.server.getLocalAddress();
  -        int port = this.server.getLocalPort();
  -
  -    	Protocol.registerProtocol("test", new Protocol("test", 
  -    			new DefaultProtocolSocketFactory(), port));
  -        
  -        this.server.setHttpService(new BasicRedirectService(host, port));
  -        GetMethod httpget = new GetMethod("test://" + host + "/oldlocation/");
  -        httpget.setFollowRedirects(true);
  -        try {
  -            this.client.executeMethod(httpget);
  -            assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
  -            assertEquals("/newlocation/", httpget.getPath());
  -            assertEquals(host, httpget.getURI().getHost());
  -            assertEquals(port, httpget.getURI().getPort());
  -            assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI());
  -        } finally {
  -            httpget.releaseConnection();
  -        }
  -        
  -        Protocol.unregisterProtocol("test");
  -    }    
   
       public void testRedirectWithCookie() throws IOException {
       	
  
  
  
  1.6       +5 -17     jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/ErrorResponse.java
  
  Index: ErrorResponse.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/ErrorResponse.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- ErrorResponse.java	4 Nov 2004 19:40:51 -0000	1.5
  +++ ErrorResponse.java	13 Nov 2004 12:21:28 -0000	1.6
  @@ -43,26 +43,14 @@
    * @author Christian Kohlschuetter
    */
   public class ErrorResponse {
  -    private static ErrorResponse instance = null;
  -    public static synchronized ErrorResponse getInstance() {
  -        if(instance == null) {
  -            instance = new ErrorResponse();
  -        }
  -        return instance;
  -    }
       
  -    private final HashMap responses = new HashMap();
  +    private static final HashMap responses = new HashMap();
       
       private ErrorResponse() {
           super();
       }
       
  -    public void setResponse(int statusCode, SimpleResponse response) {
  -        Integer code = new Integer(statusCode);
  -        responses.put(code, response);
  -    }
  -    
  -    public SimpleResponse getResponse(int statusCode) {
  +    public static SimpleResponse getResponse(int statusCode) {
           Integer code = new Integer(statusCode);
           SimpleResponse response = (SimpleResponse)responses.get(code);
           if (response == null) {
  
  
  
  1.8       +15 -15    jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/HttpServiceHandler.java
  
  Index: HttpServiceHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/HttpServiceHandler.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- HttpServiceHandler.java	9 Nov 2004 04:25:05 -0000	1.7
  +++ HttpServiceHandler.java	13 Nov 2004 12:21:28 -0000	1.8
  @@ -30,10 +30,10 @@
   package org.apache.commons.httpclient.server;
   
   import java.io.IOException;
  +import java.io.InputStream;
   
   import org.apache.commons.httpclient.Header;
   import org.apache.commons.httpclient.HttpVersion;
  -import org.apache.commons.httpclient.methods.RequestEntity;
   
   /**
    * This request handler provides service interface similar to that of Servlet API.
  @@ -65,33 +65,33 @@
           SimpleResponse response = new SimpleResponse();
           this.service.process(request, response);
           
  +        // Nake sure the request if fully consumed
  +        request.getBodyBytes();
  +        
           // Ensure there's a content type header
           if (!response.containsHeader("Content-Type")) {
  -            if (response.getEntity() != null) {
  -                Header header = new Header("Content-Type", response.getEntity().getContentType()); 
  -                response.addHeader(header);
  -            }
  +            response.addHeader(new Header("Content-Type", "text/plain"));
           }
           
           // Ensure there's a content length or transfer encoding header
           if (!response.containsHeader("Content-Length") && !response.containsHeader("Transfer-Encoding")) {
  -            RequestEntity entity = response.getEntity();
  -            if (entity != null) {
  -                long len = entity.getContentLength();
  +            InputStream content = response.getBody();
  +            if (content != null) {
  +                long len = response.getContentLength();
                   if (len < 0) {
                       if (response.getHttpVersion().lessEquals(HttpVersion.HTTP_1_0)) {
                           throw new IOException("Chunked encoding not supported for HTTP version " 
                                   + response.getHttpVersion());
                       }
                       Header header = new Header("Transfer-Encoding", "chunked"); 
  -                    response.setHeader(header);                
  +                    response.addHeader(header);                
                   } else {
                       Header header = new Header("Content-Length", Long.toString(len)); 
                       response.setHeader(header);
                   }
               } else {
                   Header header = new Header("Content-Length", "0"); 
  -                response.setHeader(header);
  +                response.addHeader(header);
               }
           }
   
  @@ -120,9 +120,9 @@
           }
           if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
               // this is a head request, we don't want to send the actualy content
  -            response.setBodyEntity(null);
  +            response.setBody(null);
           }
  -         conn.writeResponse(response);
  +        conn.writeResponse(response);
           return true;
       }
       
  
  
  
  1.11      +19 -41    jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/ProxyAuthRequestHandler.java
  
  Index: ProxyAuthRequestHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/ProxyAuthRequestHandler.java,v
  retrieving revision 1.10
  retrieving revision 1.11
  diff -u -r1.10 -r1.11
  --- ProxyAuthRequestHandler.java	7 Nov 2004 19:57:08 -0000	1.10
  +++ ProxyAuthRequestHandler.java	13 Nov 2004 12:21:28 -0000	1.11
  @@ -25,8 +25,6 @@
    * 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.server;
  @@ -35,6 +33,7 @@
   
   import org.apache.commons.httpclient.Credentials;
   import org.apache.commons.httpclient.Header;
  +import org.apache.commons.httpclient.HttpStatus;
   import org.apache.commons.httpclient.UsernamePasswordCredentials;
   import org.apache.commons.httpclient.auth.BasicScheme;
   
  @@ -50,11 +49,6 @@
       private Credentials credentials;
   
       /**
  -     * The proxy authenticate challange header.
  -     */
  -    public static final String PROXY_AUTH = "Proxy-Authenticate";
  -
  -    /**
        * The proxy authenticate response header.
        */
       public static final String PROXY_AUTH_RESP = "Proxy-Authorization";
  @@ -77,41 +71,25 @@
       {
           Header clientAuth = request.getFirstHeader(PROXY_AUTH_RESP);
           if (clientAuth != null) {
  -            boolean ok = checkAuthorization(clientAuth);
  -            if (ok)
  -                conn.connectionKeepAlive(true);
  -            return !ok;
  +            return !checkAuthorization(clientAuth);
           } else {
  -            performHandshake(conn);
  +            SimpleResponse response = performBasicHandshake(request);
  +            // Make sure the request body is fully consumed
  +            request.getBodyBytes();
  +            conn.writeResponse(response);
  +            return true;
           }
  -        return true;
       }
   
  -    /**
  -     * @param conn
  -     */
  -    private void performHandshake(SimpleHttpServerConnection conn) throws IOException {
  -        Header challenge = createChallenge();
  -        ResponseWriter out = conn.getWriter();
  -        out.println("HTTP/1.1 407 Proxy Authentication Required");
  -        out.print(challenge.toExternalForm());
  -        out.print(new Header("Proxy-Connection", "Keep-Alive").toExternalForm());
  -        out.print(new Header("Content-Length", "0").toExternalForm());
  -        out.println();
  -        out.flush();
  -        conn.connectionKeepAlive(true);
  -    }
  -
  -    /**
  -     * @return
  -     */
  -    private Header createChallenge() {
  -        Header header = new Header();
  -        header.setName(PROXY_AUTH);
  -        //TODO add more auth schemes
  -        String challenge = "basic realm=test";
  -        header.setValue(challenge);
  -        return header;
  +    //TODO add more auth schemes
  +    private SimpleResponse performBasicHandshake(final SimpleRequest request) { 
  +        SimpleResponse response = new SimpleResponse();
  +        response.setStatusLine(
  +                request.getRequestLine().getHttpVersion(),
  +                HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
  +        response.addHeader(new Header("Proxy-Authenticate", "basic realm=test"));
  +        //response.addHeader(new Header("Proxy-Connection", "Close"));
  +        return response;
       }
   
       /**
  
  
  
  1.9       +81 -86    jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/ProxyRequestHandler.java
  
  Index: ProxyRequestHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/ProxyRequestHandler.java,v
  retrieving revision 1.8
  retrieving revision 1.9
  diff -u -r1.8 -r1.9
  --- ProxyRequestHandler.java	7 Nov 2004 19:57:08 -0000	1.8
  +++ ProxyRequestHandler.java	13 Nov 2004 12:21:28 -0000	1.9
  @@ -30,35 +30,31 @@
   package org.apache.commons.httpclient.server;
   
   import java.io.IOException;
  -import java.io.InputStream;
   
   import org.apache.commons.httpclient.Header;
  -import org.apache.commons.httpclient.HttpClient;
  -import org.apache.commons.httpclient.HttpMethod;
  +import org.apache.commons.httpclient.HttpException;
  +import org.apache.commons.httpclient.HttpStatus;
   import org.apache.commons.httpclient.HttpVersion;
  -import org.apache.commons.httpclient.StatusLine;
   import org.apache.commons.httpclient.URI;
  -import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
  -import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
  -import org.apache.commons.httpclient.methods.GetMethod;
  -import org.apache.commons.httpclient.methods.HeadMethod;
  -import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
  -import org.apache.commons.httpclient.methods.PostMethod;
  -import org.apache.commons.httpclient.methods.PutMethod;
  -import org.apache.commons.httpclient.methods.RequestEntity;
  +import org.apache.commons.logging.Log;
  +import org.apache.commons.logging.LogFactory;
   
   /**
  - * This request handler can handle GET, POST, PUT, and HEAD requests. It does
  - * nothing for all other request
    * @author Ortwin Glueck
  + * @author Oleg Kalnichevski
    */
   public class ProxyRequestHandler implements HttpRequestHandler {
   
  -    private HttpClient client = null;
  +    private static final Log LOG = LogFactory.getLog(ProxyRequestHandler.class);
   
  -    public ProxyRequestHandler() {
  +    private SimpleConnManager connmanager = null;
  +    
  +    public ProxyRequestHandler(final SimpleConnManager connmanager) {
           super();
  -        this.client = new HttpClient();
  +        if (connmanager == null) {
  +            throw new IllegalArgumentException("Connection manager may not be null");
  +        }
  +        this.connmanager = connmanager;
       }
       
   	/**
  @@ -68,86 +64,85 @@
           final SimpleHttpServerConnection conn,
           final SimpleRequest request) throws IOException
       {
  -		RequestLine line = request.getRequestLine();
  -        URI url = new URI(request.getRequestLine().getUri(), false);
  -		String methodName = line.getMethod();
  -        HttpMethod method = null;
  -        if ("GET".equalsIgnoreCase(methodName)) {
  -            method = new GetMethod(url.getEscapedURI());
  -        } else if ("POST".equalsIgnoreCase(methodName)) {
  -            method = new PostMethod(url.getEscapedURI());
  -        } else if ("PUT".equalsIgnoreCase(methodName)) {
  -            method = new PutMethod(url.getEscapedURI());
  -        } else if ("HEAD".equalsIgnoreCase(methodName)) {
  -            method = new HeadMethod(url.getEscapedURI());
  -        } else {
  -            return false;
  -        }        
  -        httpProxy(conn, request, method);
  +        httpProxy(conn, request);
           return true;
   	}
   
  -	/**
  -	 * @param conn
  -	 */
   	private void httpProxy(
           final SimpleHttpServerConnection conn,
  -        final SimpleRequest request,
  -        final HttpMethod method) throws IOException
  -    {
  -        method.setFollowRedirects(false);
  -		Header[] headers = request.getHeaders();
  -		for (int i = 0; i < headers.length; i++) {
  -			method.addRequestHeader(headers[i]);
  -		}
  -		if (method instanceof EntityEnclosingMethod) {
  -			EntityEnclosingMethod emethod = (EntityEnclosingMethod) method;
  -			emethod.setRequestEntity(new ByteArrayRequestEntity(request.getBody()));
  -		}
  +        final SimpleRequest request) throws IOException {
  +
  +        RequestLine oldreqline = request.getRequestLine(); 
  +        URI uri = new URI(oldreqline.getUri(), true);
  +        SimpleHost host = new SimpleHost(uri.getHost(), uri.getPort());
  +        SimpleHttpServerConnection proxyconn = this.connmanager.openConnection(host);
           try {
  -            client.executeMethod(method);
  +
               
  -            StatusLine statusline = method.getStatusLine(); 
  -            SimpleResponse response = new SimpleResponse();
  -            response.setStatusLine(
  -                    HttpVersion.parse(statusline.getHttpVersion()),
  -                    statusline.getStatusCode(),
  -                    statusline.getReasonPhrase());
  -            response.setHeaders(method.getResponseHeaders());
  +            // Rewrite target url
  +            RequestLine newreqline = new RequestLine(
  +                    oldreqline.getMethod(), 
  +                    uri.getEscapedPath(), 
  +                    oldreqline.getHttpVersion()); 
  +            request.setRequestLine(newreqline);
  +            // Remove proxy-auth headers if present
  +            request.removeHeaders("Proxy-Authorization");
  +            // Manage connection persistence
  +            Header connheader = request.getFirstHeader("Proxy-Connection");
  +            if (connheader != null) {
  +                if (connheader.getValue().equalsIgnoreCase("close")) {
  +                    request.setHeader(new Header("Connection", "close"));
  +                }
  +            }
  +            request.removeHeaders("Proxy-Connection");
               
  -            long len = InputStreamRequestEntity.CONTENT_LENGTH_AUTO;
  -            Header header = response.getFirstHeader("Transfer-Encoding");
  -            if (header != null) {
  -                len = -1; // Use chunked encoding
  +            proxyconn.writeRequest(request);
  +            
  +            SimpleResponse response = proxyconn.readResponse();
  +            if (response == null) {
  +                return;
  +            }
  +            connheader = response.getFirstHeader("Connection");
  +            if (connheader != null) {
  +                String s = connheader.getValue(); 
  +                if (s.equalsIgnoreCase("close")) {
  +                    response.setHeader(new Header("Proxy-Connection", "close"));
  +                    conn.connectionKeepAlive(false);
  +                    proxyconn.connectionKeepAlive(false);
  +                    response.removeHeaders("Connection");
  +                }
  +                if (s.equalsIgnoreCase("keep-alive")) {
  +                    response.setHeader(new Header("Proxy-Connection", "keep-alive"));
  +                    conn.connectionKeepAlive(true);
  +                    proxyconn.connectionKeepAlive(true);
  +                    response.removeHeaders("Connection");
  +                }
               } else {
  -                header = response.getFirstHeader("Content-Length");
  -                try {
  -                    len = Long.parseLong(header.getValue());
  -                } catch (NumberFormatException e) {
  +                // Use protocol default connection policy
  +                if (response.getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
  +                    conn.connectionKeepAlive(true);
  +                    proxyconn.connectionKeepAlive(true);
  +                } else {
  +                    conn.connectionKeepAlive(false);
  +                    proxyconn.connectionKeepAlive(false);
                   }
               }
  -            String contentype = null;
  -            header = method.getResponseHeader("Content-Type");
  -            if (header != null) {
  -                contentype = header.getValue();
  -            }
  -            
  -            InputStream instream = method.getResponseBodyAsStream();
  -            if (instream != null) {
  -                RequestEntity content = new InputStreamRequestEntity(
  -                        instream, len, contentype);
  -                response.setBodyEntity(content);
  +            if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
  +                // this is a head request, we don't want to send the actualy content
  +                response.setBody(null);
               }
  -            
  -            Header connheader = new Header("Proxy-Connection", "close"); 
  -            response.setHeader(connheader);
  -            conn.connectionKeepAlive(false);
  -            
               conn.writeResponse(response);
  -            
  +
  +        } catch (HttpException e) {
  +            SimpleResponse response = ErrorResponse.getResponse(HttpStatus.SC_BAD_REQUEST);
  +            conn.writeResponse(response);
  +            proxyconn.connectionKeepAlive(false);
  +        } catch (IOException e) {
  +            LOG.warn(e.getMessage());
  +            proxyconn.connectionKeepAlive(false);
           } finally {
  -            method.releaseConnection();
  +            this.connmanager.releaseConnection(host, proxyconn);
           }
   	}
  -
  +    
   }
  
  
  
  1.2       +7 -5      jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnectionThread.java
  
  Index: SimpleConnectionThread.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnectionThread.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- SimpleConnectionThread.java	7 Nov 2004 19:57:08 -0000	1.1
  +++ SimpleConnectionThread.java	13 Nov 2004 12:21:28 -0000	1.2
  @@ -30,6 +30,7 @@
   package org.apache.commons.httpclient.server;
   
   import java.io.IOException;
  +import java.io.InterruptedIOException;
   
   import org.apache.commons.logging.Log;
   import org.apache.commons.logging.LogFactory;
  @@ -48,7 +49,7 @@
       public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";
   
       private SimpleHttpServerConnection conn = null;
  -    private SimpleConnPool connpool = null;    
  +    private SimpleConnSet connpool = null;    
       private HttpRequestHandler handler = null;
       transient boolean stopped; 
   
  @@ -56,7 +57,7 @@
               final ThreadGroup tg,
               final String name,
               final SimpleHttpServerConnection conn,
  -            final SimpleConnPool connpool,
  +            final SimpleConnSet connpool,
               final HttpRequestHandler handler) 
       throws IOException {
           super(tg, name);
  @@ -96,6 +97,7 @@
                       this.handler.processRequest(this.conn, request);
                   }
               } while (this.conn.isKeepAlive());
  +        } catch (InterruptedIOException e) {
           } catch (IOException e) {
               if (!this.stopped && !isInterrupted() && LOG.isWarnEnabled()) {
                   LOG.warn("[" + getName() + "] I/O error: " + e.getMessage());
  
  
  
  1.14      +4 -4      jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleHttpServer.java
  
  Index: SimpleHttpServer.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleHttpServer.java,v
  retrieving revision 1.13
  retrieving revision 1.14
  diff -u -r1.13 -r1.14
  --- SimpleHttpServer.java	7 Nov 2004 19:57:08 -0000	1.13
  +++ SimpleHttpServer.java	13 Nov 2004 12:21:28 -0000	1.14
  @@ -53,7 +53,7 @@
       private ThreadGroup tg;
       private boolean stopped = false;
   
  -    private SimpleConnPool connections = new SimpleConnPool();
  +    private SimpleConnSet connections = new SimpleConnSet();
   
       private HttpRequestHandler requestHandler = null;
   
  
  
  
  1.19      +89 -67    jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleHttpServerConnection.java
  
  Index: SimpleHttpServerConnection.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleHttpServerConnection.java,v
  retrieving revision 1.18
  retrieving revision 1.19
  diff -u -r1.18 -r1.19
  --- SimpleHttpServerConnection.java	7 Nov 2004 19:57:08 -0000	1.18
  +++ SimpleHttpServerConnection.java	13 Nov 2004 12:21:28 -0000	1.19
  @@ -29,7 +29,6 @@
   
   package org.apache.commons.httpclient.server;
   
  -import java.io.ByteArrayOutputStream;
   import java.io.IOException;
   import java.io.InputStream;
   import java.io.OutputStream;
  @@ -37,13 +36,10 @@
   import java.net.Socket;
   import java.util.Iterator;
   
  -import org.apache.commons.httpclient.ChunkedInputStream;
   import org.apache.commons.httpclient.ChunkedOutputStream;
  -import org.apache.commons.httpclient.ContentLengthInputStream;
   import org.apache.commons.httpclient.Header;
  -import org.apache.commons.httpclient.HeaderGroup;
   import org.apache.commons.httpclient.HttpParser;
  -import org.apache.commons.httpclient.methods.RequestEntity;
  +import org.apache.commons.httpclient.StatusLine;
   import org.apache.commons.logging.Log;
   import org.apache.commons.logging.LogFactory;
   
  @@ -58,7 +54,6 @@
       private static final Log LOG = LogFactory.getLog(SimpleHttpServerConnection.class);
       
       private static final String HTTP_ELEMENT_CHARSET = "US-ASCII";
  -    public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";
   
       private Socket socket = null;
       private InputStream in = null;
  @@ -89,6 +84,10 @@
           }
       }
   
  +    public synchronized boolean isOpen() {
  +        return this.socket != null;
  +    }
  +    
       public void connectionKeepAlive(boolean b) {
           this.keepAlive = b;
       }
  @@ -97,6 +96,14 @@
           return this.keepAlive;
       }
   
  +    public InputStream getInputStream() {
  +        return this.in;
  +    }
  +
  +    public OutputStream getOutputStream() {
  +        return this.out;
  +    }
  +
       /**
        * Returns the ResponseWriter used to write the output to the socket.
        * 
  @@ -117,22 +124,46 @@
                   connectionKeepAlive(false);
                   return null;
               }
  -            RequestLine statusLine = RequestLine.parseLine(line);
  -            Header[] headers = HttpParser.parseHeaders(in, HTTP_ELEMENT_CHARSET);
  -            return new SimpleRequest(statusLine, headers, getBody(statusLine, headers, in));
  +            SimpleRequest request = new SimpleRequest( 
  +                    RequestLine.parseLine(line),
  +                    HttpParser.parseHeaders(this.in, HTTP_ELEMENT_CHARSET),
  +                    this.in);
  +            return request;
           } catch (IOException e) {
               close();
               throw e;
           }
       }
   
  -    public void writeResponse(final SimpleResponse response) throws IOException {
  -        if (response == null) {
  +    public SimpleResponse readResponse() throws IOException {
  +        try {
  +            String line = null;
  +            do {
  +                line = HttpParser.readLine(in, HTTP_ELEMENT_CHARSET);
  +            } while (line != null && line.length() == 0);
  +
  +            if (line == null) {
  +                connectionKeepAlive(false);
  +                return null;
  +            }
  +            SimpleResponse response = new SimpleResponse(
  +                    new StatusLine(line),
  +                    HttpParser.parseHeaders(this.in, HTTP_ELEMENT_CHARSET),
  +                    this.in);
  +            return response;
  +        } catch (IOException e) {
  +            close();
  +            throw e;
  +        }
  +    }
  +
  +    public void writeRequest(final SimpleRequest request) throws IOException {
  +        if (request == null) {
               return;
           }
  -        ResponseWriter writer = new ResponseWriter(this.out, "US-ASCII");
  -        writer.println(response.getStatusLine());
  -        Iterator item = response.getHeaderIterator();
  +        ResponseWriter writer = new ResponseWriter(this.out, HTTP_ELEMENT_CHARSET);
  +        writer.println(request.getRequestLine().toString());
  +        Iterator item = request.getHeaderIterator();
           while (item.hasNext()) {
               Header header = (Header) item.next();
               writer.print(header.toExternalForm());
  @@ -141,17 +172,21 @@
           writer.flush();
           
           OutputStream outsream = this.out;
  -        RequestEntity entity = response.getEntity(); 
  -        if (entity != null) {
  +        InputStream content = request.getBody(); 
  +        if (content != null) {
   
  -            Header transferenc = response.getFirstHeader("Transfer-Encoding");
  +            Header transferenc = request.getFirstHeader("Transfer-Encoding");
               if (transferenc != null) {
  +                request.removeHeaders("Content-Length");
                   if (transferenc.getValue().indexOf("chunked") != -1) {
                       outsream = new ChunkedOutputStream(outsream);
                   }
               }
  -                        
  -            entity.writeRequest(outsream); 
  +            byte[] tmp = new byte[4096];
  +            int i = 0;
  +            while ((i = content.read(tmp)) >= 0) {
  +                outsream.write(tmp, 0, i);
  +            }        
               if (outsream instanceof ChunkedOutputStream) {
                   ((ChunkedOutputStream)outsream).finish();
               }
  @@ -159,55 +194,42 @@
           outsream.flush();
       }
       
  -    /**
  -     * Reads the request body into a byte[].
  -     * @param statusLine The request status line.
  -     * @param headers The request headers.
  -     * @param is The request input stream.
  -     * @return The content as an arra of bytes.
  -     * @throws IOException
  -     */
  -    private byte[] getBody(RequestLine statusLine, Header[] headers, InputStream is) throws IOException {
  -
  -        // only PUT and POST have content
  -        if (
  -            !statusLine.getMethod().equalsIgnoreCase("POST")
  -            && !statusLine.getMethod().equalsIgnoreCase("PUT")
  -            ) {
  -            return new byte[0];
  -        }
  -        
  -        HeaderGroup headerGroup = new HeaderGroup();
  -        headerGroup.setHeaders(headers);
  -        Header contentLength = headerGroup.getFirstHeader("Content-Length");
  -        InputStream contentStream = is;
  -        int length = -1;
  -        if (contentLength != null) {
  -            length = Integer.parseInt(contentLength.getValue().trim());
  -            contentStream = new ContentLengthInputStream(is, (long) length);
  -        } else {
  -            Header transferEncoding = headerGroup.getFirstHeader("Transfer-Encoding");
  -            if (transferEncoding != null && transferEncoding.getValue().indexOf("chunked") != -1) {
  -                contentStream = new ChunkedInputStream(is);
  -            }
  +    public void writeResponse(final SimpleResponse response) throws IOException {
  +        if (response == null) {
  +            return;
           }
  -        
  -        byte[] buff = new byte[4096];
  -        int bytesRead = 0;
  -        ByteArrayOutputStream os = new ByteArrayOutputStream(Math.max(length, 4096));
  -        while ((bytesRead = contentStream.read(buff)) != -1) {
  -            os.write(buff, 0, bytesRead);
  +        ResponseWriter writer = new ResponseWriter(this.out, HTTP_ELEMENT_CHARSET);
  +        writer.println(response.getStatusLine());
  +        Iterator item = response.getHeaderIterator();
  +        while (item.hasNext()) {
  +            Header header = (Header) item.next();
  +            writer.print(header.toExternalForm());
           }
  +        writer.println();
  +        writer.flush();
           
  -        return os.toByteArray();
  -    }
  -
  -    public InputStream getInputStream() {
  -        return in;
  -    }
  +        OutputStream outsream = this.out;
  +        InputStream content = response.getBody(); 
  +        if (content != null) {
   
  -    public OutputStream getOutputStream() {
  -        return out;
  +            Header transferenc = response.getFirstHeader("Transfer-Encoding");
  +            if (transferenc != null) {
  +                response.removeHeaders("Content-Length");
  +                if (transferenc.getValue().indexOf("chunked") != -1) {
  +                    outsream = new ChunkedOutputStream(outsream);
  +                }
  +            }
  +                        
  +            byte[] tmp = new byte[1024];
  +            int i = 0;
  +            while ((i = content.read(tmp)) >= 0) {
  +                outsream.write(tmp, 0, i);
  +            }        
  +            if (outsream instanceof ChunkedOutputStream) {
  +                ((ChunkedOutputStream)outsream).finish();
  +            }
  +        }
  +        outsream.flush();
       }
   
   }
  
  
  
  1.6       +7 -4      jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleProxy.java
  
  Index: SimpleProxy.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleProxy.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- SimpleProxy.java	7 Nov 2004 12:31:42 -0000	1.5
  +++ SimpleProxy.java	13 Nov 2004 12:21:28 -0000	1.6
  @@ -43,6 +43,7 @@
    */
   public class SimpleProxy extends SimpleHttpServer {
       
  +    private SimpleConnManager connmanager = null; 
       private HttpRequestHandlerChain chain = null;
   
       /**
  @@ -50,9 +51,10 @@
        */
       public SimpleProxy() throws IOException {
           super();
  +        this.connmanager = new SimpleConnManager(); 
           this.chain = new HttpRequestHandlerChain();
           this.chain.appendHandler(new TransparentProxyRequestHandler());
  -        this.chain.appendHandler(new ProxyRequestHandler());
  +        this.chain.appendHandler(new ProxyRequestHandler(this.connmanager));
           setRequestHandler(this.chain);
       }
   
  @@ -70,6 +72,7 @@
       }
   
       public void destroy() {
  +        this.connmanager.shutdown();
           super.destroy();
       }
       
  
  
  
  1.3       +132 -37   jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleRequest.java
  
  Index: SimpleRequest.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleRequest.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- SimpleRequest.java	6 Oct 2004 03:39:59 -0000	1.2
  +++ SimpleRequest.java	13 Nov 2004 12:21:28 -0000	1.3
  @@ -25,15 +25,17 @@
    * 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.server;
   
  +import java.io.ByteArrayOutputStream;
   import java.io.IOException;
  +import java.io.InputStream;
   import java.util.Iterator;
   
  +import org.apache.commons.httpclient.ChunkedInputStream;
  +import org.apache.commons.httpclient.ContentLengthInputStream;
   import org.apache.commons.httpclient.Header;
   import org.apache.commons.httpclient.HeaderElement;
   import org.apache.commons.httpclient.HeaderGroup;
  @@ -46,11 +48,11 @@
    */
   public class SimpleRequest {
       
  +    public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";
  +    
       private RequestLine requestLine = null;
  -    private String contentType = "text/plain";
  -    private String charSet = null;
  -    private byte[] body = null;
       private HeaderGroup headers = new HeaderGroup();
  +    private InputStream entity = null;
   
       public SimpleRequest() {
           super();
  @@ -59,55 +61,54 @@
       public SimpleRequest(
           final RequestLine requestLine,
           final Header[] headers,
  -        final byte[] body)
  +        final InputStream content) throws IOException
       {
           super();
           if (requestLine == null) {
               throw new IllegalArgumentException("Request line may not be null");
           }
           this.requestLine = requestLine;
  -        this.body = body;
           if (headers != null) {
               this.headers.setHeaders(headers);
  -            Header content = this.headers.getFirstHeader("Content-Type");
  -            if (content != null) {
  -                HeaderElement values[] = content.getElements();
  -                if (values.length == 1) {
  -                    this.contentType = values[0].getName();
  -                    NameValuePair param = values[0].getParameterByName("charset");
  -                    if (param != null) {
  -                        this.charSet = param.getValue();
  +        }
  +        if (content != null) {
  +            // only PUT and POST have content
  +            String methodname = requestLine.getMethod(); 
  +            if ("POST".equalsIgnoreCase(methodname) || "PUT".equalsIgnoreCase(methodname)) {
  +                Header contentLength = this.headers.getFirstHeader("Content-Length");
  +                Header transferEncoding = this.headers.getFirstHeader("Transfer-Encoding");
  +                InputStream in = content;
  +                if (transferEncoding != null) {
  +                    if (transferEncoding.getValue().indexOf("chunked") != -1) {
  +                        in = new ChunkedInputStream(in);
  +                    }
  +                } else if (contentLength != null) {
  +                    long len = getContentLength();
  +                    if (len >= 0) {
  +                        in = new ContentLengthInputStream(in, len);
                       }
                   }
  +                this.entity = in;
               }
           }
       }
   
  -    public String getContentType() {
  -        return this.contentType;
  +    public SimpleRequest(final RequestLine requestLine, final Header[] headers)
  +        throws IOException {
  +        this(requestLine, headers, null);
       }
       
  -    public String getCharSet() {
  -        return this.charSet;
  -    }
  -    
  -    public byte[] getBody() {
  -        return body;
  -    }
  -    
  -    public String getBodyString() throws IOException {
  -        return new String(
  -            body, 
  -            charSet == null 
  -            ? SimpleHttpServerConnection.DEFAULT_CONTENT_CHARSET 
  -            : charSet
  -            );
  -    }
  -
       public RequestLine getRequestLine() {
           return this.requestLine;
       }
   
  +    public void setRequestLine(final RequestLine requestline) {
  +        if (requestline == null) {
  +            throw new IllegalArgumentException("Request line may not be null");
  +        }
  +        this.requestLine = requestline;
  +    }
  +
       public boolean containsHeader(final String name) {
           return this.headers.containsHeader(name);
       }
  @@ -120,7 +121,101 @@
           return this.headers.getFirstHeader(s);
       }
   
  +    public void removeHeaders(final String s) {
  +        if (s == null) {
  +            return;
  +        }
  +        Header[] headers = this.headers.getHeaders(s);
  +        for (int i = 0; i < headers.length; i++) {
  +            this.headers.removeHeader(headers[i]);
  +        }
  +    }
  +
  +    public void addHeader(final Header header) {
  +        if (header == null) {
  +            return;
  +        }
  +        this.headers.addHeader(header);
  +    }
  +
  +    public void setHeader(final Header header) {
  +        if (header == null) {
  +            return;
  +        }
  +        removeHeaders(header.getName());
  +        addHeader(header);
  +    }
  +
       public Iterator getHeaderIterator() {
           return this.headers.getIterator();
  +    }
  +
  +    public String getContentType() {
  +        Header contenttype = this.headers.getFirstHeader("Content-Type");
  +        if (contenttype != null) {
  +            return contenttype.getValue(); 
  +        } else {
  +            return "text/plain"; 
  +        }
  +    }
  +    
  +    public String getCharset() {
  +        String charset = null;
  +        Header contenttype = this.headers.getFirstHeader("Content-Type");
  +        if (contenttype != null) {
  +            HeaderElement values[] = contenttype.getElements();
  +            if (values.length == 1) {
  +                NameValuePair param = values[0].getParameterByName("charset");
  +                if (param != null) {
  +                    charset = param.getValue();
  +                }
  +            }
  +        }
  +        if (charset != null) {
  +            return charset;
  +        } else {
  +            return DEFAULT_CONTENT_CHARSET;
  +        }
  +    }
  +    
  +    public long getContentLength() {
  +        Header contentLength = this.headers.getFirstHeader("Content-Length");
  +        if (contentLength != null) {
  +            try {
  +                return Long.parseLong(contentLength.getValue());
  +            } catch (NumberFormatException e) {
  +                return -1;
  +            }
  +        } else {
  +            return -1;
  +        }
  +    }
  +    
  +    public InputStream getBody() {
  +        return this.entity;
  +    }
  +    
  +    public byte[] getBodyBytes() throws IOException {
  +        InputStream in = getBody();
  +        if (in != null) {
  +            byte[] tmp = new byte[4096];
  +            int bytesRead = 0;
  +            ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
  +            while ((bytesRead = in.read(tmp)) != -1) {
  +                buffer.write(tmp, 0, bytesRead);
  +            }
  +            return buffer.toByteArray();
  +        } else {
  +            return null;
  +        }
  +    }
  +    
  +    public String getBodyString() throws IOException {
  +        byte[] raw = getBodyBytes();
  +        if (raw != null) {
  +            return new String(raw, getCharset());
  +        } else {
  +            return null;
  +        }
       }
   }
  
  
  
  1.8       +115 -26   jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleResponse.java
  
  Index: SimpleResponse.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleResponse.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- SimpleResponse.java	7 Nov 2004 12:31:42 -0000	1.7
  +++ SimpleResponse.java	13 Nov 2004 12:21:28 -0000	1.8
  @@ -29,17 +29,22 @@
   
   package org.apache.commons.httpclient.server;
   
  +import java.io.ByteArrayInputStream;
  +import java.io.ByteArrayOutputStream;
  +import java.io.IOException;
  +import java.io.InputStream;
   import java.io.UnsupportedEncodingException;
   import java.util.Iterator;
   
  +import org.apache.commons.httpclient.ChunkedInputStream;
  +import org.apache.commons.httpclient.ContentLengthInputStream;
   import org.apache.commons.httpclient.Header;
   import org.apache.commons.httpclient.HeaderElement;
   import org.apache.commons.httpclient.HeaderGroup;
   import org.apache.commons.httpclient.HttpStatus;
   import org.apache.commons.httpclient.HttpVersion;
   import org.apache.commons.httpclient.NameValuePair;
  -import org.apache.commons.httpclient.methods.RequestEntity;
  -import org.apache.commons.httpclient.methods.StringRequestEntity;
  +import org.apache.commons.httpclient.StatusLine;
   
   /**
    * A generic HTTP response.
  @@ -49,16 +54,50 @@
    */
   public class SimpleResponse {
       
  +    public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";
  +    
       private HttpVersion ver = HttpVersion.HTTP_1_1;
       private int statuscode = HttpStatus.SC_OK;
       private String phrase = HttpStatus.getStatusText(HttpStatus.SC_OK);
       private HeaderGroup headers = new HeaderGroup();
  -    private RequestEntity entity = null;
  +    private InputStream entity = null;
   
       public SimpleResponse() {
           super();
       }
   
  +    public SimpleResponse(
  +            final StatusLine statusline, 
  +            final Header[] headers, 
  +            final InputStream content) 
  +            throws IOException {
  +        super();
  +        if (statusline == null) {
  +            throw new IllegalArgumentException("Status line may not be null");
  +        }
  +        setStatusLine(HttpVersion.parse(statusline.getHttpVersion()),
  +                statusline.getStatusCode(), statusline.getReasonPhrase());
  +        setHeaders(headers);
  +        if (content != null) {
  +            InputStream in = content;
  +            Header contentLength = this.headers.getFirstHeader("Content-Length");
  +            Header transferEncoding = this.headers.getFirstHeader("Transfer-Encoding");
  +
  +            if (transferEncoding != null) {
  +                if (transferEncoding.getValue().indexOf("chunked") != -1) {
  +                    in = new ChunkedInputStream(in);
  +                }
  +            } else if (contentLength != null) {
  +                long len = getContentLength();
  +                if (len >= 0) {
  +                    in = new ContentLengthInputStream(in, len);
  +                }
  +            }
  +            this.entity = in;
  +        }
  +    }
  +
  +
       public void setStatusLine(final HttpVersion ver, int statuscode, final String phrase) {
           if (ver == null) {
               throw new IllegalArgumentException("HTTP version may not be null");
  @@ -115,15 +154,14 @@
           return this.headers.getFirstHeader(name);
       }
   
  -    public void setHeader(final Header header) {
  -        if (header == null) {
  +    public void removeHeaders(final String s) {
  +        if (s == null) {
               return;
           }
  -        Header[] headers = this.headers.getHeaders(header.getName());
  +        Header[] headers = this.headers.getHeaders(s);
           for (int i = 0; i < headers.length; i++) {
               this.headers.removeHeader(headers[i]);
           }
  -        this.headers.addHeader(header);
       }
   
       public void addHeader(final Header header) {
  @@ -133,6 +171,14 @@
           this.headers.addHeader(header);
       }
   
  +    public void setHeader(final Header header) {
  +        if (header == null) {
  +            return;
  +        }
  +        removeHeaders(header.getName());
  +        addHeader(header);
  +    }
  +
       public void setHeaders(final Header[] headers) {
           if (headers == null) {
               return;
  @@ -145,13 +191,10 @@
       }
       
       public String getCharset() {
  -        String charset = "ISO-8859-1";
  -        Header content = this.headers.getFirstHeader("Content-Type");
  -        if (content == null && this.entity != null) {
  -            content = new Header("Content-Type", this.entity.getContentType());
  -        }
  -        if (content != null) {
  -            HeaderElement values[] = content.getElements();
  +        String charset = DEFAULT_CONTENT_CHARSET;
  +        Header contenttype = this.headers.getFirstHeader("Content-Type");
  +        if (contenttype != null) {
  +            HeaderElement values[] = contenttype.getElements();
               if (values.length == 1) {
                   NameValuePair param = values[0].getParameterByName("charset");
                   if (param != null) {
  @@ -162,20 +205,66 @@
           return charset;
       }
   
  -    public RequestEntity getEntity() {
  -        return this.entity;
  +    public long getContentLength() {
  +        Header contentLength = this.headers.getFirstHeader("Content-Length");
  +        if (contentLength != null) {
  +            try {
  +                return Long.parseLong(contentLength.getValue());
  +            } catch (NumberFormatException e) {
  +                return -1;
  +            }
  +        } else {
  +            return -1;
  +        }
       }
  -
  +    
       public void setBodyString(final String string) {
  -        try {
  -            this.entity = new StringRequestEntity(string, "text/plain", "ISO-8859-1");
  -        } catch (UnsupportedEncodingException e) {
  -            this.entity = new StringRequestEntity(string);
  +        if (string != null) {
  +            byte[] raw = null;
  +            try {
  +                raw = string.getBytes(DEFAULT_CONTENT_CHARSET);
  +            } catch (UnsupportedEncodingException e) {
  +                raw = string.getBytes();
  +            }
  +            this.entity = new ByteArrayInputStream(raw);
  +            if (!containsHeader("Content-Type")) {
  +                setHeader(new Header("Content-Type", "text/plain"));
  +            }
  +            setHeader(new Header("Content-Length", Long.toString(raw.length)));
  +        } else {
  +            this.entity = null;
           }
       }
       
  -    public void setBodyEntity(final RequestEntity entity) {
  -        this.entity = entity;
  +    public void setBody(final InputStream instream) {
  +        this.entity = instream;
       }
       
  +    public InputStream getBody() {
  +        return this.entity;
  +    }
  +    
  +    public byte[] getBodyBytes() throws IOException {
  +        InputStream in = getBody();
  +        if (in != null) {
  +            byte[] tmp = new byte[4096];
  +            int bytesRead = 0;
  +            ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
  +            while ((bytesRead = in.read(tmp)) != -1) {
  +                buffer.write(tmp, 0, bytesRead);
  +            }
  +            return buffer.toByteArray();
  +        } else {
  +            return null;
  +        }
  +    }
  +    
  +    public String getBodyString() throws IOException {
  +        byte[] raw = getBodyBytes();
  +        if (raw != null) {
  +            return new String(raw, getCharset());
  +        } else {
  +            return null;
  +        }
  +    }
   }
  
  
  
  1.1                  jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnList.java
  
  Index: SimpleConnList.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnList.java,v 1.1 2004/11/13 12:21:28 olegk Exp $
   * $Revision: 1.1 $
   * $Date: 2004/11/13 12:21:28 $
   *
   * ====================================================================
   *
   *  Copyright 1999-2004 The Apache Software Foundation
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   * ====================================================================
   *
   * 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/>.
   *
   */
  
  package org.apache.commons.httpclient.server;
  
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.util.List;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  
  /**
   * A simple list of connections.
   * 
   * @author Oleg Kalnichevski
   */
  public class SimpleConnList {
      
      private static final Log LOG = LogFactory.getLog(SimpleConnList.class);
      
      private List connections = new ArrayList();
      
      public SimpleConnList() {
          super();
      }
  
      public synchronized void addConnection(final SimpleHttpServerConnection conn) {
          this.connections.add(conn);
      }
      
      public synchronized void removeConnection(final SimpleHttpServerConnection conn) {
          this.connections.remove(conn);
      }
  
      public synchronized SimpleHttpServerConnection removeLast() {
          int s = this.connections.size(); 
          if (s > 0) {
              return (SimpleHttpServerConnection)this.connections.remove(s - 1);
          } else {
              return null;
          }
      }
  
      public synchronized SimpleHttpServerConnection removeFirst() {
          int s = this.connections.size(); 
          if (s > 0) {
              return (SimpleHttpServerConnection)this.connections.remove(0);
          } else {
              return null;
          }
      }
  
      public synchronized void shutdown() {
          for (Iterator i = this.connections.iterator(); i.hasNext();) {
              SimpleHttpServerConnection conn = (SimpleHttpServerConnection) i.next();
              conn.close();
          }
          this.connections.clear();
      }
  
  }
  
  
  
  1.1                  jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnManager.java
  
  Index: SimpleConnManager.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnManager.java,v 1.1 2004/11/13 12:21:28 olegk Exp $
   * $Revision: 1.1 $
   * $Date: 2004/11/13 12:21:28 $
   *
   * ====================================================================
   *
   *  Copyright 1999-2004 The Apache Software Foundation
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   * ====================================================================
   *
   * 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/>.
   *
   */
  
  package org.apache.commons.httpclient.server;
  
  import java.io.IOException;
  import java.net.Socket;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.Map;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  
  /**
   * A REALLY simple connection manager.
   * 
   * @author Oleg Kalnichevski
   */
  public class SimpleConnManager {
      
      private static final Log LOG = LogFactory.getLog(SimpleConnManager.class);
      
      private Map connsets = new HashMap();
      
      public SimpleConnManager() {
          super();
      }
  
      public synchronized SimpleHttpServerConnection openConnection(final SimpleHost host)
          throws IOException {
          if (host == null) {
              throw new IllegalArgumentException("Host may not be null");
          }
          SimpleHttpServerConnection conn = null;
          SimpleConnList connlist = (SimpleConnList)this.connsets.get(host);
          if (connlist != null) {
              conn = connlist.removeFirst();
              if (!conn.isOpen()) {
                  conn = null;
              }
          }
          if (conn == null) {
              Socket socket = new Socket(host.getHostName(), host.getPort());
              conn = new SimpleHttpServerConnection(socket);
          }
          return conn;
      }
      
      public synchronized void releaseConnection(final SimpleHost host, 
              final SimpleHttpServerConnection conn) throws IOException {
          if (host == null) {
              throw new IllegalArgumentException("Host may not be null");
          }
          if (conn == null) {
              return;
          }
          if (!conn.isKeepAlive()) {
              conn.close();
          }
          if (conn.isOpen()) {
              SimpleConnList connlist = (SimpleConnList)this.connsets.get(host);
              if (connlist == null) {
                  connlist = new SimpleConnList();
                  this.connsets.put(host, connlist);
              }
              connlist.addConnection(conn);
          }
      }
  
      public synchronized void shutdown() {
          for (Iterator i = this.connsets.values().iterator(); i.hasNext();) {
              SimpleConnList connlist = (SimpleConnList) i.next();
              connlist.shutdown();
          }
          this.connsets.clear();
      }
  
  }
  
  
  
  1.1                  jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnSet.java
  
  Index: SimpleConnSet.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnSet.java,v 1.1 2004/11/13 12:21:28 olegk Exp $
   * $Revision: 1.1 $
   * $Date: 2004/11/13 12:21:28 $
   *
   * ====================================================================
   *
   *  Copyright 1999-2004 The Apache Software Foundation
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   * ====================================================================
   *
   * 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/>.
   *
   */
  
  package org.apache.commons.httpclient.server;
  
  import java.util.HashSet;
  import java.util.Iterator;
  import java.util.Set;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  
  /**
   * A simple set of connections.
   * 
   * @author Oleg Kalnichevski
   */
  public class SimpleConnSet {
      
      private static final Log LOG = LogFactory.getLog(SimpleConnSet.class);
      
      private Set connections = new HashSet();
      
      public SimpleConnSet() {
          super();
      }
  
      public synchronized void addConnection(final SimpleHttpServerConnection conn) {
          this.connections.add(conn);
      }
      
      public synchronized void removeConnection(final SimpleHttpServerConnection conn) {
          this.connections.remove(conn);
      }
  
      public synchronized void shutdown() {
          for (Iterator i = connections.iterator(); i.hasNext();) {
              SimpleHttpServerConnection conn = (SimpleHttpServerConnection) i.next();
              conn.close();
          }
      }
  
  }
  
  
  
  1.1                  jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleHost.java
  
  Index: SimpleHost.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleHost.java,v 1.1 2004/11/13 12:21:28 olegk Exp $
   * $Revision: 1.1 $
   * $Date: 2004/11/13 12:21:28 $
   *
   * ====================================================================
   *
   *  Copyright 2002-2004 The Apache Software Foundation
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   * ====================================================================
   *
   * 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/>.
   *
   */
  
  package org.apache.commons.httpclient.server;
  
  /**
   * @author Oleg Kalnichevski
   */
  public class SimpleHost implements Cloneable {
  
      private String hostname = null;
  
      private int port = -1;
  
      public SimpleHost(final String hostname, int port) {
          super();
          if (hostname == null) {
              throw new IllegalArgumentException("Host name may not be null");
          }
          if (port < 0) {
              throw new IllegalArgumentException("Port may not be negative");
          }
          this.hostname = hostname;
          this.port = port;
      }
  
      public SimpleHost (final SimpleHost httphost) {
          super();
          this.hostname = httphost.hostname;
          this.port = httphost.port;
      }
  
      public Object clone() {
          return new SimpleHost(this);
      }    
      
      public String getHostName() {
          return this.hostname;
      }
  
      public int getPort() {
          return this.port;
      }
  
      public String toString() {
          StringBuffer buffer = new StringBuffer(50);        
          buffer.append(this.hostname);
          buffer.append(':');
          buffer.append(this.port);
          return buffer.toString();
      }    
      
      public boolean equals(final Object o) {
          
          if (o instanceof SimpleHost) {
              if (o == this) { 
                  return true;
              }
              SimpleHost that = (SimpleHost) o;
              if (!this.hostname.equalsIgnoreCase(that.hostname)) {
                  return false;
              }
              if (this.port != that.port) {
                  return false;
              }
              return true;
          } else {
              return false;
          }
      }
  
      public int hashCode() {
          return this.hostname.hashCode() + this.port;
      }
  
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message