Clover coverage report - Cactus 1.5 for J2EE API 1.3
Coverage timestamp: Wed Feb 18 2004 09:09:13 EST
file stats: LOC: 341   Methods: 6
NCLOC: 165   Classes: 1
 
 Source file Conditionals Statements Methods TOTAL
JdkConnectionHelper.java 0% 0% 0% 0%
coverage
 1   
 /*
 2   
  * ====================================================================
 3   
  *
 4   
  * The Apache Software License, Version 1.1
 5   
  *
 6   
  * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
 7   
  * reserved.
 8   
  *
 9   
  * Redistribution and use in source and binary forms, with or without
 10   
  * modification, are permitted provided that the following conditions
 11   
  * are met:
 12   
  *
 13   
  * 1. Redistributions of source code must retain the above copyright
 14   
  *    notice, this list of conditions and the following disclaimer.
 15   
  *
 16   
  * 2. Redistributions in binary form must reproduce the above copyright
 17   
  *    notice, this list of conditions and the following disclaimer in
 18   
  *    the documentation and/or other materials provided with the
 19   
  *    distribution.
 20   
  *
 21   
  * 3. The end-user documentation included with the redistribution, if
 22   
  *    any, must include the following acknowlegement:
 23   
  *       "This product includes software developed by the
 24   
  *        Apache Software Foundation (http://www.apache.org/)."
 25   
  *    Alternately, this acknowlegement may appear in the software itself,
 26   
  *    if and wherever such third-party acknowlegements normally appear.
 27   
  *
 28   
  * 4. The names "The Jakarta Project", "Cactus" and "Apache Software
 29   
  *    Foundation" must not be used to endorse or promote products
 30   
  *    derived from this software without prior written permission. For
 31   
  *    written permission, please contact apache@apache.org.
 32   
  *
 33   
  * 5. Products derived from this software may not be called "Apache"
 34   
  *    nor may "Apache" appear in their names without prior written
 35   
  *    permission of the Apache Group.
 36   
  *
 37   
  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 38   
  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 39   
  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 40   
  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 41   
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 42   
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 43   
  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 44   
  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 45   
  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 46   
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 47   
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 48   
  * SUCH DAMAGE.
 49   
  * ====================================================================
 50   
  *
 51   
  * This software consists of voluntary contributions made by many
 52   
  * individuals on behalf of the Apache Software Foundation.  For more
 53   
  * information on the Apache Software Foundation, please see
 54   
  * <http://www.apache.org/>.
 55   
  *
 56   
  */
 57   
 package org.apache.cactus.client.connector.http;
 58   
 
 59   
 import java.io.IOException;
 60   
 import java.io.InputStream;
 61   
 import java.io.OutputStream;
 62   
 import java.io.PrintWriter;
 63   
 
 64   
 import java.net.HttpURLConnection;
 65   
 import java.net.URL;
 66   
 import java.net.URLConnection;
 67   
 import java.net.URLEncoder;
 68   
 
 69   
 import java.util.Enumeration;
 70   
 
 71   
 import org.apache.cactus.WebRequest;
 72   
 import org.apache.cactus.client.authentication.Authentication;
 73   
 import org.apache.cactus.configuration.Configuration;
 74   
 import org.apache.cactus.util.ChainedRuntimeException;
 75   
 import org.apache.cactus.util.CookieUtil;
 76   
 import org.apache.commons.logging.Log;
 77   
 import org.apache.commons.logging.LogFactory;
 78   
 
 79   
 /**
 80   
  * Implementation of <code>ConnectionHelper</code> using the JDK
 81   
  * <code>HttpURLConnection</code> class.
 82   
  *
 83   
  * @author <a href="mailto:vmassol@apache.org">Vincent Massol</a>
 84   
  * @author <a href="mailto:Jason.Robertson@acs-inc.com">Jason Robertson</a>
 85   
  *
 86   
  * @version $Id: JdkConnectionHelper.java,v 1.7 2003/06/22 16:18:47 vmassol Exp $
 87   
  */
 88   
 public class JdkConnectionHelper implements ConnectionHelper
 89   
 {
 90   
     /**
 91   
      * The logger
 92   
      */
 93   
     private static final Log LOGGER = 
 94   
         LogFactory.getLog(JdkConnectionHelper.class);
 95   
 
 96   
     // Static initialisations
 97   
     static
 98   
     {
 99   
         // Do not follow redirects (because we are doing unit tests and
 100   
         // we need to be able to assert the returned headers, cookies, ...)
 101  0
         HttpURLConnection.setFollowRedirects(false);
 102   
     }
 103   
 
 104   
     /**
 105   
      * The URL that will be used for the HTTP connection.
 106   
      */
 107   
     private String url;
 108   
 
 109   
     /**
 110   
      * @param theURL the URL that will be used for the HTTP connection.
 111   
      */
 112  0
     public JdkConnectionHelper(String theURL)
 113   
     {
 114  0
         this.url = theURL;
 115   
     }
 116   
 
 117   
     /**
 118   
      * @see ConnectionHelper#connect(WebRequest, Configuration)
 119   
      */
 120  0
     public HttpURLConnection connect(WebRequest theRequest,
 121   
         Configuration theConfiguration) throws Throwable
 122   
     {
 123  0
         URL url = new URL(this.url);
 124   
 
 125   
         // Add Authentication headers, if necessary. This is the first
 126   
         // step to allow authentication to add extra headers, HTTP parameters,
 127   
         // etc.
 128  0
         Authentication authentication = theRequest.getAuthentication();
 129   
 
 130  0
         if (authentication != null)
 131   
         {
 132  0
             authentication.configure(theRequest, theConfiguration);
 133   
         }
 134   
 
 135   
         // Add the parameters that need to be passed as part of the URL
 136  0
         url = HttpUtil.addHttpGetParameters(theRequest, url);
 137   
 
 138  0
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 139   
 
 140  0
         connection.setDoInput(true);
 141   
 
 142   
         // Choose the method that we will use to post data :
 143   
         // - If at least one parameter is to be sent in the request body, then
 144   
         //   we are doing a POST.
 145   
         // - If user data has been specified, then we are doing a POST
 146  0
         if (theRequest.getParameterNamesPost().hasMoreElements()
 147   
             || (theRequest.getUserData() != null))
 148   
         {
 149  0
             connection.setDoOutput(true);
 150   
         }
 151   
         else
 152   
         {
 153  0
             connection.setDoOutput(false);
 154   
         }
 155   
 
 156  0
         connection.setUseCaches(false);
 157   
 
 158   
         // Sets the content type
 159  0
         connection.setRequestProperty("Content-type", 
 160   
             theRequest.getContentType());
 161   
 
 162   
         // Add the other header fields
 163  0
         addHeaders(theRequest, connection);
 164   
 
 165   
         // Add the cookies
 166  0
         String cookieString = CookieUtil.getCookieString(theRequest, url);
 167  0
         if (cookieString != null)
 168   
         {
 169  0
             connection.setRequestProperty("Cookie", cookieString);
 170   
         }
 171   
 
 172   
         // Add the POST parameters if no user data has been specified (user data
 173   
         // overried post parameters)
 174  0
         if (theRequest.getUserData() != null)
 175   
         {
 176  0
             addUserData(theRequest, connection);
 177   
         }
 178   
         else
 179   
         {
 180  0
             addHttpPostParameters(theRequest, connection);
 181   
         }
 182   
 
 183   
         // Log content length
 184  0
         LOGGER.debug("ContentLength = [" + connection.getContentLength() + "]");
 185   
 
 186   
         // Open the connection and get the result
 187  0
         connection.connect();
 188   
 
 189  0
         return connection;
 190   
     }
 191   
 
 192   
     /**
 193   
      * Add user data in the request body.
 194   
      *
 195   
      * @param theRequest the request containing all data to pass to the server
 196   
      *        redirector.
 197   
      * @param theConnection the HTTP connection
 198   
      * @exception IOException if we fail to read the user data
 199   
      */
 200  0
     private void addUserData(WebRequest theRequest, URLConnection theConnection)
 201   
                       throws IOException
 202   
     {
 203   
         // If no user data, then exit
 204  0
         if (theRequest.getUserData() == null)
 205   
         {
 206  0
             return;
 207   
         }
 208   
 
 209  0
         OutputStream out = getConnectionStream(theConnection);
 210  0
         InputStream stream = theRequest.getUserData();
 211   
 
 212  0
         byte[] buffer = new byte[2048];
 213  0
         int length;
 214   
 
 215  0
         while ((length = stream.read(buffer)) != -1)
 216   
         {
 217  0
             out.write(buffer, 0, length);
 218   
         }
 219   
 
 220  0
         out.close();
 221   
     }
 222   
 
 223   
     /**
 224   
      * Add the HTTP parameters that need to be passed in the request body.
 225   
      *
 226   
      * @param theRequest the request containing all data to pass to the server
 227   
      *        redirector.
 228   
      * @param theConnection the HTTP connection
 229   
      */
 230  0
     private void addHttpPostParameters(WebRequest theRequest, 
 231   
                                    URLConnection theConnection)
 232   
     {
 233   
         // If no parameters, then exit
 234  0
         if (!theRequest.getParameterNamesPost().hasMoreElements())
 235   
         {
 236  0
             return;
 237   
         }
 238   
 
 239  0
         PrintWriter out = new PrintWriter(getConnectionStream(theConnection));
 240  0
         StringBuffer queryString = new StringBuffer();
 241  0
         Enumeration keys = theRequest.getParameterNamesPost();
 242   
 
 243  0
         if (keys.hasMoreElements())
 244   
         {
 245  0
             String key = (String) keys.nextElement();
 246  0
             String[] values = theRequest.getParameterValuesPost(key);
 247   
 
 248  0
             queryString.append(key);
 249  0
             queryString.append('=');
 250  0
             queryString.append(URLEncoder.encode(values[0]));
 251   
 
 252  0
             for (int i = 1; i < values.length; i++)
 253   
             {
 254  0
                 queryString.append('&');
 255  0
                 queryString.append(key);
 256  0
                 queryString.append('=');
 257  0
                 queryString.append(URLEncoder.encode(values[i]));
 258   
             }
 259   
         }
 260   
 
 261  0
         while (keys.hasMoreElements())
 262   
         {
 263  0
             String key = (String) keys.nextElement();
 264  0
             String[] values = theRequest.getParameterValuesPost(key);
 265   
 
 266  0
             for (int i = 0; i < values.length; i++)
 267   
             {
 268  0
                 queryString.append('&');
 269  0
                 queryString.append(key);
 270  0
                 queryString.append('=');
 271  0
                 queryString.append(URLEncoder.encode(values[i]));
 272   
             }
 273   
         }
 274   
 
 275  0
         out.print(queryString.toString());
 276  0
         out.close();
 277   
     }
 278   
 
 279   
     /**
 280   
      * @param theConnection the HTTP connection
 281   
      * @return an output stream to write in the request body
 282   
      */
 283  0
     private OutputStream getConnectionStream(URLConnection theConnection)
 284   
     {
 285  0
         OutputStream out;
 286   
 
 287  0
         try
 288   
         {
 289  0
             out = theConnection.getOutputStream();
 290   
         }
 291   
         catch (IOException e)
 292   
         {
 293   
             // Cannot connect to server, try to explain why ...
 294  0
             String reason = "Cannot connect to URL [" + theConnection.getURL()
 295   
                 + "]. Reason : [" + e.getMessage() + "]\r\n";
 296  0
             reason += "Possible reasons :\r\n";
 297  0
             reason += "\t- The server is not running,\r\n";
 298  0
             reason += ("\t- The server redirector is not correctly mapped in " 
 299   
                 + "web.xml,\r\n");
 300  0
             reason += "\t- Something else ... !";
 301   
 
 302  0
             throw new ChainedRuntimeException(reason);
 303   
         }
 304   
 
 305  0
         return out;
 306   
     }
 307   
 
 308   
     /**
 309   
      * Add the Headers to the request.
 310   
      *
 311   
      * @param theRequest the request containing all data to pass to the server
 312   
      *        redirector.
 313   
      * @param theConnection the HTTP connection
 314   
      */
 315  0
     private void addHeaders(WebRequest theRequest, URLConnection theConnection)
 316   
     {
 317  0
         Enumeration keys = theRequest.getHeaderNames();
 318   
 
 319  0
         while (keys.hasMoreElements())
 320   
         {
 321  0
             String key = (String) keys.nextElement();
 322  0
             String[] values = theRequest.getHeaderValues(key);
 323   
 
 324   
             // As the URLConnection.setRequestProperty will overwrite any
 325   
             // property already set we have to regroup the multi valued
 326   
             // headers into a single header name entry.
 327   
             // Question: Is this an implementation bug ? It seems because
 328   
             // on the server side, I cannot use the request.getHeaders() (it
 329   
             // only returns a single header).
 330  0
             StringBuffer fullHeaderValue = new StringBuffer(values[0]);
 331   
 
 332  0
             for (int i = 1; i < values.length; i++)
 333   
             {
 334  0
                 fullHeaderValue.append("," + values[i]);
 335   
             }
 336   
 
 337  0
             theConnection.setRequestProperty(key, fullHeaderValue.toString());
 338   
         }
 339   
     }
 340   
 }
 341