1 package org.apache.maven.repository.proxy;
4 * Copyright 2005-2006 The Apache Software Foundation.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 import org.apache.maven.artifact.Artifact;
20 import org.apache.maven.artifact.manager.ChecksumFailedException;
21 import org.apache.maven.artifact.repository.ArtifactRepository;
22 import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
23 import org.apache.maven.repository.discovery.ArtifactDiscoverer;
24 import org.apache.maven.repository.discovery.DiscovererException;
25 import org.apache.maven.wagon.ConnectionException;
26 import org.apache.maven.wagon.ResourceDoesNotExistException;
27 import org.apache.maven.wagon.TransferFailedException;
28 import org.apache.maven.wagon.Wagon;
29 import org.apache.maven.wagon.authentication.AuthenticationException;
30 import org.apache.maven.wagon.authorization.AuthorizationException;
31 import org.apache.maven.wagon.observers.ChecksumObserver;
32 import org.apache.maven.wagon.proxy.ProxyInfo;
33 import org.apache.maven.wagon.repository.Repository;
34 import org.codehaus.plexus.logging.AbstractLogEnabled;
35 import org.codehaus.plexus.util.FileUtils;
38 import java.io.IOException;
39 import java.security.NoSuchAlgorithmException;
40 import java.util.Date;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
47 * An implementation of the proxy handler.
49 * @author <a href="mailto:brett@apache.org">Brett Porter</a>
51 * @todo this currently duplicates a lot of the wagon manager, and doesn't do things like snapshot resolution, etc.
52 * Should we have a more artifact based one? This will merge metadata so should behave correctly, and it is able to
53 * correct some limitations of the wagon manager (eg, it can retrieve newer SNAPSHOT files without metadata)
55 public class DefaultProxyRequestHandler
56 extends AbstractLogEnabled
57 implements ProxyRequestHandler
60 * @plexus.requirement role-hint="default"
61 * @todo use a map, and have priorities in them
63 private ArtifactDiscoverer defaultArtifactDiscoverer;
66 * @plexus.requirement role-hint="legacy"
68 private ArtifactDiscoverer legacyArtifactDiscoverer;
71 * @plexus.requirement role="org.apache.maven.wagon.Wagon"
73 private Map/*<String,Wagon>*/ wagons;
75 public File get( String path, List proxiedRepositories, ArtifactRepository managedRepository )
76 throws ProxyException, ResourceDoesNotExistException
78 return get( path, proxiedRepositories, managedRepository, null );
81 public File get( String path, List proxiedRepositories, ArtifactRepository managedRepository, ProxyInfo wagonProxy )
82 throws ProxyException, ResourceDoesNotExistException
84 // TODO! this will prove wrong for metadata and snapshots, let tests bring it out
85 //@todo use wagonManager for cache use file:// as URL
86 File cachedFile = new File( managedRepository.getBasedir(), path );
87 if ( !cachedFile.exists() )
89 cachedFile = getAlways( path, proxiedRepositories, managedRepository, wagonProxy );
95 public File getAlways( String path, List proxiedRepositories, ArtifactRepository managedRepository )
96 throws ProxyException, ResourceDoesNotExistException
98 return getAlways( path, proxiedRepositories, managedRepository, null );
101 public File getAlways( String path, List proxiedRepositories, ArtifactRepository managedRepository,
102 ProxyInfo wagonProxy )
103 throws ProxyException, ResourceDoesNotExistException
105 File target = new File( managedRepository.getBasedir(), path );
107 for ( Iterator i = proxiedRepositories.iterator(); i.hasNext(); )
109 ProxiedArtifactRepository repository = (ProxiedArtifactRepository) i.next();
111 if ( repository.isCachedFailure( path ) )
113 getLogger().debug( "Skipping repository " + repository.getName() + " for a cached path failure." );
117 if ( path.endsWith( ".md5" ) || path.endsWith( ".sha1" ) )
119 // always read from the managed repository, no need to make remote request
121 else if ( path.endsWith( "maven-metadata.xml" ) )
123 // TODO: this is not always!
124 if ( !target.exists() || isOutOfDate( repository.getRepository().getReleases(), target ) )
126 getFileFromRepository( path, repository, managedRepository.getBasedir(), wagonProxy, target );
131 Artifact artifact = null;
134 artifact = defaultArtifactDiscoverer.buildArtifact( path );
136 catch ( DiscovererException e )
139 "Failed to build artifact using default layout with message: " + e.getMessage() );
142 if ( artifact == null )
146 artifact = legacyArtifactDiscoverer.buildArtifact( path );
148 catch ( DiscovererException e )
151 "Failed to build artifact using legacy layout with message: " + e.getMessage() );
155 if ( artifact != null )
157 getArtifactFromRepository( artifact, repository, managedRepository, wagonProxy, target );
161 // Some other unknown file in the repository, proxy as is
162 // TODO: this is not always!
163 if ( !target.exists() )
165 getFileFromRepository( path, repository, managedRepository.getBasedir(), wagonProxy,
171 if ( !target.exists() )
173 repository.addFailure( path );
177 // in case it previously failed and we've since found it
178 repository.clearFailure( path );
183 if ( !target.exists() )
185 throw new ResourceDoesNotExistException( "Could not find " + path + " in any of the repositories." );
191 private void getFileFromRepository( String path, ProxiedArtifactRepository repository, String repositoryCachePath,
192 ProxyInfo httpProxy, File target )
193 throws ProxyException, ResourceDoesNotExistException
195 boolean connected = false;
196 Map checksums = null;
201 String protocol = repository.getRepository().getProtocol();
202 wagon = (Wagon) wagons.get( protocol );
205 throw new ProxyException( "Unsupported remote protocol: " + protocol );
208 //@todo configure wagon (ssh settings, etc)
210 checksums = prepareChecksumListeners( wagon );
212 connected = connectToRepository( wagon, repository, httpProxy );
215 File temp = new File( target.getAbsolutePath() + ".tmp" );
225 getLogger().info( "Trying " + path + " from " + repository.getName() + "..." );
227 if ( !target.exists() )
229 wagon.get( path, temp );
233 wagon.getIfNewer( path, temp, target.lastModified() );
236 success = doChecksumCheck( checksums, path, wagon, repositoryCachePath );
238 if ( tries > 1 && !success )
240 throw new ProxyException( "Checksum failures occurred while downloading " + path );
245 disconnectWagon( wagon );
249 moveTempToTarget( temp, target );
252 //try next repository
254 catch ( TransferFailedException e )
256 String message = "Skipping repository " + repository.getName() + ": " + e.getMessage();
257 processRepositoryFailure( repository, message, e );
259 catch ( AuthorizationException e )
261 String message = "Skipping repository " + repository.getName() + ": " + e.getMessage();
262 processRepositoryFailure( repository, message, e );
266 if ( wagon != null && checksums != null )
268 releaseChecksumListeners( wagon, checksums );
273 disconnectWagon( wagon );
278 private static boolean isOutOfDate( ArtifactRepositoryPolicy policy, File target )
280 return policy != null && policy.checkOutOfDate( new Date( target.lastModified() ) );
284 * Used to add checksum observers as transfer listeners to the wagonManager object
286 * @param wagon the wagonManager object to use the checksum with
287 * @return map of ChecksumObservers added into the wagonManager transfer listeners
289 private Map prepareChecksumListeners( Wagon wagon )
291 Map checksums = new HashMap();
294 ChecksumObserver checksum = new ChecksumObserver( "SHA-1" );
295 wagon.addTransferListener( checksum );
296 checksums.put( "sha1", checksum );
298 checksum = new ChecksumObserver( "MD5" );
299 wagon.addTransferListener( checksum );
300 checksums.put( "md5", checksum );
302 catch ( NoSuchAlgorithmException e )
304 getLogger().info( "An error occurred while preparing checksum observers", e );
309 private void releaseChecksumListeners( Wagon wagon, Map checksumMap )
311 for ( Iterator checksums = checksumMap.values().iterator(); checksums.hasNext(); )
313 ChecksumObserver listener = (ChecksumObserver) checksums.next();
314 wagon.removeTransferListener( listener );
318 private boolean connectToRepository( Wagon wagon, ProxiedArtifactRepository repository, ProxyInfo httpProxy )
320 boolean connected = false;
323 ArtifactRepository artifactRepository = repository.getRepository();
324 Repository wagonRepository = new Repository( artifactRepository.getId(), artifactRepository.getUrl() );
325 if ( repository.isUseNetworkProxy() && httpProxy != null )
327 wagon.connect( wagonRepository, httpProxy );
331 wagon.connect( wagonRepository );
335 catch ( ConnectionException e )
337 getLogger().info( "Could not connect to " + repository.getName() + ": " + e.getMessage() );
339 catch ( AuthenticationException e )
341 getLogger().info( "Could not connect to " + repository.getName() + ": " + e.getMessage() );
347 private boolean doChecksumCheck( Map checksumMap, String path, Wagon wagon, String repositoryCachePath )
348 throws ProxyException
350 releaseChecksumListeners( wagon, checksumMap );
351 for ( Iterator checksums = checksumMap.keySet().iterator(); checksums.hasNext(); )
353 String checksumExt = (String) checksums.next();
354 ChecksumObserver checksum = (ChecksumObserver) checksumMap.get( checksumExt );
355 String checksumPath = path + "." + checksumExt;
356 File checksumFile = new File( repositoryCachePath, checksumPath );
360 File tempChecksumFile = new File( checksumFile.getAbsolutePath() + ".tmp" );
362 wagon.get( checksumPath, tempChecksumFile );
364 String remoteChecksum = FileUtils.fileRead( tempChecksumFile ).trim();
365 if ( remoteChecksum.indexOf( ' ' ) > 0 )
367 remoteChecksum = remoteChecksum.substring( 0, remoteChecksum.indexOf( ' ' ) );
370 boolean checksumCheck = false;
371 if ( remoteChecksum.toUpperCase().equals( checksum.getActualChecksum().toUpperCase() ) )
373 moveTempToTarget( tempChecksumFile, checksumFile );
375 checksumCheck = true;
377 return checksumCheck;
379 catch ( ChecksumFailedException e )
383 catch ( TransferFailedException e )
385 getLogger().debug( "An error occurred during the download of " + checksumPath + ": " + e.getMessage(),
387 // do nothing try the next checksum
389 catch ( ResourceDoesNotExistException e )
391 getLogger().debug( "An error occurred during the download of " + checksumPath + ": " + e.getMessage(),
393 // do nothing try the next checksum
395 catch ( AuthorizationException e )
397 getLogger().debug( "An error occurred during the download of " + checksumPath + ": " + e.getMessage(),
399 // do nothing try the next checksum
401 catch ( IOException e )
403 getLogger().debug( "An error occurred while reading the temporary checksum file.", e );
408 getLogger().debug( "Skipping checksum validation for " + path + ": No remote checksums available." );
414 * Used to move the temporary file to its real destination. This is patterned from the way WagonManager handles
415 * its downloaded files.
417 * @param temp The completed download file
418 * @param target The final location of the downloaded file
419 * @throws ProxyException when the temp file cannot replace the target file
421 private void moveTempToTarget( File temp, File target )
422 throws ProxyException
424 if ( target.exists() && !target.delete() )
426 throw new ProxyException( "Unable to overwrite existing target file: " + target.getAbsolutePath() );
429 if ( !temp.renameTo( target ) )
431 getLogger().warn( "Unable to rename tmp file to its final name... resorting to copy command." );
435 FileUtils.copyFile( temp, target );
437 catch ( IOException e )
439 throw new ProxyException( "Cannot copy tmp file to its final location", e );
449 * Used to disconnect the wagonManager from its repository
451 * @param wagon the connected wagonManager object
453 private void disconnectWagon( Wagon wagon )
459 catch ( ConnectionException e )
461 getLogger().error( "Problem disconnecting from wagonManager - ignoring: " + e.getMessage() );
466 * Queries the configuration on how to handle a repository download failure
468 * @param repository the repository object where the failure occurred
469 * @param message the message/reason for the failure
470 * @param t the cause for the exception
471 * @throws ProxyException if hard failure is enabled on the repository causing the failure
473 private void processRepositoryFailure( ProxiedArtifactRepository repository, String message, Throwable t )
474 throws ProxyException
476 if ( repository.isHardFail() )
478 throw new ProxyException(
479 "An error occurred in hardfailing repository " + repository.getName() + "...\n " + message, t );
483 getLogger().error( message, t );
487 private void getArtifactFromRepository( Artifact artifact, ProxiedArtifactRepository repository,
488 ArtifactRepository managedRepository, ProxyInfo httpProxy, File remoteFile )
489 throws ProxyException, ResourceDoesNotExistException
491 ArtifactRepository artifactRepository = repository.getRepository();
492 ArtifactRepositoryPolicy policy =
493 artifact.isSnapshot() ? artifactRepository.getSnapshots() : artifactRepository.getReleases();
495 if ( !policy.isEnabled() )
497 getLogger().debug( "Skipping disabled repository " + repository.getName() );
501 getLogger().debug( "Trying repository " + repository.getName() );
502 // Don't use releases policy, we don't want to perform updates on them (only metadata, as used earlier)
503 // TODO: this is not always!
504 if ( !remoteFile.exists() || isOutOfDate( policy, remoteFile ) )
506 getFileFromRepository( artifactRepository.pathOf( artifact ), repository,
507 managedRepository.getBasedir(), httpProxy, remoteFile );
509 getLogger().debug( " Artifact resolved" );
511 artifact.setResolved( true );