brett       2004/12/03 22:52:13

  Modified:    src/java/org/apache/maven/util Tag: MAVEN-1_0-BRANCH
                        HttpUtils.java
  Log:
  PR: MAVEN-1428, MAVEN-1502

  improved error handling for dependency downloader
  
  Revision  Changes    Path
  No                   revision
  No                   revision
  1.28.4.18 +306 -223  maven/src/java/org/apache/maven/util/HttpUtils.java
  
  Index: HttpUtils.java
  ===================================================================
  RCS file: /home/cvs/maven/src/java/org/apache/maven/util/HttpUtils.java,v
  retrieving revision 1.28.4.17
  retrieving revision 1.28.4.18
  diff -u -r1.28.4.17 -r1.28.4.18
  --- HttpUtils.java    4 Nov 2004 11:08:56 -0000       1.28.4.17
  +++ HttpUtils.java    4 Dec 2004 06:52:12 -0000       1.28.4.18
  @@ -53,18 +53,19 @@
    * @author [EMAIL PROTECTED]
    * @author [EMAIL PROTECTED] (Added Java 1.1 style HTTP basic auth)
    * @author <a href="mailto:[EMAIL PROTECTED]">Jason van Zyl</a>
  - *
    * @todo Need to add a timeout so we can flip to a backup repository.
    * @todo Download everything in a single session.
    * @todo Throw meaningful exception when authentication fails.
    */
   public class HttpUtils
   {
  -    private static final Log LOG = LogFactory.getLog(HttpUtils.class);
  +    private static final Log LOG = LogFactory.getLog( HttpUtils.class );
   
  -    private static final TimeZone GMT_TIME_ZONE = 
TimeZone.getTimeZone("GMT");
  +    private static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone( 
"GMT" );
   
  -    /** @todo make it a property. */
  +    /**
  +     * @todo make it a property.
  +     */
       private static final int REDIRECT_LIMIT = 5;
   
       private static final DownloadMeter silentDownloadMeter = new 
SilentDownloadMeter();
  @@ -74,14 +75,14 @@
       /**
        * Use a proxy to bypass the firewall with or without authentication
        *
  -     * @param proxyHost Proxy Host (if proxy is required), or null
  -     * @param proxyPort Proxy Port (if proxy is required), or null
  +     * @param proxyHost     Proxy Host (if proxy is required), or null
  +     * @param proxyPort     Proxy Port (if proxy is required), or null
        * @param proxyUserName Proxy Username (if authentification is required),
  -     *        or null
  +     *                      or null
        * @param proxyPassword Proxy Password (if authentification is required),
  -     *        or null
  +     *                      or null
        * @throws SecurityException if an operation is not authorized by the
  -     * SecurityManager
  +     *                           SecurityManager
        */
       public static void useProxyUser( final String proxyHost,
                                        final String proxyPort,
  @@ -109,23 +110,23 @@
       }
   
       /**
  -     * Retrieve a remote file.  Throws an Exception on errors unless the 
  +     * Retrieve a remote file.  Throws an Exception on errors unless the
        * ifnoreErrors flag is set to True
        *
  -     * @param url the of the file to retrieve
  +     * @param url             the of the file to retrieve
        * @param destinationFile where to store it
  -     * @param ignoreErrors whether to ignore errors during I/O or throw an
  -     *      exception when they happen
  -     * @param useTimestamp whether to check the modified timestamp on the
  -     *      <code>destinationFile</code> against the remote 
<code>source</code>
  -     * @param proxyHost Proxy Host (if proxy is required), or null
  -     * @param proxyPort Proxy Port (if proxy is required), or null
  -     * @param proxyUserName Proxy Username (if authentification is required),
  -     *        or null.
  -     * @param proxyPassword Proxy Password (if authentification is required),
  -     *        or null.
  -     * @param useChecksum Flag to indicate the use of the checksum for the 
retrieved
  -     *        artifact if it is available.
  +     * @param ignoreErrors    whether to ignore errors during I/O or throw an
  +     *                        exception when they happen
  +     * @param useTimestamp    whether to check the modified timestamp on the
  +     *                        <code>destinationFile</code> against the 
remote <code>source</code>
  +     * @param proxyHost       Proxy Host (if proxy is required), or null
  +     * @param proxyPort       Proxy Port (if proxy is required), or null
  +     * @param proxyUserName   Proxy Username (if authentification is 
required),
  +     *                        or null.
  +     * @param proxyPassword   Proxy Password (if authentification is 
required),
  +     *                        or null.
  +     * @param useChecksum     Flag to indicate the use of the checksum for 
the retrieved
  +     *                        artifact if it is available.
        */
       public static void getFile( String url,
                                   File destinationFile,
  @@ -142,26 +143,26 @@
       }
   
       /**
  -     * Retrieve a remote file.  Throws an Exception on errors unless the 
  +     * Retrieve a remote file.  Throws an Exception on errors unless the
        * ifnoreErrors flag is set to True
        *
  -     * @param url the of the file to retrieve
  +     * @param url             the of the file to retrieve
        * @param destinationFile where to store it
  -     * @param ignoreErrors whether to ignore errors during I/O or throw an
  -     *      exception when they happen
  -     * @param useTimestamp whether to check the modified timestamp on the
  -     *      <code>destinationFile</code> against the remote 
<code>source</code>
  -     * @param proxyHost Proxy Host (if proxy is required), or null
  -     * @param proxyPort Proxy Port (if proxy is required), or null
  -     * @param proxyUserName Proxy Username (if authentification is required),
  -     *        or null.
  -     * @param proxyPassword Proxy Password (if authentification is required),
  -     *        or null.
  -     * @param useChecksum Flag to indicate the use of the checksum for the 
retrieved
  -     *        artifact if it is available.
  -     * @param loginHost The host the authentication request is originating 
from. 
  -     *        Essentially, the computer name for this machine.
  -     * @param loginDomain the domain to authenticate within.
  +     * @param ignoreErrors    whether to ignore errors during I/O or throw an
  +     *                        exception when they happen
  +     * @param useTimestamp    whether to check the modified timestamp on the
  +     *                        <code>destinationFile</code> against the 
remote <code>source</code>
  +     * @param proxyHost       Proxy Host (if proxy is required), or null
  +     * @param proxyPort       Proxy Port (if proxy is required), or null
  +     * @param proxyUserName   Proxy Username (if authentification is 
required),
  +     *                        or null.
  +     * @param proxyPassword   Proxy Password (if authentification is 
required),
  +     *                        or null.
  +     * @param useChecksum     Flag to indicate the use of the checksum for 
the retrieved
  +     *                        artifact if it is available.
  +     * @param loginHost       The host the authentication request is 
originating from.
  +     *                        Essentially, the computer name for this 
machine.
  +     * @param loginDomain     the domain to authenticate within.
        */
       public static void getFile( String url,
                                   File destinationFile,
  @@ -211,21 +212,21 @@
       }
   
       /**
  -     * Retrieve a remote file.  Throws an Exception on errors unless the 
  +     * Retrieve a remote file.  Throws an Exception on errors unless the
        * ifnoreErrors flag is set to True
        *
  -     * @param url the of the file to retrieve
  +     * @param url             the of the file to retrieve
        * @param destinationFile where to store it
  -     * @param ignoreErrors whether to ignore errors during I/O or throw an
  -     *      exception when they happen
  -     * @param useTimestamp whether to check the modified timestamp on the
  -     *      <code>destinationFile</code> against the remote 
<code>source</code>
  -     * @param proxyHost Proxy Host (if proxy is required), or null
  -     * @param proxyPort Proxy Port (if proxy is required), or null
  -     * @param proxyUserName Proxy Username (if authentification is required),
  -     *        or null
  -     * @param proxyPassword Proxy Password (if authentification is required),
  -     *        or null
  +     * @param ignoreErrors    whether to ignore errors during I/O or throw an
  +     *                        exception when they happen
  +     * @param useTimestamp    whether to check the modified timestamp on the
  +     *                        <code>destinationFile</code> against the 
remote <code>source</code>
  +     * @param proxyHost       Proxy Host (if proxy is required), or null
  +     * @param proxyPort       Proxy Port (if proxy is required), or null
  +     * @param proxyUserName   Proxy Username (if authentification is 
required),
  +     *                        or null
  +     * @param proxyPassword   Proxy Password (if authentification is 
required),
  +     *                        or null
        */
       public static void getFile( String url,
                                   File destinationFile,
  @@ -244,22 +245,22 @@
        * Retrieve a remote file.  Throws an Exception on errors unless the
        * ifnoreErrors flag is set to True
        *
  -     * @param url the of the file to retrieve
  +     * @param url             the of the file to retrieve
        * @param destinationFile where to store it
  -     * @param ignoreErrors whether to ignore errors during I/O or throw an
  -     *      exception when they happen
  -     * @param useTimestamp whether to check the modified timestamp on the
  -     *      <code>destinationFile</code> against the remote 
<code>source</code>
  -     * @param proxyHost Proxy Host (if proxy is required), or null
  -     * @param proxyPort Proxy Port (if proxy is required), or null
  -     * @param proxyUserName Proxy Username (if authentification is required),
  -     *        or null
  -     * @param proxyPassword Proxy Password (if authentification is required),
  -     *        or null
  -     * @param loginHost The host the authentication request is originating 
from.
  -     *        Essentially, the computer name for this machine.
  -     * @param loginDomain the domain to authenticate within.
  -     * @param downloadMeter the download meter to use
  +     * @param ignoreErrors    whether to ignore errors during I/O or throw an
  +     *                        exception when they happen
  +     * @param useTimestamp    whether to check the modified timestamp on the
  +     *                        <code>destinationFile</code> against the 
remote <code>source</code>
  +     * @param proxyHost       Proxy Host (if proxy is required), or null
  +     * @param proxyPort       Proxy Port (if proxy is required), or null
  +     * @param proxyUserName   Proxy Username (if authentification is 
required),
  +     *                        or null
  +     * @param proxyPassword   Proxy Password (if authentification is 
required),
  +     *                        or null
  +     * @param loginHost       The host the authentication request is 
originating from.
  +     *                        Essentially, the computer name for this 
machine.
  +     * @param loginDomain     the domain to authenticate within.
  +     * @param downloadMeter   the download meter to use
        */
       public static void getFile( String url,
                                   File destinationFile,
  @@ -306,22 +307,22 @@
       /**
        * Retrieve a remote file.
        *
  -     * @param url the URL of the file to retrieve
  +     * @param url             the URL of the file to retrieve
        * @param destinationFile where to store it
  -     * @param timestamp if provided, the remote URL is only retrieved if it 
was
  -     * modified more recently than timestamp. Otherwise, negative value 
indicates that
  -     * the remote URL should be retrieved unconditionally.
  -     * @param proxyHost Proxy Host (if proxy is required), or null
  -     * @param proxyPort Proxy Port (if proxy is required), or null
  -     * @param proxyUserName Proxy Username (if authentification is required),
  -     *        or null
  -     * @param proxyPassword Proxy Password (if authentification is required),
  -     *        or null
  -     * @param loginHost The host the authentication request is originating 
from. 
  -     *        Essentially, the computer name for this machine.
  -     * @param loginDomain the domain to authenticate within.
  -     * @param downloadMeter the download meter to use
  -     * @exception IOException If an I/O exception occurs.
  +     * @param timestamp       if provided, the remote URL is only retrieved 
if it was
  +     *                        modified more recently than timestamp. 
Otherwise, negative value indicates that
  +     *                        the remote URL should be retrieved 
unconditionally.
  +     * @param proxyHost       Proxy Host (if proxy is required), or null
  +     * @param proxyPort       Proxy Port (if proxy is required), or null
  +     * @param proxyUserName   Proxy Username (if authentification is 
required),
  +     *                        or null
  +     * @param proxyPassword   Proxy Password (if authentification is 
required),
  +     *                        or null
  +     * @param loginHost       The host the authentication request is 
originating from.
  +     *                        Essentially, the computer name for this 
machine.
  +     * @param loginDomain     the domain to authenticate within.
  +     * @param downloadMeter   the download meter to use
  +     * @throws IOException If an I/O exception occurs.
        */
       public static void getFile( String url,
                                   File destinationFile,
  @@ -333,7 +334,7 @@
                                   String loginHost,
                                   String loginDomain,
                                   DownloadMeter downloadMeter )
  -      throws IOException
  +        throws IOException
       {
           String[] s = parseUrl( url );
           String username = s[0];
  @@ -347,56 +348,66 @@
           }
   
           URL source = new URL( parsedUrl );
  -        if (source.getProtocol().equals("http") || 
source.getProtocol().equals("https")) {
  +        if ( source.getProtocol().equals( "http" ) || 
source.getProtocol().equals( "https" ) )
  +        {
               Credentials creds = null;
  -            if (!empty(loginHost) || !empty(loginDomain)) {
  -                creds = new NTCredentials(proxyUserName, proxyPassword, 
loginHost, loginDomain);
  +            if ( !empty( loginHost ) || !empty( loginDomain ) )
  +            {
  +                creds = new NTCredentials( proxyUserName, proxyPassword, 
loginHost, loginDomain );
               }
  -            else if (!empty(proxyUserName) || !empty(proxyPassword)) {
  -                creds = new UsernamePasswordCredentials(proxyUserName, 
proxyPassword);
  +            else if ( !empty( proxyUserName ) || !empty( proxyPassword ) )
  +            {
  +                creds = new UsernamePasswordCredentials( proxyUserName, 
proxyPassword );
               }
  -        
  +
               HttpClient client = new HttpClient();
               HostConfiguration hc = new HostConfiguration();
  -            hc.setHost(source.getHost(), source.getPort(), 
source.getProtocol());
  +            hc.setHost( source.getHost(), source.getPort(), 
source.getProtocol() );
   
  -            if (!empty(proxyHost) || !empty(proxyPort)) {
  -                try {
  -                    hc.setProxy(proxyHost, Integer.parseInt(proxyPort));
  -                } catch (NumberFormatException e) {
  -                    LOG.error("Unable to parse proxy port '"+proxyPort+"', 
ignoring proxy settings");
  +            if ( !empty( proxyHost ) || !empty( proxyPort ) )
  +            {
  +                try
  +                {
  +                    hc.setProxy( proxyHost, Integer.parseInt( proxyPort ) );
  +                }
  +                catch ( NumberFormatException e )
  +                {
  +                    LOG.error( "Unable to parse proxy port '" + proxyPort + 
"', ignoring proxy settings" );
                   }
               }
  -            client.setHostConfiguration(hc);
  -            if (creds != null) {
  -                client.getState().setProxyCredentials(null, null, creds);
  +            client.setHostConfiguration( hc );
  +            if ( creds != null )
  +            {
  +                client.getState().setProxyCredentials( null, null, creds );
                   client.getState().setAuthenticationPreemptive( true );
               }
   
               // Basic authentication
               if ( username != null || password != null )
               {
  -                creds = new UsernamePasswordCredentials(username, password);
  -                client.getState().setCredentials(null, null, creds);
  +                creds = new UsernamePasswordCredentials( username, password 
);
  +                client.getState().setCredentials( null, null, creds );
                   client.getState().setAuthenticationPreemptive( true );
               }
   
  -            for (int i = 0; i < REDIRECT_LIMIT; i++ )
  +            for ( int i = 0; i < REDIRECT_LIMIT; i++ )
               {
  -                String redirect = retrieveArtifact(client, source, 
destinationFile, timestamp, downloadMeter);
  -                if (redirect == null) {
  +                String redirect = retrieveArtifact( client, source, 
destinationFile, timestamp, downloadMeter );
  +                if ( redirect == null )
  +                {
                       break;
                   }
  -                if (i >= REDIRECT_LIMIT - 1) {
  -                    throw new IOException("Redirection limit of " + 
REDIRECT_LIMIT + " exceeded");
  +                if ( i >= REDIRECT_LIMIT - 1 )
  +                {
  +                    throw new IOException( "Redirection limit of " + 
REDIRECT_LIMIT + " exceeded" );
                   }
   
                   redirect = StringUtils.replace( redirect, ":/", "://" );
                   redirect = StringUtils.replace( redirect, "//", "/" );
   
                   source = new URL( redirect );
  -                hc.setHost(source.getHost(), source.getPort(), 
source.getProtocol());
  -                client.setHostConfiguration(hc);
  +                hc.setHost( source.getHost(), source.getPort(), 
source.getProtocol() );
  +                client.setHostConfiguration( hc );
               }
           }
           else
  @@ -407,7 +418,8 @@
               //set up the URL connection
               URLConnection connection = source.openConnection();
               InputStream is = null;
  -            try {
  +            try
  +            {
                   //modify the headers
                   if ( timestamp >= 0 )
                   {
  @@ -418,7 +430,7 @@
                   if ( username != null || password != null )
                   {
                       String up = username + ":" + password;
  -                    String encoding = Base64.encode(up.getBytes(), false);
  +                    String encoding = Base64.encode( up.getBytes(), false );
                       connection.setRequestProperty( "Authorization", "Basic " 
+ encoding );
                   }
   
  @@ -427,185 +439,248 @@
   
                   if ( connection.getLastModified() <= timestamp && 
connection.getLastModified() != 0 )
                   {
  -                    LOG.debug("Not modified");
  +                    LOG.debug( "Not modified" );
                       return;
                   }
   
                   long remoteTimestamp = connection.getLastModified();
   
                   is = connection.getInputStream();
  -                process( true, is, destinationFile, 0, timestamp, 
remoteTimestamp, downloadMeter );
  +                process( is, destinationFile, 0, timestamp, remoteTimestamp, 
downloadMeter );
               }
  -            finally {
  -                if (is != null) try { is.close(); } catch (Exception e) { 
LOG.error("error closing stream", e); }
  +            finally
  +            {
  +                if ( is != null )
  +                    try
  +                    {
  +                        is.close();
  +                    }
  +                    catch ( Exception e )
  +                    {
  +                        LOG.error( "error closing stream", e );
  +                    }
               }
           }
       }
   
  -    private static String retrieveArtifact(HttpClient client, URL source, 
File destinationFile, long timestamp, DownloadMeter downloadMeter ) throws 
FileNotFoundException, IOException, HttpRecoverableException {
  +    private static String retrieveArtifact( HttpClient client, URL source, 
File destinationFile, long timestamp, DownloadMeter downloadMeter ) throws 
FileNotFoundException, IOException, HttpRecoverableException
  +    {
           int statusCode = -1;
           String redirectUrl = null;
           InputStream is = null;
  -        GetMethod get = new GetMethod(source.getPath());
  +        GetMethod get = new GetMethod( source.getPath() );
           // Handle these ourselves until httpclient deals with cross host 
redirects
  -        get.setFollowRedirects(false);
  -        try {
  +        get.setFollowRedirects( false );
  +        try
  +        {
               if ( timestamp >= 0 )
               {
  -                SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy 
HH:mm:ss zzz", Locale.US);
  -                fmt.setTimeZone(GMT_TIME_ZONE);
  -                Header hdr = new Header("If-Modified-Since", fmt.format(new 
Date(timestamp)));
  -                LOG.debug("sending ==> " + hdr + "(" + timestamp + ")");
  -                get.addRequestHeader(hdr);
  +                SimpleDateFormat fmt = new SimpleDateFormat( "EEE, dd-MMM-yy 
HH:mm:ss zzz", Locale.US );
  +                fmt.setTimeZone( GMT_TIME_ZONE );
  +                Header hdr = new Header( "If-Modified-Since", fmt.format( 
new Date( timestamp ) ) );
  +                LOG.debug( "sending ==> " + hdr + "(" + timestamp + ")" );
  +                get.addRequestHeader( hdr );
               }
   
               // We will retry up to 3 times.
  -            for (int i = 0; i < 3; i++)
  +            for ( int i = 0; i < 3; i++ )
               {
  -                try 
  +                try
                   {
  -                    statusCode = client.executeMethod(get);
  -                    if (statusCode != -1) {
  -                        LOG.debug("Received status code: " + statusCode);
  +                    statusCode = client.executeMethod( get );
  +                    if ( statusCode != -1 )
  +                    {
  +                        LOG.debug( "Received status code: " + statusCode );
                           break;
                       }
                   }
  -                catch (HttpRecoverableException e)
  +                catch ( HttpRecoverableException e )
                   {
  -                    if (i >= 2) {
  +                    if ( i >= 2 )
  +                    {
                           throw e;
                       }
  -                    LOG.warn( "A recoverable exception occurred." + 
e.getMessage());
  +                    LOG.warn( "A recoverable exception occurred." + 
e.getMessage() );
                   }
  -                catch (IOException e)
  +                catch ( IOException e )
                   {
                       throw e;
                   }
  -                LOG.warn("retrying (" + (i + 1) + ")");
  +                LOG.warn( "retrying (" + ( i + 1 ) + ")" );
               }
  -    
  -            boolean use = statusCode < 300;
   
  -            if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
  -                LOG.debug("Not modified");
  +            boolean isOk = statusCode < 300;
  +
  +            if ( statusCode == HttpURLConnection.HTTP_NOT_MODIFIED )
  +            {
  +                LOG.debug( "Not modified" );
               }
  -            else if (statusCode >= 300 && statusCode < 400) {
  -                Header header = get.getResponseHeader("Location");
  -                if (header != null) {
  +            else if ( statusCode >= 300 && statusCode < 400 )
  +            {
  +                Header header = get.getResponseHeader( "Location" );
  +                if ( header != null )
  +                {
                       redirectUrl = header.getValue();
  -                    LOG.debug("Location: " + redirectUrl);
  +                    LOG.debug( "Location: " + redirectUrl );
                   }
  -                else {
  -                    LOG.warn("Location header not specified");
  +                else
  +                {
  +                    LOG.warn( "Location header not specified" );
                   }
               }
   
               // Must read content regardless
               is = get.getResponseBodyAsStream();
  -            if (is == null) {
  +            if ( is == null )
  +            {
  +                // This could be null, which is fine. The reponse just 
wasn't a redirect.
                   return redirectUrl;
               }
   
  -            int projected = 0;
  -            Header header = get.getResponseHeader("Content-Length");
  -            if (header != null) {
  -                try {
  -                    projected = 
Integer.valueOf(header.getValue()).intValue();
  -                }
  -                catch (NumberFormatException e) {
  -                    LOG.warn( "error parsing content length header '" + 
header.getValue() + "' " + e );
  +            if ( isOk )
  +            {
  +                int projected = 0;
  +                Header header = get.getResponseHeader( "Content-Length" );
  +                if ( header != null )
  +                {
  +                    try
  +                    {
  +                        projected = Integer.valueOf( header.getValue() 
).intValue();
  +                    }
  +                    catch ( NumberFormatException e )
  +                    {
  +                        LOG.warn( "error parsing content length header '" + 
header.getValue() + "' " + e );
  +                    }
                   }
  -            }
   
  -            long remoteTimestamp = 0;
  -            if ( use ) {
  -                header = get.getResponseHeader("Last-Modified");
  -                if (header != null) {
  -                    try {
  -                        remoteTimestamp = 
DateParser.parseDate(header.getValue()).getTime();
  +                long remoteTimestamp = 0;
  +                header = get.getResponseHeader( "Last-Modified" );
  +                if ( header != null )
  +                {
  +                    try
  +                    {
  +                        remoteTimestamp = DateParser.parseDate( 
header.getValue() ).getTime();
                       }
  -                    catch (DateParseException e) {
  -                        LOG.warn("Unable to parse last modified header", e );
  +                    catch ( DateParseException e )
  +                    {
  +                        LOG.warn( "Unable to parse last modified header", e 
);
                       }
  -                    LOG.debug("last-modified = " + header.getValue() + " (" 
+ remoteTimestamp + ")");
  +                    LOG.debug( "last-modified = " + header.getValue() + " (" 
+ remoteTimestamp + ")" );
                   }
  -                else {
  -                    LOG.warn("warning: last-modified not specified");
  +                else
  +                {
  +                    LOG.warn( "warning: last-modified not specified" );
                   }
                   if ( remoteTimestamp <= timestamp && remoteTimestamp != 0 )
                   {
  -                    LOG.debug("Not modified - local file is newer");
  -                    // TODO: httpclient doesn't seem to think it is valid to 
close the stream before its done like this. Why?
  -                    // use = false;
  -                    return null;
  +                    LOG.debug( "Not modified - local file is newer" );
                   }
  +                else
  +                {
  +                    process( is, destinationFile, projected, timestamp, 
remoteTimestamp, downloadMeter );
  +                }
  +                return null;
               }
  -            process( use, is, destinationFile, projected, timestamp, 
remoteTimestamp, downloadMeter );
  -        }
  -        finally {
  -            if (is != null) try { is.close(); } catch (Exception e) { 
LOG.error("error closing stream", e); }
  -            get.releaseConnection();
  -        }
  +            else
  +            {
  +                readAndDispose( is );
   
  -        if ( statusCode == HttpURLConnection.HTTP_NOT_FOUND)
  -        {
  -            throw new FileNotFoundException(source.toString());
  -        }
  -        // test for 401 result (HTTP only)
  -        if ( statusCode == HttpURLConnection.HTTP_UNAUTHORIZED )
  -        {
  -            throw new IOException( "Not authorized." );
  +                if ( statusCode == HttpURLConnection.HTTP_NOT_FOUND )
  +                {
  +                    throw new FileNotFoundException( source.toString() );
  +                }
  +                // test for 401 result (HTTP only)
  +                if ( statusCode == HttpURLConnection.HTTP_UNAUTHORIZED )
  +                {
  +                    throw new IOException( "Not authorized." );
  +                }
  +                // test for 403 result (HTTP only)
  +                if ( statusCode == HttpURLConnection.HTTP_FORBIDDEN )
  +                {
  +                    throw new IOException( "Forbidden." );
  +                }
  +                // test for 407 result (HTTP only)
  +                if ( statusCode == HttpURLConnection.HTTP_PROXY_AUTH )
  +                {
  +                    throw new IOException( "Not authorized by proxy." );
  +                }
  +                throw new IOException( "Unknown error downloading; status 
code was: " + statusCode );
  +            }
           }
  -        // test for 407 result (HTTP only)
  -        if ( statusCode == HttpURLConnection.HTTP_PROXY_AUTH )
  +        finally
           {
  -            throw new IOException( "Not authorized by proxy." );
  +            if ( is != null )
  +            {
  +                try
  +                {
  +                    is.close();
  +                }
  +                catch ( Exception e )
  +                {
  +                    LOG.error( "error closing stream", e );
  +                }
  +            }
  +            get.releaseConnection();
           }
  -        return redirectUrl;
       }
   
  -    private static void process( boolean use, InputStream is, File 
destinationFile, int projected, long timestamp, long remoteTimestamp, 
DownloadMeter downloadMeter ) 
  -        throws IOException {
  +    private static void process( InputStream is, File destinationFile, int 
projected, long timestamp, long remoteTimestamp, DownloadMeter downloadMeter )
  +        throws IOException
  +    {
           byte[] buffer = new byte[100 * 1024];
           int length, total = 0;
           OutputStream os = null;
   
  -        try {
  -            if ( use ) {
  -                os = new FileOutputStream( destinationFile );
  -            }
  +        try
  +        {
  +            os = new FileOutputStream( destinationFile );
               while ( ( length = is.read( buffer ) ) >= 0 )
               {
  -                if ( use ) {
  -                    os.write( buffer, 0, length );
  -                    total += length;
  -                    downloadMeter.update( total, projected );
  -                }
  +                os.write( buffer, 0, length );
  +                total += length;
  +                downloadMeter.update( total, projected );
               }
           }
  -        finally {
  -            if (os != null) try { os.close(); } catch (Exception e) { 
LOG.error("error closing stream", e); }
  +        finally
  +        {
  +            if ( os != null )
  +                try
  +                {
  +                    os.close();
  +                }
  +                catch ( Exception e )
  +                {
  +                    LOG.error( "error closing stream", e );
  +                }
           }
   
  -        if ( use ) {
  -            downloadMeter.finish( total );
  +        downloadMeter.finish( total );
   
  -            LOG.debug("Local timestamp: " + timestamp);
  -            LOG.debug("Remote timestamp: " + remoteTimestamp);
  -  
  -            // if (and only if) the use file time option is set, then the
  -            // saved file now has its timestamp set to that of the downloaded
  -            // file
  -            if ( timestamp >= 0 )
  +        LOG.debug( "Local timestamp: " + timestamp );
  +        LOG.debug( "Remote timestamp: " + remoteTimestamp );
  +
  +        // if (and only if) the use file time option is set, then the
  +        // saved file now has its timestamp set to that of the downloaded
  +        // file
  +        if ( timestamp >= 0 )
  +        {
  +            if ( remoteTimestamp != 0 )
               {
  -                if ( remoteTimestamp != 0 )
  -                {
  -                    touchFile( destinationFile, remoteTimestamp );
  -                }
  +                touchFile( destinationFile, remoteTimestamp );
               }
           }
       }
   
  +    private static void readAndDispose( InputStream is )
  +        throws IOException
  +    {
  +        byte[] buffer = new byte[100 * 1024];
  +
  +        while ( is.read( buffer ) >= 0 )
  +        {
  +        }
  +    }
  +
       /**
        * Parse an url which might contain a username and password. If the
        * given url doesn't contain a username and password then return the
  @@ -630,7 +705,7 @@
           int i = url.indexOf( "@" );
           if ( i > 0 )
           {
  -            String protocol = url.substring( 0, url.indexOf("://") ) + "://";
  +            String protocol = url.substring( 0, url.indexOf( "://" ) ) + 
"://";
               String s = url.substring( protocol.length(), i );
               int j = s.indexOf( ":" );
               parsedUrl[0] = s.substring( 0, j );
  @@ -644,10 +719,10 @@
       /**
        * set the timestamp of a named file to a specified time.
        *
  -     * @param file the file to touch
  +     * @param file       the file to touch
        * @param timemillis in milliseconds since the start of the era
        * @return true if it succeeded. False means that this is a java1.1 
system
  -     *      and that file times can not be set
  +     *         and that file times can not be set
        */
       private static boolean touchFile( File file, long timemillis )
       {
  @@ -662,29 +737,37 @@
               modifiedTime = timemillis;
           }
   
  -        LOG.debug("touching " + file + " with " + modifiedTime);
  +        LOG.debug( "touching " + file + " with " + modifiedTime );
           file.setLastModified( modifiedTime );
           return true;
       }
   
  -    private static boolean empty(String s) { return s == null || s.length() 
== 0; }
  +    private static boolean empty( String s )
  +    {
  +        return s == null || s.length() == 0;
  +    }
   
       /**
        * @todo this method of setting the meter is not desirable... but a 
static method class is not really
  -     *   conducive to anything else :)
  +     * conducive to anything else :)
        */
  -    public static void setMeterType(String type) {
  -        if (type.equals("bootstrap")) { 
  +    public static void setMeterType( String type )
  +    {
  +        if ( type.equals( "bootstrap" ) )
  +        {
               defaultDownloadMeter = new BootstrapDownloadMeter();
           }
  -        else if (type.equals("console")) { 
  +        else if ( type.equals( "console" ) )
  +        {
               defaultDownloadMeter = new ConsoleDownloadMeter();
           }
  -        else if (type.equals("silent")) { 
  +        else if ( type.equals( "silent" ) )
  +        {
               defaultDownloadMeter = new SilentDownloadMeter();
           }
  -        else {
  -            LOG.warn("Unknown download meter type: " + type);
  +        else
  +        {
  +            LOG.warn( "Unknown download meter type: " + type );
           }
       }
   }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to