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.repository.ArtifactRepository;
21 import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
22 import org.apache.maven.artifact.repository.metadata.Metadata;
23 import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader;
24 import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer;
25 import org.apache.maven.repository.digest.DigestUtils;
26 import org.apache.maven.repository.digest.DigesterException;
27 import org.apache.maven.repository.discovery.ArtifactDiscoverer;
28 import org.apache.maven.repository.discovery.DiscovererException;
29 import org.apache.maven.wagon.ConnectionException;
30 import org.apache.maven.wagon.ResourceDoesNotExistException;
31 import org.apache.maven.wagon.TransferFailedException;
32 import org.apache.maven.wagon.Wagon;
33 import org.apache.maven.wagon.authentication.AuthenticationException;
34 import org.apache.maven.wagon.authorization.AuthorizationException;
35 import org.apache.maven.wagon.observers.ChecksumObserver;
36 import org.apache.maven.wagon.proxy.ProxyInfo;
37 import org.apache.maven.wagon.repository.Repository;
38 import org.codehaus.plexus.logging.AbstractLogEnabled;
39 import org.codehaus.plexus.util.FileUtils;
40 import org.codehaus.plexus.util.IOUtil;
41 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
44 import java.io.FileReader;
45 import java.io.FileWriter;
46 import java.io.IOException;
47 import java.security.NoSuchAlgorithmException;
48 import java.util.Date;
49 import java.util.Iterator;
50 import java.util.LinkedHashMap;
51 import java.util.List;
55 * An implementation of the proxy handler.
57 * @author <a href="mailto:brett@apache.org">Brett Porter</a>
59 * @todo use wagonManager for cache use file:// as URL
60 * @todo this currently duplicates a lot of the wagon manager, and doesn't do things like snapshot resolution, etc.
61 * The checksum handling is inconsistent with that of the wagon manager.
62 * Should we have a more artifact based one? This will merge metadata so should behave correctly, and it is able to
63 * correct some limitations of the wagon manager (eg, it can retrieve newer SNAPSHOT files without metadata)
65 public class DefaultProxyRequestHandler
66 extends AbstractLogEnabled
67 implements ProxyRequestHandler
70 * @plexus.requirement role-hint="default"
71 * @todo use a map, and have priorities in them
73 private ArtifactDiscoverer defaultArtifactDiscoverer;
76 * @plexus.requirement role-hint="legacy"
78 private ArtifactDiscoverer legacyArtifactDiscoverer;
81 * @plexus.requirement role="org.apache.maven.wagon.Wagon"
83 private Map/*<String,Wagon>*/ wagons;
86 * @plexus.requirement role="org.apache.maven.repository.digest.Digester"
88 private Map/*<String,Digester>*/ digesters;
90 public File get( String path, List proxiedRepositories, ArtifactRepository managedRepository )
91 throws ProxyException, ResourceDoesNotExistException
93 return get( path, proxiedRepositories, managedRepository, null );
96 public File get( String path, List proxiedRepositories, ArtifactRepository managedRepository, ProxyInfo wagonProxy )
97 throws ProxyException, ResourceDoesNotExistException
99 return get( managedRepository, path, proxiedRepositories, wagonProxy, false );
102 public File getAlways( String path, List proxiedRepositories, ArtifactRepository managedRepository )
103 throws ProxyException, ResourceDoesNotExistException
105 return getAlways( path, proxiedRepositories, managedRepository, null );
108 public File getAlways( String path, List proxiedRepositories, ArtifactRepository managedRepository,
109 ProxyInfo wagonProxy )
110 throws ResourceDoesNotExistException, ProxyException
112 return get( managedRepository, path, proxiedRepositories, wagonProxy, true );
115 private File get( ArtifactRepository managedRepository, String path, List proxiedRepositories, ProxyInfo wagonProxy,
117 throws ProxyException, ResourceDoesNotExistException
119 File target = new File( managedRepository.getBasedir(), path );
121 for ( Iterator i = proxiedRepositories.iterator(); i.hasNext(); )
123 ProxiedArtifactRepository repository = (ProxiedArtifactRepository) i.next();
125 if ( !force && repository.isCachedFailure( path ) )
127 processCachedRepositoryFailure( repository, "Cached failure found for: " + path );
131 get( path, target, repository, managedRepository, wagonProxy, force );
135 if ( !target.exists() )
137 throw new ResourceDoesNotExistException( "Could not find " + path + " in any of the repositories." );
143 private void get( String path, File target, ProxiedArtifactRepository repository,
144 ArtifactRepository managedRepository, ProxyInfo wagonProxy, boolean force )
145 throws ProxyException
147 ArtifactRepositoryPolicy policy;
149 if ( path.endsWith( ".md5" ) || path.endsWith( ".sha1" ) )
151 // always read from the managed repository, no need to make remote request
153 else if ( path.endsWith( "maven-metadata.xml" ) )
155 File metadataFile = new File( target.getParentFile(), ".metadata-" + repository.getRepository().getId() );
157 policy = repository.getRepository().getReleases();
159 // if it is snapshot metadata, use a different policy
160 if ( path.endsWith( "-SNAPSHOT/maven-metadata.xml" ) )
162 policy = repository.getRepository().getSnapshots();
165 if ( force || !metadataFile.exists() || isOutOfDate( policy, metadataFile ) )
167 getFileFromRepository( path, repository, managedRepository.getBasedir(), wagonProxy, metadataFile,
170 mergeMetadataFiles( target, metadataFile );
175 Artifact artifact = null;
178 artifact = defaultArtifactDiscoverer.buildArtifact( path );
180 catch ( DiscovererException e )
182 getLogger().debug( "Failed to build artifact using default layout with message: " + e.getMessage() );
185 if ( artifact == null )
189 artifact = legacyArtifactDiscoverer.buildArtifact( path );
191 catch ( DiscovererException e )
193 getLogger().debug( "Failed to build artifact using legacy layout with message: " + e.getMessage() );
197 if ( artifact != null )
199 ArtifactRepository artifactRepository = repository.getRepository();
201 // we use the release policy for tracking failures, but only check for updates on snapshots
202 // also, we don't look for updates on timestamp snapshot files, only non-unique-version ones
203 policy = artifact.isSnapshot() ? artifactRepository.getSnapshots() : artifactRepository.getReleases();
205 boolean needsUpdate = false;
206 if ( artifact.getVersion().endsWith( "-SNAPSHOT" ) && isOutOfDate( policy, target ) )
211 if ( needsUpdate || force || !target.exists() )
213 getFileFromRepository( artifactRepository.pathOf( artifact ), repository,
214 managedRepository.getBasedir(), wagonProxy, target, policy, force );
219 // Some other unknown file in the repository, proxy as is
220 if ( force || !target.exists() )
222 policy = repository.getRepository().getReleases();
223 getFileFromRepository( path, repository, managedRepository.getBasedir(), wagonProxy, target, policy,
229 if ( target.exists() )
231 // in case it previously failed and we've since found it
232 repository.clearFailure( path );
236 private void mergeMetadataFiles( File target, File metadataFile )
237 throws ProxyException
239 MetadataXpp3Reader reader = new MetadataXpp3Reader();
240 if ( metadataFile.exists() )
242 Metadata metadata = null;
243 if ( target.exists() )
245 FileReader fileReader = null;
248 fileReader = new FileReader( target );
249 metadata = reader.read( fileReader );
251 catch ( XmlPullParserException e )
253 throw new ProxyException( "Unable to parse existing metadata: " + e.getMessage(), e );
255 catch ( IOException e )
257 throw new ProxyException( "Unable to read existing metadata: " + e.getMessage(), e );
261 IOUtil.close( fileReader );
265 FileReader fileReader = null;
266 boolean changed = false;
269 fileReader = new FileReader( metadataFile );
270 Metadata newMetadata = reader.read( fileReader );
272 if ( metadata != null )
274 changed = metadata.merge( newMetadata );
278 metadata = newMetadata;
282 catch ( IOException e )
284 // ignore the merged file
285 getLogger().warn( "Unable to read new metadata: " + e.getMessage() );
287 catch ( XmlPullParserException e )
289 // ignore the merged file
290 getLogger().warn( "Unable to parse new metadata: " + e.getMessage() );
294 IOUtil.close( fileReader );
299 FileWriter fileWriter = null;
302 fileWriter = new FileWriter( target );
303 new MetadataXpp3Writer().write( fileWriter, metadata );
305 catch ( IOException e )
307 getLogger().warn( "Unable to store new metadata: " + e.getMessage() );
311 IOUtil.close( fileWriter );
317 private void getFileFromRepository( String path, ProxiedArtifactRepository repository, String repositoryCachePath,
318 ProxyInfo httpProxy, File target, ArtifactRepositoryPolicy policy,
320 throws ProxyException
322 if ( !policy.isEnabled() )
324 getLogger().debug( "Skipping disabled repository " + repository.getName() );
328 Map checksums = null;
331 File temp = new File( target.getAbsolutePath() + ".tmp" );
334 boolean connected = false;
337 String protocol = repository.getRepository().getProtocol();
338 wagon = (Wagon) wagons.get( protocol );
341 throw new ProxyException( "Unsupported remote protocol: " + protocol );
344 //@todo configure wagon (ssh settings, etc)
346 checksums = prepareChecksumListeners( wagon );
348 connected = connectToRepository( wagon, repository, httpProxy );
358 getLogger().debug( "Trying " + path + " from " + repository.getName() + "..." );
360 boolean downloaded = true;
361 if ( force || !target.exists() )
363 wagon.get( path, temp );
367 downloaded = wagon.getIfNewer( path, temp, target.lastModified() );
372 success = checkChecksum( checksums, path, wagon, repositoryCachePath );
374 if ( tries > 1 && !success )
376 processRepositoryFailure( repository,
377 "Checksum failures occurred while downloading " + path, path,
384 // getIfNewer determined we were up to date
390 // temp won't exist if we called getIfNewer and it was older, but its still a successful return
393 moveTempToTarget( temp, target );
396 //try next repository
398 catch ( TransferFailedException e )
400 processRepositoryFailure( repository, e, path, policy );
402 catch ( AuthorizationException e )
404 processRepositoryFailure( repository, e, path, policy );
406 catch ( ResourceDoesNotExistException e )
408 // hard failure setting doesn't affect "not found".
409 getLogger().debug( "Artifact not found in repository: " + repository.getName() + ": " + e.getMessage() );
415 if ( wagon != null && checksums != null )
417 releaseChecksumListeners( wagon, checksums );
422 disconnectWagon( wagon );
427 private static boolean isOutOfDate( ArtifactRepositoryPolicy policy, File target )
429 return policy != null && policy.checkOutOfDate( new Date( target.lastModified() ) );
433 * Used to add checksum observers as transfer listeners to the wagonManager object
435 * @param wagon the wagonManager object to use the checksum with
436 * @return map of ChecksumObservers added into the wagonManager transfer listeners
438 private Map prepareChecksumListeners( Wagon wagon )
440 Map checksums = new LinkedHashMap();
443 ChecksumObserver checksum = new ChecksumObserver( "SHA-1" );
444 wagon.addTransferListener( checksum );
445 checksums.put( "sha1", checksum );
447 checksum = new ChecksumObserver( "MD5" );
448 wagon.addTransferListener( checksum );
449 checksums.put( "md5", checksum );
451 catch ( NoSuchAlgorithmException e )
453 getLogger().info( "An error occurred while preparing checksum observers", e );
458 private void releaseChecksumListeners( Wagon wagon, Map checksumMap )
460 for ( Iterator checksums = checksumMap.values().iterator(); checksums.hasNext(); )
462 ChecksumObserver listener = (ChecksumObserver) checksums.next();
463 wagon.removeTransferListener( listener );
467 private boolean connectToRepository( Wagon wagon, ProxiedArtifactRepository repository, ProxyInfo httpProxy )
469 boolean connected = false;
472 ArtifactRepository artifactRepository = repository.getRepository();
473 Repository wagonRepository = new Repository( artifactRepository.getId(), artifactRepository.getUrl() );
474 if ( repository.isUseNetworkProxy() && httpProxy != null )
476 wagon.connect( wagonRepository, httpProxy );
480 wagon.connect( wagonRepository );
484 catch ( ConnectionException e )
486 getLogger().info( "Could not connect to " + repository.getName() + ": " + e.getMessage() );
488 catch ( AuthenticationException e )
490 getLogger().info( "Could not connect to " + repository.getName() + ": " + e.getMessage() );
496 private boolean checkChecksum( Map checksumMap, String path, Wagon wagon, String repositoryCachePath )
497 throws ProxyException
499 releaseChecksumListeners( wagon, checksumMap );
501 boolean correctChecksum = false;
503 boolean allNotFound = true;
505 for ( Iterator i = checksumMap.keySet().iterator(); i.hasNext() && !correctChecksum; )
507 String checksumExt = (String) i.next();
508 ChecksumObserver checksum = (ChecksumObserver) checksumMap.get( checksumExt );
509 String checksumPath = path + "." + checksumExt;
510 File checksumFile = new File( repositoryCachePath, checksumPath );
512 File tempChecksumFile = new File( checksumFile.getAbsolutePath() + ".tmp" );
513 tempChecksumFile.deleteOnExit();
517 wagon.get( checksumPath, tempChecksumFile );
521 String remoteChecksum = DigestUtils.cleanChecksum( FileUtils.fileRead( tempChecksumFile ),
522 checksumExt.toUpperCase(),
523 path.substring( path.lastIndexOf( '/' ) ) );
525 String actualChecksum = checksum.getActualChecksum().toUpperCase();
526 remoteChecksum = remoteChecksum.toUpperCase();
528 if ( remoteChecksum.equals( actualChecksum ) )
530 moveTempToTarget( tempChecksumFile, checksumFile );
532 correctChecksum = true;
537 "The checksum '" + actualChecksum + "' did not match the remote value: " + remoteChecksum );
540 catch ( TransferFailedException e )
542 getLogger().warn( "An error occurred during the download of " + checksumPath + ": " + e.getMessage(),
544 // do nothing try the next checksum
548 catch ( ResourceDoesNotExistException e )
550 getLogger().debug( "The checksum did not exist: " + checksumPath, e );
551 // do nothing try the next checksum
552 // remove it if it is present locally in case there is an old incorrect one
553 if ( checksumFile.exists() )
555 checksumFile.delete();
558 catch ( AuthorizationException e )
560 getLogger().warn( "An error occurred during the download of " + checksumPath + ": " + e.getMessage(),
562 // do nothing try the next checksum
566 catch ( IOException e )
568 getLogger().warn( "An error occurred while reading the temporary checksum file.", e );
569 // do nothing try the next checksum
573 catch ( DigesterException e )
575 getLogger().warn( "The checksum was invalid: " + checksumPath + ": " + e.getMessage(), e );
576 // do nothing try the next checksum
582 tempChecksumFile.delete();
585 return correctChecksum || allNotFound;
589 * Used to move the temporary file to its real destination. This is patterned from the way WagonManager handles
590 * its downloaded files.
592 * @param temp The completed download file
593 * @param target The final location of the downloaded file
594 * @throws ProxyException when the temp file cannot replace the target file
596 private void moveTempToTarget( File temp, File target )
597 throws ProxyException
599 if ( target.exists() && !target.delete() )
601 throw new ProxyException( "Unable to overwrite existing target file: " + target.getAbsolutePath() );
604 if ( !temp.renameTo( target ) )
606 getLogger().warn( "Unable to rename tmp file to its final name... resorting to copy command." );
610 FileUtils.copyFile( temp, target );
612 catch ( IOException e )
614 throw new ProxyException( "Cannot copy tmp file to its final location", e );
624 * Used to disconnect the wagonManager from its repository
626 * @param wagon the connected wagonManager object
628 private void disconnectWagon( Wagon wagon )
634 catch ( ConnectionException e )
636 getLogger().error( "Problem disconnecting from wagonManager - ignoring: " + e.getMessage() );
640 private void processRepositoryFailure( ProxiedArtifactRepository repository, Throwable t, String path,
641 ArtifactRepositoryPolicy policy )
642 throws ProxyException
644 repository.addFailure( path, policy );
646 String message = t.getMessage();
647 if ( repository.isHardFail() )
649 repository.addFailure( path, policy );
650 throw new ProxyException(
651 "An error occurred in hardfailing repository " + repository.getName() + "...\n " + message, t );
654 getLogger().warn( "Skipping repository " + repository.getName() + ": " + message );
655 getLogger().debug( "Cause", t );
658 private void processRepositoryFailure( ProxiedArtifactRepository repository, String message, String path,
659 ArtifactRepositoryPolicy policy )
660 throws ProxyException
662 repository.addFailure( path, policy );
664 processCachedRepositoryFailure( repository, message );
667 private void processCachedRepositoryFailure( ProxiedArtifactRepository repository, String message )
668 throws ProxyException
670 if ( repository.isHardFail() )
672 throw new ProxyException(
673 "An error occurred in hardfailing repository " + repository.getName() + "...\n " + message );
676 getLogger().warn( "Skipping repository " + repository.getName() + ": " + message );