--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import com.google.common.collect.Lists;
+import org.apache.archiva.proxy.common.WagonFactory;
+import org.apache.archiva.proxy.common.WagonFactoryException;
+import org.apache.archiva.scheduler.ArchivaTaskScheduler;
+import org.apache.archiva.scheduler.repository.RepositoryTask;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.maven.archiva.configuration.ArchivaConfiguration;
+import org.apache.maven.archiva.configuration.ConfigurationNames;
+import org.apache.maven.archiva.configuration.NetworkProxyConfiguration;
+import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
+import org.apache.maven.archiva.model.ArtifactReference;
+import org.apache.maven.archiva.model.Keys;
+import org.apache.maven.archiva.model.RepositoryURL;
+import org.apache.maven.archiva.policies.DownloadErrorPolicy;
+import org.apache.maven.archiva.policies.DownloadPolicy;
+import org.apache.maven.archiva.policies.PolicyConfigurationException;
+import org.apache.maven.archiva.policies.PolicyViolationException;
+import org.apache.maven.archiva.policies.PostDownloadPolicy;
+import org.apache.maven.archiva.policies.PreDownloadPolicy;
+import org.apache.maven.archiva.policies.ProxyDownloadException;
+import org.apache.maven.archiva.policies.urlcache.UrlFailureCache;
+import org.apache.maven.archiva.repository.ManagedRepositoryContent;
+import org.apache.maven.archiva.repository.RemoteRepositoryContent;
+import org.apache.maven.archiva.repository.RepositoryContentFactory;
+import org.apache.maven.archiva.repository.RepositoryException;
+import org.apache.maven.archiva.repository.RepositoryNotFoundException;
+import org.apache.maven.archiva.repository.metadata.MetadataTools;
+import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
+import org.apache.maven.wagon.ConnectionException;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.apache.maven.wagon.Wagon;
+import org.apache.maven.wagon.WagonException;
+import org.apache.maven.wagon.authentication.AuthenticationException;
+import org.apache.maven.wagon.authentication.AuthenticationInfo;
+import org.apache.maven.wagon.proxy.ProxyInfo;
+import org.apache.maven.wagon.repository.Repository;
+import org.codehaus.plexus.registry.Registry;
+import org.codehaus.plexus.registry.RegistryListener;
+import org.codehaus.plexus.taskqueue.TaskQueueException;
+import org.codehaus.plexus.util.SelectorUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Properties;
+
+/**
+ * DefaultRepositoryProxyConnectors
+ *
+ * @version $Id$
+ * @todo exception handling needs work - "not modified" is not really an exceptional case, and it has more layers than
+ * your average brown onion
+ */
+@Service( "repositoryProxyConnectors#default" )
+public class DefaultRepositoryProxyConnectors
+ implements RepositoryProxyConnectors, RegistryListener
+{
+ private Logger log = LoggerFactory.getLogger( DefaultRepositoryProxyConnectors.class );
+
+ /**
+ *
+ */
+ @Inject
+ @Named( value = "archivaConfiguration#default" )
+ private ArchivaConfiguration archivaConfiguration;
+
+ /**
+ *
+ */
+ @Inject
+ @Named( value = "repositoryContentFactory#default" )
+ private RepositoryContentFactory repositoryFactory;
+
+ /**
+ *
+ */
+ @Inject
+ @Named( value = "metadataTools#default" )
+ private MetadataTools metadataTools;
+
+ /**
+ *
+ */
+ @Inject
+ private Map<String, PreDownloadPolicy> preDownloadPolicies;
+
+ /**
+ *
+ */
+ @Inject
+ private Map<String, PostDownloadPolicy> postDownloadPolicies;
+
+ /**
+ *
+ */
+ @Inject
+ private Map<String, DownloadErrorPolicy> downloadErrorPolicies;
+
+ /**
+ *
+ */
+ @Inject
+ private UrlFailureCache urlFailureCache;
+
+ private Map<String, List<ProxyConnector>> proxyConnectorMap = new HashMap<String, List<ProxyConnector>>();
+
+ private Map<String, ProxyInfo> networkProxyMap = new HashMap<String, ProxyInfo>();
+
+ /**
+ *
+ */
+ @Inject
+ private WagonFactory wagonFactory;
+
+ /**
+ *
+ */
+ @Inject
+ @Named( value = "archivaTaskScheduler#repository" )
+ private ArchivaTaskScheduler scheduler;
+
+ @PostConstruct
+ public void initialize()
+ {
+ initConnectorsAndNetworkProxies();
+ archivaConfiguration.addChangeListener( this );
+ //this.postDownloadPolicies = applicationContext.getBeansOfType( PostDownloadPolicy.class );
+ //his.preDownloadPolicies = applicationContext.getBeansOfType( PreDownloadPolicy.class );
+ //this.downloadErrorPolicies = applicationContext.getBeansOfType( DownloadErrorPolicy.class );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ private void initConnectorsAndNetworkProxies()
+ {
+ synchronized ( this.proxyConnectorMap )
+ {
+ ProxyConnectorOrderComparator proxyOrderSorter = new ProxyConnectorOrderComparator();
+ this.proxyConnectorMap.clear();
+
+ List<ProxyConnectorConfiguration> proxyConfigs =
+ archivaConfiguration.getConfiguration().getProxyConnectors();
+ for ( ProxyConnectorConfiguration proxyConfig : proxyConfigs )
+ {
+ String key = proxyConfig.getSourceRepoId();
+
+ try
+ {
+ // Create connector object.
+ ProxyConnector connector = new ProxyConnector();
+
+ connector.setSourceRepository(
+ repositoryFactory.getManagedRepositoryContent( proxyConfig.getSourceRepoId() ) );
+ connector.setTargetRepository(
+ repositoryFactory.getRemoteRepositoryContent( proxyConfig.getTargetRepoId() ) );
+
+ connector.setProxyId( proxyConfig.getProxyId() );
+ connector.setPolicies( proxyConfig.getPolicies() );
+ connector.setOrder( proxyConfig.getOrder() );
+ connector.setDisabled( proxyConfig.isDisabled() );
+
+ // Copy any blacklist patterns.
+ List<String> blacklist = new ArrayList<String>();
+ if ( CollectionUtils.isNotEmpty( proxyConfig.getBlackListPatterns() ) )
+ {
+ blacklist.addAll( proxyConfig.getBlackListPatterns() );
+ }
+ connector.setBlacklist( blacklist );
+
+ // Copy any whitelist patterns.
+ List<String> whitelist = new ArrayList<String>();
+ if ( CollectionUtils.isNotEmpty( proxyConfig.getWhiteListPatterns() ) )
+ {
+ whitelist.addAll( proxyConfig.getWhiteListPatterns() );
+ }
+ connector.setWhitelist( whitelist );
+
+ // Get other connectors
+ List<ProxyConnector> connectors = this.proxyConnectorMap.get( key );
+ if ( connectors == null )
+ {
+ // Create if we are the first.
+ connectors = new ArrayList<ProxyConnector>();
+ }
+
+ // Add the connector.
+ connectors.add( connector );
+
+ // Ensure the list is sorted.
+ Collections.sort( connectors, proxyOrderSorter );
+
+ // Set the key to the list of connectors.
+ this.proxyConnectorMap.put( key, connectors );
+ }
+ catch ( RepositoryNotFoundException e )
+ {
+ log.warn( "Unable to use proxy connector: " + e.getMessage(), e );
+ }
+ catch ( RepositoryException e )
+ {
+ log.warn( "Unable to use proxy connector: " + e.getMessage(), e );
+ }
+ }
+
+ }
+
+ synchronized ( this.networkProxyMap )
+ {
+ this.networkProxyMap.clear();
+
+ List<NetworkProxyConfiguration> networkProxies =
+ archivaConfiguration.getConfiguration().getNetworkProxies();
+ for ( NetworkProxyConfiguration networkProxyConfig : networkProxies )
+ {
+ String key = networkProxyConfig.getId();
+
+ ProxyInfo proxy = new ProxyInfo();
+
+ proxy.setType( networkProxyConfig.getProtocol() );
+ proxy.setHost( networkProxyConfig.getHost() );
+ proxy.setPort( networkProxyConfig.getPort() );
+ proxy.setUserName( networkProxyConfig.getUsername() );
+ proxy.setPassword( networkProxyConfig.getPassword() );
+
+ this.networkProxyMap.put( key, proxy );
+ }
+ }
+ }
+
+ public File fetchFromProxies( ManagedRepositoryContent repository, ArtifactReference artifact )
+ throws ProxyDownloadException
+ {
+ File localFile = toLocalFile( repository, artifact );
+
+ Properties requestProperties = new Properties();
+ requestProperties.setProperty( "filetype", "artifact" );
+ requestProperties.setProperty( "version", artifact.getVersion() );
+ requestProperties.setProperty( "managedRepositoryId", repository.getId() );
+
+ List<ProxyConnector> connectors = getProxyConnectors( repository );
+ Map<String, Exception> previousExceptions = new LinkedHashMap<String, Exception>();
+ for ( ProxyConnector connector : connectors )
+ {
+ if ( connector.isDisabled() )
+ {
+ continue;
+ }
+
+ RemoteRepositoryContent targetRepository = connector.getTargetRepository();
+ requestProperties.setProperty( "remoteRepositoryId", targetRepository.getId() );
+
+ String targetPath = targetRepository.toPath( artifact );
+
+ try
+ {
+ File downloadedFile =
+ transferFile( connector, targetRepository, targetPath, repository, localFile, requestProperties,
+ true );
+
+ if ( fileExists( downloadedFile ) )
+ {
+ log.debug( "Successfully transferred: {}", downloadedFile.getAbsolutePath() );
+ return downloadedFile;
+ }
+ }
+ catch ( NotFoundException e )
+ {
+ log.debug( "Artifact {} not found on repository \"{}\".", Keys.toKey( artifact ),
+ targetRepository.getRepository().getId() );
+ }
+ catch ( NotModifiedException e )
+ {
+ log.debug( "Artifact {} not updated on repository \"{}\".", Keys.toKey( artifact ),
+ targetRepository.getRepository().getId() );
+ }
+ catch ( ProxyException e )
+ {
+ validatePolicies( this.downloadErrorPolicies, connector.getPolicies(), requestProperties, artifact,
+ targetRepository, localFile, e, previousExceptions );
+ }
+ }
+
+ if ( !previousExceptions.isEmpty() )
+ {
+ throw new ProxyDownloadException( "Failures occurred downloading from some remote repositories",
+ previousExceptions );
+ }
+
+ log.debug( "Exhausted all target repositories, artifact {} not found.", Keys.toKey( artifact ) );
+
+ return null;
+ }
+
+ public File fetchFromProxies( ManagedRepositoryContent repository, String path )
+ {
+ File localFile = new File( repository.getRepoRoot(), path );
+
+ // no update policies for these paths
+ if ( localFile.exists() )
+ {
+ return null;
+ }
+
+ Properties requestProperties = new Properties();
+ requestProperties.setProperty( "filetype", "resource" );
+ requestProperties.setProperty( "managedRepositoryId", repository.getId() );
+
+ List<ProxyConnector> connectors = getProxyConnectors( repository );
+ for ( ProxyConnector connector : connectors )
+ {
+ if ( connector.isDisabled() )
+ {
+ continue;
+ }
+
+ RemoteRepositoryContent targetRepository = connector.getTargetRepository();
+ requestProperties.setProperty( "remoteRepositoryId", targetRepository.getId() );
+
+ String targetPath = path;
+
+ try
+ {
+ File downloadedFile =
+ transferFile( connector, targetRepository, targetPath, repository, localFile, requestProperties,
+ false );
+
+ if ( fileExists( downloadedFile ) )
+ {
+ log.debug( "Successfully transferred: {}", downloadedFile.getAbsolutePath() );
+ return downloadedFile;
+ }
+ }
+ catch ( NotFoundException e )
+ {
+ log.debug( "Resource {} not found on repository \"{}\".", path,
+ targetRepository.getRepository().getId() );
+ }
+ catch ( NotModifiedException e )
+ {
+ log.debug( "Resource {} not updated on repository \"{}\".", path,
+ targetRepository.getRepository().getId() );
+ }
+ catch ( ProxyException e )
+ {
+ log.warn(
+ "Transfer error from repository \"" + targetRepository.getRepository().getId() + "\" for resource "
+ + path + ", continuing to next repository. Error message: " + e.getMessage() );
+ log.debug( "Full stack trace", e );
+ }
+ }
+
+ log.debug( "Exhausted all target repositories, resource {} not found.", path );
+
+ return null;
+ }
+
+ public File fetchMetatadaFromProxies( ManagedRepositoryContent repository, String logicalPath )
+ {
+ File localFile = new File( repository.getRepoRoot(), logicalPath );
+
+ Properties requestProperties = new Properties();
+ requestProperties.setProperty( "filetype", "metadata" );
+ boolean metadataNeedsUpdating = false;
+ long originalTimestamp = getLastModified( localFile );
+
+ List<ProxyConnector> connectors = getProxyConnectors( repository );
+ for ( ProxyConnector connector : connectors )
+ {
+ if ( connector.isDisabled() )
+ {
+ continue;
+ }
+
+ RemoteRepositoryContent targetRepository = connector.getTargetRepository();
+
+ File localRepoFile = toLocalRepoFile( repository, targetRepository, logicalPath );
+ long originalMetadataTimestamp = getLastModified( localRepoFile );
+
+ try
+ {
+ transferFile( connector, targetRepository, logicalPath, repository, localRepoFile, requestProperties,
+ true );
+
+ if ( hasBeenUpdated( localRepoFile, originalMetadataTimestamp ) )
+ {
+ metadataNeedsUpdating = true;
+ }
+ }
+ catch ( NotFoundException e )
+ {
+ if ( log.isDebugEnabled() )
+ {
+ log.debug( "Metadata {} not found on remote repository \"{}\".",
+ Lists.<Object>newArrayList( logicalPath, targetRepository.getRepository().getId() ), e );
+ }
+ }
+ catch ( NotModifiedException e )
+ {
+ if ( log.isDebugEnabled() )
+ {
+ log.debug( "Metadata {} not updated on remote repository \"{}\".",
+ Lists.<Object>newArrayList( logicalPath, targetRepository.getRepository().getId() ), e );
+ }
+ }
+ catch ( ProxyException e )
+ {
+ log.warn( "Transfer error from repository \"" + targetRepository.getRepository().getId()
+ + "\" for versioned Metadata " + logicalPath
+ + ", continuing to next repository. Error message: " + e.getMessage() );
+ log.debug( "Full stack trace", e );
+ }
+ }
+
+ if ( hasBeenUpdated( localFile, originalTimestamp ) )
+ {
+ metadataNeedsUpdating = true;
+ }
+
+ if ( metadataNeedsUpdating || !localFile.exists() )
+ {
+ try
+ {
+ metadataTools.updateMetadata( repository, logicalPath );
+ }
+ catch ( RepositoryMetadataException e )
+ {
+ log.warn( "Unable to update metadata " + localFile.getAbsolutePath() + ": " + e.getMessage(), e );
+ }
+ }
+
+ if ( fileExists( localFile ) )
+ {
+ return localFile;
+ }
+
+ return null;
+ }
+
+ private long getLastModified( File file )
+ {
+ if ( !file.exists() || !file.isFile() )
+ {
+ return 0;
+ }
+
+ return file.lastModified();
+ }
+
+ private boolean hasBeenUpdated( File file, long originalLastModified )
+ {
+ if ( !file.exists() || !file.isFile() )
+ {
+ return false;
+ }
+
+ long currentLastModified = getLastModified( file );
+ return ( currentLastModified > originalLastModified );
+ }
+
+ private File toLocalRepoFile( ManagedRepositoryContent repository, RemoteRepositoryContent targetRepository,
+ String targetPath )
+ {
+ String repoPath = metadataTools.getRepositorySpecificName( targetRepository, targetPath );
+ return new File( repository.getRepoRoot(), repoPath );
+ }
+
+ /**
+ * Test if the provided ManagedRepositoryContent has any proxies configured for it.
+ */
+ public boolean hasProxies( ManagedRepositoryContent repository )
+ {
+ synchronized ( this.proxyConnectorMap )
+ {
+ return this.proxyConnectorMap.containsKey( repository.getId() );
+ }
+ }
+
+ private File toLocalFile( ManagedRepositoryContent repository, ArtifactReference artifact )
+ {
+ return repository.toFile( artifact );
+ }
+
+ /**
+ * Simple method to test if the file exists on the local disk.
+ *
+ * @param file the file to test. (may be null)
+ * @return true if file exists. false if the file param is null, doesn't exist, or is not of type File.
+ */
+ private boolean fileExists( File file )
+ {
+ if ( file == null )
+ {
+ return false;
+ }
+
+ if ( !file.exists() )
+ {
+ return false;
+ }
+
+ if ( !file.isFile() )
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Perform the transfer of the file.
+ *
+ * @param connector the connector configuration to use.
+ * @param remoteRepository the remote repository get the resource from.
+ * @param remotePath the path in the remote repository to the resource to get.
+ * @param repository the managed repository that will hold the file
+ * @param resource the local file to place the downloaded resource into
+ * @param requestProperties the request properties to utilize for policy handling.
+ * @param executeConsumers whether to execute the consumers after proxying
+ * @return the local file that was downloaded, or null if not downloaded.
+ * @throws NotFoundException if the file was not found on the remote repository.
+ * @throws NotModifiedException if the localFile was present, and the resource was present on remote repository, but
+ * the remote resource is not newer than the local File.
+ * @throws ProxyException if transfer was unsuccessful.
+ */
+ private File transferFile( ProxyConnector connector, RemoteRepositoryContent remoteRepository, String remotePath,
+ ManagedRepositoryContent repository, File resource, Properties requestProperties,
+ boolean executeConsumers )
+ throws ProxyException, NotModifiedException
+ {
+ String url = remoteRepository.getURL().getUrl();
+ if ( !url.endsWith( "/" ) )
+ {
+ url = url + "/";
+ }
+ url = url + remotePath;
+ requestProperties.setProperty( "url", url );
+
+ // Is a whitelist defined?
+ if ( CollectionUtils.isNotEmpty( connector.getWhitelist() ) )
+ {
+ // Path must belong to whitelist.
+ if ( !matchesPattern( remotePath, connector.getWhitelist() ) )
+ {
+ log.debug( "Path [{}] is not part of defined whitelist (skipping transfer from repository [{}]).",
+ remotePath, remoteRepository.getRepository().getName() );
+ return null;
+ }
+ }
+
+ // Is target path part of blacklist?
+ if ( matchesPattern( remotePath, connector.getBlacklist() ) )
+ {
+ log.debug( "Path [{}] is part of blacklist (skipping transfer from repository [{}]).", remotePath,
+ remoteRepository.getRepository().getName() );
+ return null;
+ }
+
+ // Handle pre-download policy
+ try
+ {
+ validatePolicies( this.preDownloadPolicies, connector.getPolicies(), requestProperties, resource );
+ }
+ catch ( PolicyViolationException e )
+ {
+ String emsg = "Transfer not attempted on " + url + " : " + e.getMessage();
+ if ( fileExists( resource ) )
+ {
+ log.debug( "{} : using already present local file.", emsg );
+ return resource;
+ }
+
+ log.debug( emsg );
+ return null;
+ }
+
+ File tmpMd5 = null;
+ File tmpSha1 = null;
+ File tmpResource = null;
+
+ File workingDirectory = createWorkingDirectory( repository );
+ try
+ {
+ Wagon wagon = null;
+ try
+ {
+ RepositoryURL repoUrl = remoteRepository.getURL();
+ String protocol = repoUrl.getProtocol();
+ wagon = wagonFactory.getWagon( "wagon#" + protocol );
+ if ( wagon == null )
+ {
+ throw new ProxyException( "Unsupported target repository protocol: " + protocol );
+ }
+
+ boolean connected = connectToRepository( connector, wagon, remoteRepository );
+ if ( connected )
+ {
+ tmpResource = new File( workingDirectory, resource.getName() );
+ transferSimpleFile( wagon, remoteRepository, remotePath, repository, resource, tmpResource );
+
+ // TODO: these should be used to validate the download based on the policies, not always downloaded
+ // to
+ // save on connections since md5 is rarely used
+ tmpSha1 =
+ transferChecksum( wagon, remoteRepository, remotePath, repository, resource, workingDirectory,
+ ".sha1" );
+ tmpMd5 =
+ transferChecksum( wagon, remoteRepository, remotePath, repository, resource, workingDirectory,
+ ".md5" );
+ }
+ }
+ catch ( NotFoundException e )
+ {
+ urlFailureCache.cacheFailure( url );
+ throw e;
+ }
+ catch ( NotModifiedException e )
+ {
+ // Do not cache url here.
+ throw e;
+ }
+ catch ( ProxyException e )
+ {
+ urlFailureCache.cacheFailure( url );
+ throw e;
+ }
+ catch ( WagonFactoryException e )
+ {
+ throw new ProxyException( e.getMessage(), e );
+ }
+ finally
+ {
+ if ( wagon != null )
+ {
+ try
+ {
+ wagon.disconnect();
+ }
+ catch ( ConnectionException e )
+ {
+ log.warn( "Unable to disconnect wagon.", e );
+ }
+ }
+ }
+
+ // Handle post-download policies.
+ try
+ {
+ validatePolicies( this.postDownloadPolicies, connector.getPolicies(), requestProperties, tmpResource );
+ }
+ catch ( PolicyViolationException e )
+ {
+ log.warn( "Transfer invalidated from {} : {}", url, e.getMessage() );
+ executeConsumers = false;
+ if ( !fileExists( tmpResource ) )
+ {
+ resource = null;
+ }
+ }
+
+ if ( resource != null )
+ {
+ synchronized ( resource.getAbsolutePath().intern() )
+ {
+ File directory = resource.getParentFile();
+ moveFileIfExists( tmpMd5, directory );
+ moveFileIfExists( tmpSha1, directory );
+ moveFileIfExists( tmpResource, directory );
+ }
+ }
+ }
+ finally
+ {
+ FileUtils.deleteQuietly( workingDirectory );
+ }
+
+ if ( executeConsumers )
+ {
+ // Just-in-time update of the index and database by executing the consumers for this artifact
+ //consumers.executeConsumers( connector.getSourceRepository().getRepository(), resource );
+ queueRepositoryTask( connector.getSourceRepository().getRepository().getId(), resource );
+ }
+
+ return resource;
+ }
+
+ private void queueRepositoryTask( String repositoryId, File localFile )
+ {
+ RepositoryTask task = new RepositoryTask();
+ task.setRepositoryId( repositoryId );
+ task.setResourceFile( localFile );
+ task.setUpdateRelatedArtifacts( true );
+ task.setScanAll( true );
+
+ try
+ {
+ scheduler.queueTask( task );
+ }
+ catch ( TaskQueueException e )
+ {
+ log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
+ + "']." );
+ }
+ }
+
+ /**
+ * Moves the file into repository location if it exists
+ *
+ * @param fileToMove this could be either the main artifact, sha1 or md5 checksum file.
+ * @param directory directory to write files to
+ */
+ private void moveFileIfExists( File fileToMove, File directory )
+ throws ProxyException
+ {
+ if ( fileToMove != null && fileToMove.exists() )
+ {
+ File newLocation = new File( directory, fileToMove.getName() );
+ moveTempToTarget( fileToMove, newLocation );
+ }
+ }
+
+ /**
+ * <p>
+ * Quietly transfer the checksum file from the remote repository to the local file.
+ * </p>
+ *
+ * @param wagon the wagon instance (should already be connected) to use.
+ * @param remoteRepository the remote repository to transfer from.
+ * @param remotePath the remote path to the resource to get.
+ * @param repository the managed repository that will hold the file
+ * @param resource the local file that should contain the downloaded contents
+ * @param tmpDirectory the temporary directory to download to
+ * @param ext the type of checksum to transfer (example: ".md5" or ".sha1")
+ * @throws ProxyException if copying the downloaded file into place did not succeed.
+ */
+ private File transferChecksum( Wagon wagon, RemoteRepositoryContent remoteRepository, String remotePath,
+ ManagedRepositoryContent repository, File resource, File tmpDirectory, String ext )
+ throws ProxyException
+ {
+ String url = remoteRepository.getURL().getUrl() + remotePath + ext;
+
+ // Transfer checksum does not use the policy.
+ if ( urlFailureCache.hasFailedBefore( url ) )
+ {
+ return null;
+ }
+
+ File destFile = new File( tmpDirectory, resource.getName() + ext );
+
+ try
+ {
+ transferSimpleFile( wagon, remoteRepository, remotePath + ext, repository, resource, destFile );
+ log.debug( "Checksum {} Downloaded: {} to move to {}", Arrays.asList( url, destFile, resource ).toArray() );
+ }
+ catch ( NotFoundException e )
+ {
+ urlFailureCache.cacheFailure( url );
+ log.debug( "Transfer failed, checksum not found: {}", url );
+ // Consume it, do not pass this on.
+ }
+ catch ( NotModifiedException e )
+ {
+ log.debug( "Transfer skipped, checksum not modified: {}", url );
+ // Consume it, do not pass this on.
+ }
+ catch ( ProxyException e )
+ {
+ urlFailureCache.cacheFailure( url );
+ log.warn( "Transfer failed on checksum: " + url + " : " + e.getMessage(), e );
+ // Critical issue, pass it on.
+ throw e;
+ }
+ return destFile;
+ }
+
+ /**
+ * Perform the transfer of the remote file to the local file specified.
+ *
+ * @param wagon the wagon instance to use.
+ * @param remoteRepository the remote repository to use
+ * @param remotePath the remote path to attempt to get
+ * @param repository the managed repository that will hold the file
+ * @param origFile the local file to save to
+ * @return The local file that was transfered.
+ * @throws ProxyException if there was a problem moving the downloaded file into place.
+ * @throws WagonException if there was a problem tranfering the file.
+ */
+ private void transferSimpleFile( Wagon wagon, RemoteRepositoryContent remoteRepository, String remotePath,
+ ManagedRepositoryContent repository, File origFile, File destFile )
+ throws ProxyException
+ {
+ assert ( remotePath != null );
+
+ // Transfer the file.
+ try
+ {
+ boolean success = false;
+
+ if ( !origFile.exists() )
+ {
+ log.debug( "Retrieving {} from {}", remotePath, remoteRepository.getRepository().getName() );
+ wagon.get( remotePath, destFile );
+ success = true;
+
+ // You wouldn't get here on failure, a WagonException would have been thrown.
+ log.debug( "Downloaded successfully." );
+ }
+ else
+ {
+ log.debug( "Retrieving {} from {} if updated", remotePath, remoteRepository.getRepository().getName() );
+ success = wagon.getIfNewer( remotePath, destFile, origFile.lastModified() );
+ if ( !success )
+ {
+ throw new NotModifiedException(
+ "Not downloaded, as local file is newer than remote side: " + origFile.getAbsolutePath() );
+ }
+
+ if ( destFile.exists() )
+ {
+ log.debug( "Downloaded successfully." );
+ }
+ }
+ }
+ catch ( ResourceDoesNotExistException e )
+ {
+ throw new NotFoundException(
+ "Resource [" + remoteRepository.getURL() + "/" + remotePath + "] does not exist: " + e.getMessage(),
+ e );
+ }
+ catch ( WagonException e )
+ {
+ // TODO: shouldn't have to drill into the cause, but TransferFailedException is often not descriptive enough
+
+ String msg =
+ "Download failure on resource [" + remoteRepository.getURL() + "/" + remotePath + "]:" + e.getMessage();
+ if ( e.getCause() != null )
+ {
+ msg += " (cause: " + e.getCause() + ")";
+ }
+ throw new ProxyException( msg, e );
+ }
+ }
+
+ /**
+ * Apply the policies.
+ *
+ * @param policies the map of policies to execute. (Map of String policy keys, to {@link DownloadPolicy} objects)
+ * @param settings the map of settings for the policies to execute. (Map of String policy keys, to String policy
+ * setting)
+ * @param request the request properties (utilized by the {@link DownloadPolicy#applyPolicy(String, Properties, File)}
+ * )
+ * @param localFile the local file (utilized by the {@link DownloadPolicy#applyPolicy(String, Properties, File)})
+ */
+ private void validatePolicies( Map<String, ? extends DownloadPolicy> policies, Map<String, String> settings,
+ Properties request, File localFile )
+ throws PolicyViolationException
+ {
+ for ( Entry<String, ? extends DownloadPolicy> entry : policies.entrySet() )
+ {
+ // olamy with spring rolehint is now downloadPolicy#hint
+ // so substring after last # to get the hint as with plexus
+ String key = StringUtils.substringAfterLast( entry.getKey(), "#" );
+ DownloadPolicy policy = entry.getValue();
+ String defaultSetting = policy.getDefaultOption();
+
+ String setting = StringUtils.defaultString( settings.get( key ), defaultSetting );
+
+ log.debug( "Applying [{}] policy with [{}]", key, setting );
+ try
+ {
+ policy.applyPolicy( setting, request, localFile );
+ }
+ catch ( PolicyConfigurationException e )
+ {
+ log.error( e.getMessage(), e );
+ }
+ }
+ }
+
+ private void validatePolicies( Map<String, DownloadErrorPolicy> policies, Map<String, String> settings,
+ Properties request, ArtifactReference artifact, RemoteRepositoryContent content,
+ File localFile, ProxyException exception, Map<String, Exception> previousExceptions )
+ throws ProxyDownloadException
+ {
+ boolean process = true;
+ for ( Entry<String, ? extends DownloadErrorPolicy> entry : policies.entrySet() )
+ {
+
+ // olamy with spring rolehint is now downloadPolicy#hint
+ // so substring after last # to get the hint as with plexus
+ String key = StringUtils.substringAfterLast( entry.getKey(), "#" );
+ DownloadErrorPolicy policy = entry.getValue();
+ String defaultSetting = policy.getDefaultOption();
+ String setting = StringUtils.defaultString( settings.get( key ), defaultSetting );
+
+ log.debug( "Applying [{}] policy with [{}]", key, setting );
+ try
+ {
+ // all policies must approve the exception, any can cancel
+ process = policy.applyPolicy( setting, request, localFile, exception, previousExceptions );
+ if ( !process )
+ {
+ break;
+ }
+ }
+ catch ( PolicyConfigurationException e )
+ {
+ log.error( e.getMessage(), e );
+ }
+ }
+
+ if ( process )
+ {
+ // if the exception was queued, don't throw it
+ if ( !previousExceptions.containsKey( content.getId() ) )
+ {
+ throw new ProxyDownloadException(
+ "An error occurred in downloading from the remote repository, and the policy is to fail immediately",
+ content.getId(), exception );
+ }
+ }
+ else
+ {
+ // if the exception was queued, but cancelled, remove it
+ previousExceptions.remove( content.getId() );
+ }
+
+ log.warn( "Transfer error from repository \"" + content.getRepository().getId() + "\" for artifact "
+ + Keys.toKey( artifact ) + ", continuing to next repository. Error message: "
+ + exception.getMessage() );
+ log.debug( "Full stack trace", exception );
+ }
+
+ /**
+ * Creates a working directory in the repository root for this request
+ *
+ * @param repository
+ * @return file location of working directory
+ * @throws IOException
+ */
+ private File createWorkingDirectory( ManagedRepositoryContent repository )
+ {
+ // TODO: This is ugly - lets actually clean this up when we get the new repository api
+ try
+ {
+ File tmpDir = File.createTempFile( ".workingdirectory", null, new File( repository.getRepoRoot() ) );
+ tmpDir.delete();
+ tmpDir.mkdirs();
+ return tmpDir;
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( "Could not create working directory for this request", e );
+ }
+ }
+
+ /**
+ * Used to move the temporary file to its real destination. This is patterned from the way WagonManager handles its
+ * downloaded files.
+ *
+ * @param temp The completed download file
+ * @param target The final location of the downloaded file
+ * @throws ProxyException when the temp file cannot replace the target file
+ */
+ private void moveTempToTarget( File temp, File target )
+ throws ProxyException
+ {
+ if ( target.exists() && !target.delete() )
+ {
+ throw new ProxyException( "Unable to overwrite existing target file: " + target.getAbsolutePath() );
+ }
+
+ target.getParentFile().mkdirs();
+ if ( !temp.renameTo( target ) )
+ {
+ log.warn( "Unable to rename tmp file to its final name... resorting to copy command." );
+
+ try
+ {
+ FileUtils.copyFile( temp, target );
+ }
+ catch ( IOException e )
+ {
+ if ( target.exists() )
+ {
+ log.debug( "Tried to copy file {} to {} but file with this name already exists.", temp.getName(),
+ target.getAbsolutePath() );
+ }
+ else
+ {
+ throw new ProxyException(
+ "Cannot copy tmp file " + temp.getAbsolutePath() + " to its final location", e );
+ }
+ }
+ finally
+ {
+ FileUtils.deleteQuietly( temp );
+ }
+ }
+ }
+
+ /**
+ * Using wagon, connect to the remote repository.
+ *
+ * @param connector the connector configuration to utilize (for obtaining network proxy configuration from)
+ * @param wagon the wagon instance to establish the connection on.
+ * @param remoteRepository the remote repository to connect to.
+ * @return true if the connection was successful. false if not connected.
+ */
+ private boolean connectToRepository( ProxyConnector connector, Wagon wagon,
+ RemoteRepositoryContent remoteRepository )
+ {
+ boolean connected = false;
+
+ final ProxyInfo networkProxy;
+ synchronized ( this.networkProxyMap )
+ {
+ networkProxy = (ProxyInfo) this.networkProxyMap.get( connector.getProxyId() );
+ }
+
+ if ( log.isDebugEnabled() )
+ {
+ if ( networkProxy != null )
+ {
+ // TODO: move to proxyInfo.toString()
+ String msg = "Using network proxy " + networkProxy.getHost() + ":" + networkProxy.getPort()
+ + " to connect to remote repository " + remoteRepository.getURL();
+ if ( networkProxy.getNonProxyHosts() != null )
+ {
+ msg += "; excluding hosts: " + networkProxy.getNonProxyHosts();
+ }
+ if ( StringUtils.isNotBlank( networkProxy.getUserName() ) )
+ {
+ msg += "; as user: " + networkProxy.getUserName();
+ }
+ log.debug( msg );
+ }
+ }
+
+ AuthenticationInfo authInfo = null;
+ String username = remoteRepository.getRepository().getUserName();
+ String password = remoteRepository.getRepository().getPassword();
+
+ if ( StringUtils.isNotBlank( username ) && StringUtils.isNotBlank( password ) )
+ {
+ log.debug( "Using username {} to connect to remote repository {}", username, remoteRepository.getURL() );
+ authInfo = new AuthenticationInfo();
+ authInfo.setUserName( username );
+ authInfo.setPassword( password );
+ }
+
+ // Convert seconds to milliseconds
+ int timeoutInMilliseconds = remoteRepository.getRepository().getTimeout() * 1000;
+
+ // Set timeout
+ wagon.setTimeout( timeoutInMilliseconds );
+
+ try
+ {
+ Repository wagonRepository =
+ new Repository( remoteRepository.getId(), remoteRepository.getURL().toString() );
+ wagon.connect( wagonRepository, authInfo, networkProxy );
+ connected = true;
+ }
+ catch ( ConnectionException e )
+ {
+ log.warn( "Could not connect to " + remoteRepository.getRepository().getName() + ": " + e.getMessage() );
+ connected = false;
+ }
+ catch ( AuthenticationException e )
+ {
+ log.warn( "Could not connect to " + remoteRepository.getRepository().getName() + ": " + e.getMessage() );
+ connected = false;
+ }
+
+ return connected;
+ }
+
+ /**
+ * Tests whitelist and blacklist patterns against path.
+ *
+ * @param path the path to test.
+ * @param patterns the list of patterns to check.
+ * @return true if the path matches at least 1 pattern in the provided patterns list.
+ */
+ private boolean matchesPattern( String path, List<String> patterns )
+ {
+ if ( CollectionUtils.isEmpty( patterns ) )
+ {
+ return false;
+ }
+
+ if ( !path.startsWith( "/" ) )
+ {
+ path = "/" + path;
+ }
+
+ for ( String pattern : patterns )
+ {
+ if ( !pattern.startsWith( "/" ) )
+ {
+ pattern = "/" + pattern;
+ }
+
+ if ( SelectorUtils.matchPath( pattern, path, false ) )
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * TODO: Ensure that list is correctly ordered based on configuration. See MRM-477
+ */
+ public List<ProxyConnector> getProxyConnectors( ManagedRepositoryContent repository )
+ {
+ synchronized ( this.proxyConnectorMap )
+ {
+ List<ProxyConnector> ret = (List<ProxyConnector>) this.proxyConnectorMap.get( repository.getId() );
+ if ( ret == null )
+ {
+ return Collections.emptyList();
+ }
+
+ Collections.sort( ret, ProxyConnectorOrderComparator.getInstance() );
+ return ret;
+ }
+ }
+
+ public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue )
+ {
+ if ( ConfigurationNames.isNetworkProxy( propertyName )
+ || ConfigurationNames.isManagedRepositories( propertyName )
+ || ConfigurationNames.isRemoteRepositories( propertyName ) || ConfigurationNames.isProxyConnector(
+ propertyName ) )
+ {
+ initConnectorsAndNetworkProxies();
+ }
+ }
+
+ public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue )
+ {
+ /* do nothing */
+ }
+
+ public ArchivaConfiguration getArchivaConfiguration()
+ {
+ return archivaConfiguration;
+ }
+
+ public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
+ {
+ this.archivaConfiguration = archivaConfiguration;
+ }
+
+ public RepositoryContentFactory getRepositoryFactory()
+ {
+ return repositoryFactory;
+ }
+
+ public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
+ {
+ this.repositoryFactory = repositoryFactory;
+ }
+
+ public MetadataTools getMetadataTools()
+ {
+ return metadataTools;
+ }
+
+ public void setMetadataTools( MetadataTools metadataTools )
+ {
+ this.metadataTools = metadataTools;
+ }
+
+ public UrlFailureCache getUrlFailureCache()
+ {
+ return urlFailureCache;
+ }
+
+ public void setUrlFailureCache( UrlFailureCache urlFailureCache )
+ {
+ this.urlFailureCache = urlFailureCache;
+ }
+
+ public WagonFactory getWagonFactory()
+ {
+ return wagonFactory;
+ }
+
+ public void setWagonFactory( WagonFactory wagonFactory )
+ {
+ this.wagonFactory = wagonFactory;
+ }
+
+ public Map<String, PreDownloadPolicy> getPreDownloadPolicies()
+ {
+ return preDownloadPolicies;
+ }
+
+ public void setPreDownloadPolicies( Map<String, PreDownloadPolicy> preDownloadPolicies )
+ {
+ this.preDownloadPolicies = preDownloadPolicies;
+ }
+
+ public Map<String, PostDownloadPolicy> getPostDownloadPolicies()
+ {
+ return postDownloadPolicies;
+ }
+
+ public void setPostDownloadPolicies( Map<String, PostDownloadPolicy> postDownloadPolicies )
+ {
+ this.postDownloadPolicies = postDownloadPolicies;
+ }
+
+ public Map<String, DownloadErrorPolicy> getDownloadErrorPolicies()
+ {
+ return downloadErrorPolicies;
+ }
+
+ public void setDownloadErrorPolicies( Map<String, DownloadErrorPolicy> downloadErrorPolicies )
+ {
+ this.downloadErrorPolicies = downloadErrorPolicies;
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+/**
+ * NotFoundException - thrown when the resource requested was not found on the remote repository.
+ *
+ * @version $Id$
+ */
+public class NotFoundException
+ extends ProxyException
+{
+ public NotFoundException( String message, Throwable t )
+ {
+ super( message, t );
+ }
+
+ public NotFoundException( String message )
+ {
+ super( message );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+/**
+ * <p>
+ * NotModifiedException - thrown when the resource requested was found on the remote repository, but
+ * the remote repository reported that the copy we have in our managed repository is newer than
+ * the one present on the remote repository.
+ * </p>
+ * <p>
+ * Similar in scope to the <code>HTTP 304 Not Modified</code> response code.
+ * </p>
+ *
+ * @version $Id$
+ */
+public class NotModifiedException
+ extends ProxyException
+{
+
+ public NotModifiedException( String message )
+ {
+ super( message );
+ }
+
+ public NotModifiedException( String message, Throwable t )
+ {
+ super( message, t );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.maven.archiva.repository.ManagedRepositoryContent;
+import org.apache.maven.archiva.repository.RemoteRepositoryContent;
+import org.apache.maven.archiva.repository.connector.RepositoryConnector;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This represents a connector for a repository to repository proxy.
+ *
+ * @version $Id$
+ */
+public class ProxyConnector
+ implements RepositoryConnector
+{
+ private ManagedRepositoryContent sourceRepository;
+
+ private RemoteRepositoryContent targetRepository;
+
+ private List<String> blacklist;
+
+ private List<String> whitelist;
+
+ private String proxyId;
+
+ private int order;
+
+ private Map<String, String> policies;
+
+ private boolean disabled;
+
+ public boolean isDisabled()
+ {
+ return disabled;
+ }
+
+ public void setDisabled(boolean disabled)
+ {
+ this.disabled = disabled;
+ }
+
+ public List<String> getBlacklist()
+ {
+ return blacklist;
+ }
+
+ public void setBlacklist( List<String> blacklist )
+ {
+ this.blacklist = blacklist;
+ }
+
+ public ManagedRepositoryContent getSourceRepository()
+ {
+ return sourceRepository;
+ }
+
+ public void setSourceRepository( ManagedRepositoryContent sourceRepository )
+ {
+ this.sourceRepository = sourceRepository;
+ }
+
+ public RemoteRepositoryContent getTargetRepository()
+ {
+ return targetRepository;
+ }
+
+ public void setTargetRepository( RemoteRepositoryContent targetRepository )
+ {
+ this.targetRepository = targetRepository;
+ }
+
+ public List<String> getWhitelist()
+ {
+ return whitelist;
+ }
+
+ public void setWhitelist( List<String> whitelist )
+ {
+ this.whitelist = whitelist;
+ }
+
+ public Map<String, String> getPolicies()
+ {
+ return policies;
+ }
+
+ public void setPolicies( Map<String, String> policies )
+ {
+ this.policies = policies;
+ }
+
+ public String getProxyId()
+ {
+ return proxyId;
+ }
+
+ public void setProxyId( String proxyId )
+ {
+ this.proxyId = proxyId;
+ }
+
+ @Override
+ public String toString()
+ {
+ StringBuffer sb = new StringBuffer();
+
+ sb.append( "ProxyConnector[\n" );
+ sb.append( " source: [managed] " ).append( this.sourceRepository.getRepoRoot() ).append( "\n" );
+ sb.append( " target: [remote] " ).append( this.targetRepository.getRepository().getUrl() ).append( "\n" );
+ sb.append( " proxyId:" ).append( this.proxyId ).append( "\n" );
+
+ Iterator<String> keys = this.policies.keySet().iterator();
+ while ( keys.hasNext() )
+ {
+ String name = keys.next();
+ sb.append( " policy[" ).append( name ).append( "]:" );
+ sb.append( this.policies.get( name ) ).append( "\n" );
+ }
+
+ sb.append( "]" );
+
+ return sb.toString();
+ }
+
+ public void setPolicy( String policyId, String policySetting )
+ {
+ this.policies.put( policyId, policySetting );
+ }
+
+ public int getOrder()
+ {
+ return order;
+ }
+
+ public void setOrder( int order )
+ {
+ this.order = order;
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import java.util.Comparator;
+
+/**
+ * ProxyConnectorOrderComparator
+ *
+ * @version $Id$
+ */
+public class ProxyConnectorOrderComparator
+ implements Comparator<ProxyConnector>
+{
+ private static ProxyConnectorOrderComparator INSTANCE = new ProxyConnectorOrderComparator();
+
+ public static ProxyConnectorOrderComparator getInstance()
+ {
+ return INSTANCE;
+ }
+
+ public int compare( ProxyConnector o1, ProxyConnector o2 )
+ {
+ if ( o1 == null && o2 == null )
+ {
+ return 0;
+ }
+
+ // Ensure null goes to end of list.
+ if ( o1 == null && o2 != null )
+ {
+ return 1;
+ }
+
+ if ( o1 != null && o2 == null )
+ {
+ return -1;
+ }
+
+ // Ensure 0 (unordered) goes to end of list.
+ if ( o1.getOrder() == 0 && o2.getOrder() != 0 )
+ {
+ return 1;
+ }
+
+ if ( o1.getOrder() != 0 && o2.getOrder() == 0 )
+ {
+ return -1;
+ }
+
+ return o1.getOrder() - o2.getOrder();
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+/**
+ */
+public class ProxyException
+ extends Exception
+{
+ public ProxyException( String message )
+ {
+ super( message );
+ }
+
+ public ProxyException( String message, Throwable t )
+ {
+ super( message, t );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.maven.archiva.model.ArtifactReference;
+import org.apache.maven.archiva.policies.ProxyDownloadException;
+import org.apache.maven.archiva.repository.ManagedRepositoryContent;
+
+import java.io.File;
+import java.util.List;
+
+/**
+ * Handler for potential repository proxy connectors.
+ *
+ * @version $Id$
+ */
+public interface RepositoryProxyConnectors
+{
+ /**
+ * Performs the artifact fetch operation against the target repositories
+ * of the provided source repository.
+ *
+ * If the artifact is found, it is downloaded and placed into the source repository
+ * filesystem.
+ *
+ * @param repository the source repository to use. (must be a managed repository)
+ * @param artifact the artifact to fetch.
+ * @return the file that was obtained, or null if no content was obtained
+ * @throws ProxyDownloadException if there was a problem fetching the content from the target repositories.
+ */
+ public File fetchFromProxies( ManagedRepositoryContent repository, ArtifactReference artifact )
+ throws ProxyDownloadException;
+
+ /**
+ * Performs the metadata fetch operation against the target repositories
+ * of the provided source repository.
+ *
+ * If the metadata is found, it is downloaded and placed into the source repository
+ * filesystem.
+ *
+ * @param repository the source repository to use. (must be a managed repository)
+ * @param metadata the metadata to fetch.
+ * @return the file that was obtained, or null if no content was obtained
+ */
+ public File fetchMetatadaFromProxies( ManagedRepositoryContent repository, String logicalPath );
+
+ /**
+ * Performs the fetch operation against the target repositories
+ * of the provided source repository.
+ *
+ * @param repository the source repository to use. (must be a managed repository)
+ * @param path the path of the resource to fetch
+ * @return the file that was obtained, or null if no content was obtained
+ */
+ public File fetchFromProxies( ManagedRepositoryContent managedRepository, String path );
+
+ /**
+ * Get the List of {@link ProxyConnector} objects of the source repository.
+ *
+ * @param repository the source repository to look for.
+ * @return the List of {@link ProxyConnector} objects.
+ */
+ public List<ProxyConnector> getProxyConnectors( ManagedRepositoryContent repository );
+
+ /**
+ * Tests to see if the provided repository is a source repository for
+ * any {@link ProxyConnector} objects.
+ *
+ * @param repository the source repository to look for.
+ * @return true if there are proxy connectors that use the provided
+ * repository as a source repository.
+ */
+ public boolean hasProxies( ManagedRepositoryContent repository );
+}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import com.google.common.collect.Lists;
-import org.apache.archiva.proxy.common.WagonFactory;
-import org.apache.archiva.proxy.common.WagonFactoryException;
-import org.apache.archiva.scheduler.ArchivaTaskScheduler;
-import org.apache.archiva.scheduler.repository.RepositoryTask;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringUtils;
-import org.apache.maven.archiva.configuration.ArchivaConfiguration;
-import org.apache.maven.archiva.configuration.ConfigurationNames;
-import org.apache.maven.archiva.configuration.NetworkProxyConfiguration;
-import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
-import org.apache.maven.archiva.model.ArtifactReference;
-import org.apache.maven.archiva.model.Keys;
-import org.apache.maven.archiva.model.RepositoryURL;
-import org.apache.maven.archiva.policies.DownloadErrorPolicy;
-import org.apache.maven.archiva.policies.DownloadPolicy;
-import org.apache.maven.archiva.policies.PolicyConfigurationException;
-import org.apache.maven.archiva.policies.PolicyViolationException;
-import org.apache.maven.archiva.policies.PostDownloadPolicy;
-import org.apache.maven.archiva.policies.PreDownloadPolicy;
-import org.apache.maven.archiva.policies.ProxyDownloadException;
-import org.apache.maven.archiva.policies.urlcache.UrlFailureCache;
-import org.apache.maven.archiva.repository.ManagedRepositoryContent;
-import org.apache.maven.archiva.repository.RemoteRepositoryContent;
-import org.apache.maven.archiva.repository.RepositoryContentFactory;
-import org.apache.maven.archiva.repository.RepositoryException;
-import org.apache.maven.archiva.repository.RepositoryNotFoundException;
-import org.apache.maven.archiva.repository.metadata.MetadataTools;
-import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
-import org.apache.maven.wagon.ConnectionException;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.apache.maven.wagon.Wagon;
-import org.apache.maven.wagon.WagonException;
-import org.apache.maven.wagon.authentication.AuthenticationException;
-import org.apache.maven.wagon.authentication.AuthenticationInfo;
-import org.apache.maven.wagon.proxy.ProxyInfo;
-import org.apache.maven.wagon.repository.Repository;
-import org.codehaus.plexus.registry.Registry;
-import org.codehaus.plexus.registry.RegistryListener;
-import org.codehaus.plexus.taskqueue.TaskQueueException;
-import org.codehaus.plexus.util.SelectorUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
-import javax.inject.Inject;
-import javax.inject.Named;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-
-/**
- * DefaultRepositoryProxyConnectors
- *
- * @version $Id$
- * @todo exception handling needs work - "not modified" is not really an exceptional case, and it has more layers than
- * your average brown onion
- */
-@Service( "repositoryProxyConnectors#default" )
-public class DefaultRepositoryProxyConnectors
- implements RepositoryProxyConnectors, RegistryListener
-{
- private Logger log = LoggerFactory.getLogger( DefaultRepositoryProxyConnectors.class );
-
- /**
- *
- */
- @Inject
- @Named( value = "archivaConfiguration#default" )
- private ArchivaConfiguration archivaConfiguration;
-
- /**
- *
- */
- @Inject
- @Named( value = "repositoryContentFactory#default" )
- private RepositoryContentFactory repositoryFactory;
-
- /**
- *
- */
- @Inject
- @Named( value = "metadataTools#default" )
- private MetadataTools metadataTools;
-
- /**
- *
- */
- @Inject
- private Map<String, PreDownloadPolicy> preDownloadPolicies;
-
- /**
- *
- */
- @Inject
- private Map<String, PostDownloadPolicy> postDownloadPolicies;
-
- /**
- *
- */
- @Inject
- private Map<String, DownloadErrorPolicy> downloadErrorPolicies;
-
- /**
- *
- */
- @Inject
- private UrlFailureCache urlFailureCache;
-
- private Map<String, List<ProxyConnector>> proxyConnectorMap = new HashMap<String, List<ProxyConnector>>();
-
- private Map<String, ProxyInfo> networkProxyMap = new HashMap<String, ProxyInfo>();
-
- /**
- *
- */
- @Inject
- private WagonFactory wagonFactory;
-
- /**
- *
- */
- @Inject
- @Named( value = "archivaTaskScheduler#repository" )
- private ArchivaTaskScheduler scheduler;
-
- @PostConstruct
- public void initialize()
- {
- initConnectorsAndNetworkProxies();
- archivaConfiguration.addChangeListener( this );
- //this.postDownloadPolicies = applicationContext.getBeansOfType( PostDownloadPolicy.class );
- //his.preDownloadPolicies = applicationContext.getBeansOfType( PreDownloadPolicy.class );
- //this.downloadErrorPolicies = applicationContext.getBeansOfType( DownloadErrorPolicy.class );
- }
-
- @SuppressWarnings( "unchecked" )
- private void initConnectorsAndNetworkProxies()
- {
- synchronized ( this.proxyConnectorMap )
- {
- ProxyConnectorOrderComparator proxyOrderSorter = new ProxyConnectorOrderComparator();
- this.proxyConnectorMap.clear();
-
- List<ProxyConnectorConfiguration> proxyConfigs =
- archivaConfiguration.getConfiguration().getProxyConnectors();
- for ( ProxyConnectorConfiguration proxyConfig : proxyConfigs )
- {
- String key = proxyConfig.getSourceRepoId();
-
- try
- {
- // Create connector object.
- ProxyConnector connector = new ProxyConnector();
-
- connector.setSourceRepository(
- repositoryFactory.getManagedRepositoryContent( proxyConfig.getSourceRepoId() ) );
- connector.setTargetRepository(
- repositoryFactory.getRemoteRepositoryContent( proxyConfig.getTargetRepoId() ) );
-
- connector.setProxyId( proxyConfig.getProxyId() );
- connector.setPolicies( proxyConfig.getPolicies() );
- connector.setOrder( proxyConfig.getOrder() );
- connector.setDisabled( proxyConfig.isDisabled() );
-
- // Copy any blacklist patterns.
- List<String> blacklist = new ArrayList<String>();
- if ( CollectionUtils.isNotEmpty( proxyConfig.getBlackListPatterns() ) )
- {
- blacklist.addAll( proxyConfig.getBlackListPatterns() );
- }
- connector.setBlacklist( blacklist );
-
- // Copy any whitelist patterns.
- List<String> whitelist = new ArrayList<String>();
- if ( CollectionUtils.isNotEmpty( proxyConfig.getWhiteListPatterns() ) )
- {
- whitelist.addAll( proxyConfig.getWhiteListPatterns() );
- }
- connector.setWhitelist( whitelist );
-
- // Get other connectors
- List<ProxyConnector> connectors = this.proxyConnectorMap.get( key );
- if ( connectors == null )
- {
- // Create if we are the first.
- connectors = new ArrayList<ProxyConnector>();
- }
-
- // Add the connector.
- connectors.add( connector );
-
- // Ensure the list is sorted.
- Collections.sort( connectors, proxyOrderSorter );
-
- // Set the key to the list of connectors.
- this.proxyConnectorMap.put( key, connectors );
- }
- catch ( RepositoryNotFoundException e )
- {
- log.warn( "Unable to use proxy connector: " + e.getMessage(), e );
- }
- catch ( RepositoryException e )
- {
- log.warn( "Unable to use proxy connector: " + e.getMessage(), e );
- }
- }
-
- }
-
- synchronized ( this.networkProxyMap )
- {
- this.networkProxyMap.clear();
-
- List<NetworkProxyConfiguration> networkProxies =
- archivaConfiguration.getConfiguration().getNetworkProxies();
- for ( NetworkProxyConfiguration networkProxyConfig : networkProxies )
- {
- String key = networkProxyConfig.getId();
-
- ProxyInfo proxy = new ProxyInfo();
-
- proxy.setType( networkProxyConfig.getProtocol() );
- proxy.setHost( networkProxyConfig.getHost() );
- proxy.setPort( networkProxyConfig.getPort() );
- proxy.setUserName( networkProxyConfig.getUsername() );
- proxy.setPassword( networkProxyConfig.getPassword() );
-
- this.networkProxyMap.put( key, proxy );
- }
- }
- }
-
- public File fetchFromProxies( ManagedRepositoryContent repository, ArtifactReference artifact )
- throws ProxyDownloadException
- {
- File localFile = toLocalFile( repository, artifact );
-
- Properties requestProperties = new Properties();
- requestProperties.setProperty( "filetype", "artifact" );
- requestProperties.setProperty( "version", artifact.getVersion() );
- requestProperties.setProperty( "managedRepositoryId", repository.getId() );
-
- List<ProxyConnector> connectors = getProxyConnectors( repository );
- Map<String, Exception> previousExceptions = new LinkedHashMap<String, Exception>();
- for ( ProxyConnector connector : connectors )
- {
- if ( connector.isDisabled() )
- {
- continue;
- }
-
- RemoteRepositoryContent targetRepository = connector.getTargetRepository();
- requestProperties.setProperty( "remoteRepositoryId", targetRepository.getId() );
-
- String targetPath = targetRepository.toPath( artifact );
-
- try
- {
- File downloadedFile =
- transferFile( connector, targetRepository, targetPath, repository, localFile, requestProperties,
- true );
-
- if ( fileExists( downloadedFile ) )
- {
- log.debug( "Successfully transferred: {}", downloadedFile.getAbsolutePath() );
- return downloadedFile;
- }
- }
- catch ( NotFoundException e )
- {
- log.debug( "Artifact {} not found on repository \"{}\".", Keys.toKey( artifact ),
- targetRepository.getRepository().getId() );
- }
- catch ( NotModifiedException e )
- {
- log.debug( "Artifact {} not updated on repository \"{}\".", Keys.toKey( artifact ),
- targetRepository.getRepository().getId() );
- }
- catch ( ProxyException e )
- {
- validatePolicies( this.downloadErrorPolicies, connector.getPolicies(), requestProperties, artifact,
- targetRepository, localFile, e, previousExceptions );
- }
- }
-
- if ( !previousExceptions.isEmpty() )
- {
- throw new ProxyDownloadException( "Failures occurred downloading from some remote repositories",
- previousExceptions );
- }
-
- log.debug( "Exhausted all target repositories, artifact {} not found.", Keys.toKey( artifact ) );
-
- return null;
- }
-
- public File fetchFromProxies( ManagedRepositoryContent repository, String path )
- {
- File localFile = new File( repository.getRepoRoot(), path );
-
- // no update policies for these paths
- if ( localFile.exists() )
- {
- return null;
- }
-
- Properties requestProperties = new Properties();
- requestProperties.setProperty( "filetype", "resource" );
- requestProperties.setProperty( "managedRepositoryId", repository.getId() );
-
- List<ProxyConnector> connectors = getProxyConnectors( repository );
- for ( ProxyConnector connector : connectors )
- {
- if ( connector.isDisabled() )
- {
- continue;
- }
-
- RemoteRepositoryContent targetRepository = connector.getTargetRepository();
- requestProperties.setProperty( "remoteRepositoryId", targetRepository.getId() );
-
- String targetPath = path;
-
- try
- {
- File downloadedFile =
- transferFile( connector, targetRepository, targetPath, repository, localFile, requestProperties,
- false );
-
- if ( fileExists( downloadedFile ) )
- {
- log.debug( "Successfully transferred: {}", downloadedFile.getAbsolutePath() );
- return downloadedFile;
- }
- }
- catch ( NotFoundException e )
- {
- log.debug( "Resource {} not found on repository \"{}\".", path,
- targetRepository.getRepository().getId() );
- }
- catch ( NotModifiedException e )
- {
- log.debug( "Resource {} not updated on repository \"{}\".", path,
- targetRepository.getRepository().getId() );
- }
- catch ( ProxyException e )
- {
- log.warn(
- "Transfer error from repository \"" + targetRepository.getRepository().getId() + "\" for resource "
- + path + ", continuing to next repository. Error message: " + e.getMessage() );
- log.debug( "Full stack trace", e );
- }
- }
-
- log.debug( "Exhausted all target repositories, resource {} not found.", path );
-
- return null;
- }
-
- public File fetchMetatadaFromProxies( ManagedRepositoryContent repository, String logicalPath )
- {
- File localFile = new File( repository.getRepoRoot(), logicalPath );
-
- Properties requestProperties = new Properties();
- requestProperties.setProperty( "filetype", "metadata" );
- boolean metadataNeedsUpdating = false;
- long originalTimestamp = getLastModified( localFile );
-
- List<ProxyConnector> connectors = getProxyConnectors( repository );
- for ( ProxyConnector connector : connectors )
- {
- if ( connector.isDisabled() )
- {
- continue;
- }
-
- RemoteRepositoryContent targetRepository = connector.getTargetRepository();
-
- File localRepoFile = toLocalRepoFile( repository, targetRepository, logicalPath );
- long originalMetadataTimestamp = getLastModified( localRepoFile );
-
- try
- {
- transferFile( connector, targetRepository, logicalPath, repository, localRepoFile, requestProperties,
- true );
-
- if ( hasBeenUpdated( localRepoFile, originalMetadataTimestamp ) )
- {
- metadataNeedsUpdating = true;
- }
- }
- catch ( NotFoundException e )
- {
- if ( log.isDebugEnabled() )
- {
- log.debug( "Metadata {} not found on remote repository \"{}\".",
- Lists.<Object>newArrayList( logicalPath, targetRepository.getRepository().getId() ), e );
- }
- }
- catch ( NotModifiedException e )
- {
- if ( log.isDebugEnabled() )
- {
- log.debug( "Metadata {} not updated on remote repository \"{}\".",
- Lists.<Object>newArrayList( logicalPath, targetRepository.getRepository().getId() ), e );
- }
- }
- catch ( ProxyException e )
- {
- log.warn( "Transfer error from repository \"" + targetRepository.getRepository().getId()
- + "\" for versioned Metadata " + logicalPath
- + ", continuing to next repository. Error message: " + e.getMessage() );
- log.debug( "Full stack trace", e );
- }
- }
-
- if ( hasBeenUpdated( localFile, originalTimestamp ) )
- {
- metadataNeedsUpdating = true;
- }
-
- if ( metadataNeedsUpdating || !localFile.exists() )
- {
- try
- {
- metadataTools.updateMetadata( repository, logicalPath );
- }
- catch ( RepositoryMetadataException e )
- {
- log.warn( "Unable to update metadata " + localFile.getAbsolutePath() + ": " + e.getMessage(), e );
- }
- }
-
- if ( fileExists( localFile ) )
- {
- return localFile;
- }
-
- return null;
- }
-
- private long getLastModified( File file )
- {
- if ( !file.exists() || !file.isFile() )
- {
- return 0;
- }
-
- return file.lastModified();
- }
-
- private boolean hasBeenUpdated( File file, long originalLastModified )
- {
- if ( !file.exists() || !file.isFile() )
- {
- return false;
- }
-
- long currentLastModified = getLastModified( file );
- return ( currentLastModified > originalLastModified );
- }
-
- private File toLocalRepoFile( ManagedRepositoryContent repository, RemoteRepositoryContent targetRepository,
- String targetPath )
- {
- String repoPath = metadataTools.getRepositorySpecificName( targetRepository, targetPath );
- return new File( repository.getRepoRoot(), repoPath );
- }
-
- /**
- * Test if the provided ManagedRepositoryContent has any proxies configured for it.
- */
- public boolean hasProxies( ManagedRepositoryContent repository )
- {
- synchronized ( this.proxyConnectorMap )
- {
- return this.proxyConnectorMap.containsKey( repository.getId() );
- }
- }
-
- private File toLocalFile( ManagedRepositoryContent repository, ArtifactReference artifact )
- {
- return repository.toFile( artifact );
- }
-
- /**
- * Simple method to test if the file exists on the local disk.
- *
- * @param file the file to test. (may be null)
- * @return true if file exists. false if the file param is null, doesn't exist, or is not of type File.
- */
- private boolean fileExists( File file )
- {
- if ( file == null )
- {
- return false;
- }
-
- if ( !file.exists() )
- {
- return false;
- }
-
- if ( !file.isFile() )
- {
- return false;
- }
-
- return true;
- }
-
- /**
- * Perform the transfer of the file.
- *
- * @param connector the connector configuration to use.
- * @param remoteRepository the remote repository get the resource from.
- * @param remotePath the path in the remote repository to the resource to get.
- * @param repository the managed repository that will hold the file
- * @param resource the local file to place the downloaded resource into
- * @param requestProperties the request properties to utilize for policy handling.
- * @param executeConsumers whether to execute the consumers after proxying
- * @return the local file that was downloaded, or null if not downloaded.
- * @throws NotFoundException if the file was not found on the remote repository.
- * @throws NotModifiedException if the localFile was present, and the resource was present on remote repository, but
- * the remote resource is not newer than the local File.
- * @throws ProxyException if transfer was unsuccessful.
- */
- private File transferFile( ProxyConnector connector, RemoteRepositoryContent remoteRepository, String remotePath,
- ManagedRepositoryContent repository, File resource, Properties requestProperties,
- boolean executeConsumers )
- throws ProxyException, NotModifiedException
- {
- String url = remoteRepository.getURL().getUrl();
- if ( !url.endsWith( "/" ) )
- {
- url = url + "/";
- }
- url = url + remotePath;
- requestProperties.setProperty( "url", url );
-
- // Is a whitelist defined?
- if ( CollectionUtils.isNotEmpty( connector.getWhitelist() ) )
- {
- // Path must belong to whitelist.
- if ( !matchesPattern( remotePath, connector.getWhitelist() ) )
- {
- log.debug( "Path [{}] is not part of defined whitelist (skipping transfer from repository [{}]).",
- remotePath, remoteRepository.getRepository().getName() );
- return null;
- }
- }
-
- // Is target path part of blacklist?
- if ( matchesPattern( remotePath, connector.getBlacklist() ) )
- {
- log.debug( "Path [{}] is part of blacklist (skipping transfer from repository [{}]).", remotePath,
- remoteRepository.getRepository().getName() );
- return null;
- }
-
- // Handle pre-download policy
- try
- {
- validatePolicies( this.preDownloadPolicies, connector.getPolicies(), requestProperties, resource );
- }
- catch ( PolicyViolationException e )
- {
- String emsg = "Transfer not attempted on " + url + " : " + e.getMessage();
- if ( fileExists( resource ) )
- {
- log.debug( "{} : using already present local file.", emsg );
- return resource;
- }
-
- log.debug( emsg );
- return null;
- }
-
- File tmpMd5 = null;
- File tmpSha1 = null;
- File tmpResource = null;
-
- File workingDirectory = createWorkingDirectory( repository );
- try
- {
- Wagon wagon = null;
- try
- {
- RepositoryURL repoUrl = remoteRepository.getURL();
- String protocol = repoUrl.getProtocol();
- wagon = wagonFactory.getWagon( "wagon#" + protocol );
- if ( wagon == null )
- {
- throw new ProxyException( "Unsupported target repository protocol: " + protocol );
- }
-
- boolean connected = connectToRepository( connector, wagon, remoteRepository );
- if ( connected )
- {
- tmpResource = new File( workingDirectory, resource.getName() );
- transferSimpleFile( wagon, remoteRepository, remotePath, repository, resource, tmpResource );
-
- // TODO: these should be used to validate the download based on the policies, not always downloaded
- // to
- // save on connections since md5 is rarely used
- tmpSha1 =
- transferChecksum( wagon, remoteRepository, remotePath, repository, resource, workingDirectory,
- ".sha1" );
- tmpMd5 =
- transferChecksum( wagon, remoteRepository, remotePath, repository, resource, workingDirectory,
- ".md5" );
- }
- }
- catch ( NotFoundException e )
- {
- urlFailureCache.cacheFailure( url );
- throw e;
- }
- catch ( NotModifiedException e )
- {
- // Do not cache url here.
- throw e;
- }
- catch ( ProxyException e )
- {
- urlFailureCache.cacheFailure( url );
- throw e;
- }
- catch ( WagonFactoryException e )
- {
- throw new ProxyException( e.getMessage(), e );
- }
- finally
- {
- if ( wagon != null )
- {
- try
- {
- wagon.disconnect();
- }
- catch ( ConnectionException e )
- {
- log.warn( "Unable to disconnect wagon.", e );
- }
- }
- }
-
- // Handle post-download policies.
- try
- {
- validatePolicies( this.postDownloadPolicies, connector.getPolicies(), requestProperties, tmpResource );
- }
- catch ( PolicyViolationException e )
- {
- log.warn( "Transfer invalidated from {} : {}", url, e.getMessage() );
- executeConsumers = false;
- if ( !fileExists( tmpResource ) )
- {
- resource = null;
- }
- }
-
- if ( resource != null )
- {
- synchronized ( resource.getAbsolutePath().intern() )
- {
- File directory = resource.getParentFile();
- moveFileIfExists( tmpMd5, directory );
- moveFileIfExists( tmpSha1, directory );
- moveFileIfExists( tmpResource, directory );
- }
- }
- }
- finally
- {
- FileUtils.deleteQuietly( workingDirectory );
- }
-
- if ( executeConsumers )
- {
- // Just-in-time update of the index and database by executing the consumers for this artifact
- //consumers.executeConsumers( connector.getSourceRepository().getRepository(), resource );
- queueRepositoryTask( connector.getSourceRepository().getRepository().getId(), resource );
- }
-
- return resource;
- }
-
- private void queueRepositoryTask( String repositoryId, File localFile )
- {
- RepositoryTask task = new RepositoryTask();
- task.setRepositoryId( repositoryId );
- task.setResourceFile( localFile );
- task.setUpdateRelatedArtifacts( true );
- task.setScanAll( true );
-
- try
- {
- scheduler.queueTask( task );
- }
- catch ( TaskQueueException e )
- {
- log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
- + "']." );
- }
- }
-
- /**
- * Moves the file into repository location if it exists
- *
- * @param fileToMove this could be either the main artifact, sha1 or md5 checksum file.
- * @param directory directory to write files to
- */
- private void moveFileIfExists( File fileToMove, File directory )
- throws ProxyException
- {
- if ( fileToMove != null && fileToMove.exists() )
- {
- File newLocation = new File( directory, fileToMove.getName() );
- moveTempToTarget( fileToMove, newLocation );
- }
- }
-
- /**
- * <p>
- * Quietly transfer the checksum file from the remote repository to the local file.
- * </p>
- *
- * @param wagon the wagon instance (should already be connected) to use.
- * @param remoteRepository the remote repository to transfer from.
- * @param remotePath the remote path to the resource to get.
- * @param repository the managed repository that will hold the file
- * @param resource the local file that should contain the downloaded contents
- * @param tmpDirectory the temporary directory to download to
- * @param ext the type of checksum to transfer (example: ".md5" or ".sha1")
- * @throws ProxyException if copying the downloaded file into place did not succeed.
- */
- private File transferChecksum( Wagon wagon, RemoteRepositoryContent remoteRepository, String remotePath,
- ManagedRepositoryContent repository, File resource, File tmpDirectory, String ext )
- throws ProxyException
- {
- String url = remoteRepository.getURL().getUrl() + remotePath + ext;
-
- // Transfer checksum does not use the policy.
- if ( urlFailureCache.hasFailedBefore( url ) )
- {
- return null;
- }
-
- File destFile = new File( tmpDirectory, resource.getName() + ext );
-
- try
- {
- transferSimpleFile( wagon, remoteRepository, remotePath + ext, repository, resource, destFile );
- log.debug( "Checksum {} Downloaded: {} to move to {}", Arrays.asList( url, destFile, resource ).toArray() );
- }
- catch ( NotFoundException e )
- {
- urlFailureCache.cacheFailure( url );
- log.debug( "Transfer failed, checksum not found: {}", url );
- // Consume it, do not pass this on.
- }
- catch ( NotModifiedException e )
- {
- log.debug( "Transfer skipped, checksum not modified: {}", url );
- // Consume it, do not pass this on.
- }
- catch ( ProxyException e )
- {
- urlFailureCache.cacheFailure( url );
- log.warn( "Transfer failed on checksum: " + url + " : " + e.getMessage(), e );
- // Critical issue, pass it on.
- throw e;
- }
- return destFile;
- }
-
- /**
- * Perform the transfer of the remote file to the local file specified.
- *
- * @param wagon the wagon instance to use.
- * @param remoteRepository the remote repository to use
- * @param remotePath the remote path to attempt to get
- * @param repository the managed repository that will hold the file
- * @param origFile the local file to save to
- * @return The local file that was transfered.
- * @throws ProxyException if there was a problem moving the downloaded file into place.
- * @throws WagonException if there was a problem tranfering the file.
- */
- private void transferSimpleFile( Wagon wagon, RemoteRepositoryContent remoteRepository, String remotePath,
- ManagedRepositoryContent repository, File origFile, File destFile )
- throws ProxyException
- {
- assert ( remotePath != null );
-
- // Transfer the file.
- try
- {
- boolean success = false;
-
- if ( !origFile.exists() )
- {
- log.debug( "Retrieving {} from {}", remotePath, remoteRepository.getRepository().getName() );
- wagon.get( remotePath, destFile );
- success = true;
-
- // You wouldn't get here on failure, a WagonException would have been thrown.
- log.debug( "Downloaded successfully." );
- }
- else
- {
- log.debug( "Retrieving {} from {} if updated", remotePath, remoteRepository.getRepository().getName() );
- success = wagon.getIfNewer( remotePath, destFile, origFile.lastModified() );
- if ( !success )
- {
- throw new NotModifiedException(
- "Not downloaded, as local file is newer than remote side: " + origFile.getAbsolutePath() );
- }
-
- if ( destFile.exists() )
- {
- log.debug( "Downloaded successfully." );
- }
- }
- }
- catch ( ResourceDoesNotExistException e )
- {
- throw new NotFoundException(
- "Resource [" + remoteRepository.getURL() + "/" + remotePath + "] does not exist: " + e.getMessage(),
- e );
- }
- catch ( WagonException e )
- {
- // TODO: shouldn't have to drill into the cause, but TransferFailedException is often not descriptive enough
-
- String msg =
- "Download failure on resource [" + remoteRepository.getURL() + "/" + remotePath + "]:" + e.getMessage();
- if ( e.getCause() != null )
- {
- msg += " (cause: " + e.getCause() + ")";
- }
- throw new ProxyException( msg, e );
- }
- }
-
- /**
- * Apply the policies.
- *
- * @param policies the map of policies to execute. (Map of String policy keys, to {@link DownloadPolicy} objects)
- * @param settings the map of settings for the policies to execute. (Map of String policy keys, to String policy
- * setting)
- * @param request the request properties (utilized by the {@link DownloadPolicy#applyPolicy(String, Properties, File)}
- * )
- * @param localFile the local file (utilized by the {@link DownloadPolicy#applyPolicy(String, Properties, File)})
- */
- private void validatePolicies( Map<String, ? extends DownloadPolicy> policies, Map<String, String> settings,
- Properties request, File localFile )
- throws PolicyViolationException
- {
- for ( Entry<String, ? extends DownloadPolicy> entry : policies.entrySet() )
- {
- // olamy with spring rolehint is now downloadPolicy#hint
- // so substring after last # to get the hint as with plexus
- String key = StringUtils.substringAfterLast( entry.getKey(), "#" );
- DownloadPolicy policy = entry.getValue();
- String defaultSetting = policy.getDefaultOption();
-
- String setting = StringUtils.defaultString( settings.get( key ), defaultSetting );
-
- log.debug( "Applying [{}] policy with [{}]", key, setting );
- try
- {
- policy.applyPolicy( setting, request, localFile );
- }
- catch ( PolicyConfigurationException e )
- {
- log.error( e.getMessage(), e );
- }
- }
- }
-
- private void validatePolicies( Map<String, DownloadErrorPolicy> policies, Map<String, String> settings,
- Properties request, ArtifactReference artifact, RemoteRepositoryContent content,
- File localFile, ProxyException exception, Map<String, Exception> previousExceptions )
- throws ProxyDownloadException
- {
- boolean process = true;
- for ( Entry<String, ? extends DownloadErrorPolicy> entry : policies.entrySet() )
- {
-
- // olamy with spring rolehint is now downloadPolicy#hint
- // so substring after last # to get the hint as with plexus
- String key = StringUtils.substringAfterLast( entry.getKey(), "#" );
- DownloadErrorPolicy policy = entry.getValue();
- String defaultSetting = policy.getDefaultOption();
- String setting = StringUtils.defaultString( settings.get( key ), defaultSetting );
-
- log.debug( "Applying [{}] policy with [{}]", key, setting );
- try
- {
- // all policies must approve the exception, any can cancel
- process = policy.applyPolicy( setting, request, localFile, exception, previousExceptions );
- if ( !process )
- {
- break;
- }
- }
- catch ( PolicyConfigurationException e )
- {
- log.error( e.getMessage(), e );
- }
- }
-
- if ( process )
- {
- // if the exception was queued, don't throw it
- if ( !previousExceptions.containsKey( content.getId() ) )
- {
- throw new ProxyDownloadException(
- "An error occurred in downloading from the remote repository, and the policy is to fail immediately",
- content.getId(), exception );
- }
- }
- else
- {
- // if the exception was queued, but cancelled, remove it
- previousExceptions.remove( content.getId() );
- }
-
- log.warn( "Transfer error from repository \"" + content.getRepository().getId() + "\" for artifact "
- + Keys.toKey( artifact ) + ", continuing to next repository. Error message: "
- + exception.getMessage() );
- log.debug( "Full stack trace", exception );
- }
-
- /**
- * Creates a working directory in the repository root for this request
- *
- * @param repository
- * @return file location of working directory
- * @throws IOException
- */
- private File createWorkingDirectory( ManagedRepositoryContent repository )
- {
- // TODO: This is ugly - lets actually clean this up when we get the new repository api
- try
- {
- File tmpDir = File.createTempFile( ".workingdirectory", null, new File( repository.getRepoRoot() ) );
- tmpDir.delete();
- tmpDir.mkdirs();
- return tmpDir;
- }
- catch ( IOException e )
- {
- throw new RuntimeException( "Could not create working directory for this request", e );
- }
- }
-
- /**
- * Used to move the temporary file to its real destination. This is patterned from the way WagonManager handles its
- * downloaded files.
- *
- * @param temp The completed download file
- * @param target The final location of the downloaded file
- * @throws ProxyException when the temp file cannot replace the target file
- */
- private void moveTempToTarget( File temp, File target )
- throws ProxyException
- {
- if ( target.exists() && !target.delete() )
- {
- throw new ProxyException( "Unable to overwrite existing target file: " + target.getAbsolutePath() );
- }
-
- target.getParentFile().mkdirs();
- if ( !temp.renameTo( target ) )
- {
- log.warn( "Unable to rename tmp file to its final name... resorting to copy command." );
-
- try
- {
- FileUtils.copyFile( temp, target );
- }
- catch ( IOException e )
- {
- if ( target.exists() )
- {
- log.debug( "Tried to copy file {} to {} but file with this name already exists.", temp.getName(),
- target.getAbsolutePath() );
- }
- else
- {
- throw new ProxyException(
- "Cannot copy tmp file " + temp.getAbsolutePath() + " to its final location", e );
- }
- }
- finally
- {
- FileUtils.deleteQuietly( temp );
- }
- }
- }
-
- /**
- * Using wagon, connect to the remote repository.
- *
- * @param connector the connector configuration to utilize (for obtaining network proxy configuration from)
- * @param wagon the wagon instance to establish the connection on.
- * @param remoteRepository the remote repository to connect to.
- * @return true if the connection was successful. false if not connected.
- */
- private boolean connectToRepository( ProxyConnector connector, Wagon wagon,
- RemoteRepositoryContent remoteRepository )
- {
- boolean connected = false;
-
- final ProxyInfo networkProxy;
- synchronized ( this.networkProxyMap )
- {
- networkProxy = (ProxyInfo) this.networkProxyMap.get( connector.getProxyId() );
- }
-
- if ( log.isDebugEnabled() )
- {
- if ( networkProxy != null )
- {
- // TODO: move to proxyInfo.toString()
- String msg = "Using network proxy " + networkProxy.getHost() + ":" + networkProxy.getPort()
- + " to connect to remote repository " + remoteRepository.getURL();
- if ( networkProxy.getNonProxyHosts() != null )
- {
- msg += "; excluding hosts: " + networkProxy.getNonProxyHosts();
- }
- if ( StringUtils.isNotBlank( networkProxy.getUserName() ) )
- {
- msg += "; as user: " + networkProxy.getUserName();
- }
- log.debug( msg );
- }
- }
-
- AuthenticationInfo authInfo = null;
- String username = remoteRepository.getRepository().getUserName();
- String password = remoteRepository.getRepository().getPassword();
-
- if ( StringUtils.isNotBlank( username ) && StringUtils.isNotBlank( password ) )
- {
- log.debug( "Using username {} to connect to remote repository {}", username, remoteRepository.getURL() );
- authInfo = new AuthenticationInfo();
- authInfo.setUserName( username );
- authInfo.setPassword( password );
- }
-
- // Convert seconds to milliseconds
- int timeoutInMilliseconds = remoteRepository.getRepository().getTimeout() * 1000;
-
- // Set timeout
- wagon.setTimeout( timeoutInMilliseconds );
-
- try
- {
- Repository wagonRepository =
- new Repository( remoteRepository.getId(), remoteRepository.getURL().toString() );
- wagon.connect( wagonRepository, authInfo, networkProxy );
- connected = true;
- }
- catch ( ConnectionException e )
- {
- log.warn( "Could not connect to " + remoteRepository.getRepository().getName() + ": " + e.getMessage() );
- connected = false;
- }
- catch ( AuthenticationException e )
- {
- log.warn( "Could not connect to " + remoteRepository.getRepository().getName() + ": " + e.getMessage() );
- connected = false;
- }
-
- return connected;
- }
-
- /**
- * Tests whitelist and blacklist patterns against path.
- *
- * @param path the path to test.
- * @param patterns the list of patterns to check.
- * @return true if the path matches at least 1 pattern in the provided patterns list.
- */
- private boolean matchesPattern( String path, List<String> patterns )
- {
- if ( CollectionUtils.isEmpty( patterns ) )
- {
- return false;
- }
-
- if ( !path.startsWith( "/" ) )
- {
- path = "/" + path;
- }
-
- for ( String pattern : patterns )
- {
- if ( !pattern.startsWith( "/" ) )
- {
- pattern = "/" + pattern;
- }
-
- if ( SelectorUtils.matchPath( pattern, path, false ) )
- {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * TODO: Ensure that list is correctly ordered based on configuration. See MRM-477
- */
- public List<ProxyConnector> getProxyConnectors( ManagedRepositoryContent repository )
- {
- synchronized ( this.proxyConnectorMap )
- {
- List<ProxyConnector> ret = (List<ProxyConnector>) this.proxyConnectorMap.get( repository.getId() );
- if ( ret == null )
- {
- return Collections.emptyList();
- }
-
- Collections.sort( ret, ProxyConnectorOrderComparator.getInstance() );
- return ret;
- }
- }
-
- public void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue )
- {
- if ( ConfigurationNames.isNetworkProxy( propertyName )
- || ConfigurationNames.isManagedRepositories( propertyName )
- || ConfigurationNames.isRemoteRepositories( propertyName ) || ConfigurationNames.isProxyConnector(
- propertyName ) )
- {
- initConnectorsAndNetworkProxies();
- }
- }
-
- public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue )
- {
- /* do nothing */
- }
-
- public ArchivaConfiguration getArchivaConfiguration()
- {
- return archivaConfiguration;
- }
-
- public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
- {
- this.archivaConfiguration = archivaConfiguration;
- }
-
- public RepositoryContentFactory getRepositoryFactory()
- {
- return repositoryFactory;
- }
-
- public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
- {
- this.repositoryFactory = repositoryFactory;
- }
-
- public MetadataTools getMetadataTools()
- {
- return metadataTools;
- }
-
- public void setMetadataTools( MetadataTools metadataTools )
- {
- this.metadataTools = metadataTools;
- }
-
- public UrlFailureCache getUrlFailureCache()
- {
- return urlFailureCache;
- }
-
- public void setUrlFailureCache( UrlFailureCache urlFailureCache )
- {
- this.urlFailureCache = urlFailureCache;
- }
-
- public WagonFactory getWagonFactory()
- {
- return wagonFactory;
- }
-
- public void setWagonFactory( WagonFactory wagonFactory )
- {
- this.wagonFactory = wagonFactory;
- }
-
- public Map<String, PreDownloadPolicy> getPreDownloadPolicies()
- {
- return preDownloadPolicies;
- }
-
- public void setPreDownloadPolicies( Map<String, PreDownloadPolicy> preDownloadPolicies )
- {
- this.preDownloadPolicies = preDownloadPolicies;
- }
-
- public Map<String, PostDownloadPolicy> getPostDownloadPolicies()
- {
- return postDownloadPolicies;
- }
-
- public void setPostDownloadPolicies( Map<String, PostDownloadPolicy> postDownloadPolicies )
- {
- this.postDownloadPolicies = postDownloadPolicies;
- }
-
- public Map<String, DownloadErrorPolicy> getDownloadErrorPolicies()
- {
- return downloadErrorPolicies;
- }
-
- public void setDownloadErrorPolicies( Map<String, DownloadErrorPolicy> downloadErrorPolicies )
- {
- this.downloadErrorPolicies = downloadErrorPolicies;
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-/**
- * NotFoundException - thrown when the resource requested was not found on the remote repository.
- *
- * @version $Id$
- */
-public class NotFoundException
- extends ProxyException
-{
- public NotFoundException( String message, Throwable t )
- {
- super( message, t );
- }
-
- public NotFoundException( String message )
- {
- super( message );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-/**
- * <p>
- * NotModifiedException - thrown when the resource requested was found on the remote repository, but
- * the remote repository reported that the copy we have in our managed repository is newer than
- * the one present on the remote repository.
- * </p>
- * <p>
- * Similar in scope to the <code>HTTP 304 Not Modified</code> response code.
- * </p>
- *
- * @version $Id$
- */
-public class NotModifiedException
- extends ProxyException
-{
-
- public NotModifiedException( String message )
- {
- super( message );
- }
-
- public NotModifiedException( String message, Throwable t )
- {
- super( message, t );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.maven.archiva.repository.ManagedRepositoryContent;
-import org.apache.maven.archiva.repository.RemoteRepositoryContent;
-import org.apache.maven.archiva.repository.connector.RepositoryConnector;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * This represents a connector for a repository to repository proxy.
- *
- * @version $Id$
- */
-public class ProxyConnector
- implements RepositoryConnector
-{
- private ManagedRepositoryContent sourceRepository;
-
- private RemoteRepositoryContent targetRepository;
-
- private List<String> blacklist;
-
- private List<String> whitelist;
-
- private String proxyId;
-
- private int order;
-
- private Map<String, String> policies;
-
- private boolean disabled;
-
- public boolean isDisabled()
- {
- return disabled;
- }
-
- public void setDisabled(boolean disabled)
- {
- this.disabled = disabled;
- }
-
- public List<String> getBlacklist()
- {
- return blacklist;
- }
-
- public void setBlacklist( List<String> blacklist )
- {
- this.blacklist = blacklist;
- }
-
- public ManagedRepositoryContent getSourceRepository()
- {
- return sourceRepository;
- }
-
- public void setSourceRepository( ManagedRepositoryContent sourceRepository )
- {
- this.sourceRepository = sourceRepository;
- }
-
- public RemoteRepositoryContent getTargetRepository()
- {
- return targetRepository;
- }
-
- public void setTargetRepository( RemoteRepositoryContent targetRepository )
- {
- this.targetRepository = targetRepository;
- }
-
- public List<String> getWhitelist()
- {
- return whitelist;
- }
-
- public void setWhitelist( List<String> whitelist )
- {
- this.whitelist = whitelist;
- }
-
- public Map<String, String> getPolicies()
- {
- return policies;
- }
-
- public void setPolicies( Map<String, String> policies )
- {
- this.policies = policies;
- }
-
- public String getProxyId()
- {
- return proxyId;
- }
-
- public void setProxyId( String proxyId )
- {
- this.proxyId = proxyId;
- }
-
- @Override
- public String toString()
- {
- StringBuffer sb = new StringBuffer();
-
- sb.append( "ProxyConnector[\n" );
- sb.append( " source: [managed] " ).append( this.sourceRepository.getRepoRoot() ).append( "\n" );
- sb.append( " target: [remote] " ).append( this.targetRepository.getRepository().getUrl() ).append( "\n" );
- sb.append( " proxyId:" ).append( this.proxyId ).append( "\n" );
-
- Iterator<String> keys = this.policies.keySet().iterator();
- while ( keys.hasNext() )
- {
- String name = keys.next();
- sb.append( " policy[" ).append( name ).append( "]:" );
- sb.append( this.policies.get( name ) ).append( "\n" );
- }
-
- sb.append( "]" );
-
- return sb.toString();
- }
-
- public void setPolicy( String policyId, String policySetting )
- {
- this.policies.put( policyId, policySetting );
- }
-
- public int getOrder()
- {
- return order;
- }
-
- public void setOrder( int order )
- {
- this.order = order;
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import java.util.Comparator;
-
-/**
- * ProxyConnectorOrderComparator
- *
- * @version $Id$
- */
-public class ProxyConnectorOrderComparator
- implements Comparator<ProxyConnector>
-{
- private static ProxyConnectorOrderComparator INSTANCE = new ProxyConnectorOrderComparator();
-
- public static ProxyConnectorOrderComparator getInstance()
- {
- return INSTANCE;
- }
-
- public int compare( ProxyConnector o1, ProxyConnector o2 )
- {
- if ( o1 == null && o2 == null )
- {
- return 0;
- }
-
- // Ensure null goes to end of list.
- if ( o1 == null && o2 != null )
- {
- return 1;
- }
-
- if ( o1 != null && o2 == null )
- {
- return -1;
- }
-
- // Ensure 0 (unordered) goes to end of list.
- if ( o1.getOrder() == 0 && o2.getOrder() != 0 )
- {
- return 1;
- }
-
- if ( o1.getOrder() != 0 && o2.getOrder() == 0 )
- {
- return -1;
- }
-
- return o1.getOrder() - o2.getOrder();
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-/**
- */
-public class ProxyException
- extends Exception
-{
- public ProxyException( String message )
- {
- super( message );
- }
-
- public ProxyException( String message, Throwable t )
- {
- super( message, t );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.maven.archiva.model.ArtifactReference;
-import org.apache.maven.archiva.policies.ProxyDownloadException;
-import org.apache.maven.archiva.repository.ManagedRepositoryContent;
-
-import java.io.File;
-import java.util.List;
-
-/**
- * Handler for potential repository proxy connectors.
- *
- * @version $Id$
- */
-public interface RepositoryProxyConnectors
-{
- /**
- * Performs the artifact fetch operation against the target repositories
- * of the provided source repository.
- *
- * If the artifact is found, it is downloaded and placed into the source repository
- * filesystem.
- *
- * @param repository the source repository to use. (must be a managed repository)
- * @param artifact the artifact to fetch.
- * @return the file that was obtained, or null if no content was obtained
- * @throws ProxyDownloadException if there was a problem fetching the content from the target repositories.
- */
- public File fetchFromProxies( ManagedRepositoryContent repository, ArtifactReference artifact )
- throws ProxyDownloadException;
-
- /**
- * Performs the metadata fetch operation against the target repositories
- * of the provided source repository.
- *
- * If the metadata is found, it is downloaded and placed into the source repository
- * filesystem.
- *
- * @param repository the source repository to use. (must be a managed repository)
- * @param metadata the metadata to fetch.
- * @return the file that was obtained, or null if no content was obtained
- */
- public File fetchMetatadaFromProxies( ManagedRepositoryContent repository, String logicalPath );
-
- /**
- * Performs the fetch operation against the target repositories
- * of the provided source repository.
- *
- * @param repository the source repository to use. (must be a managed repository)
- * @param path the path of the resource to fetch
- * @return the file that was obtained, or null if no content was obtained
- */
- public File fetchFromProxies( ManagedRepositoryContent managedRepository, String path );
-
- /**
- * Get the List of {@link ProxyConnector} objects of the source repository.
- *
- * @param repository the source repository to look for.
- * @return the List of {@link ProxyConnector} objects.
- */
- public List<ProxyConnector> getProxyConnectors( ManagedRepositoryContent repository );
-
- /**
- * Tests to see if the provided repository is a source repository for
- * any {@link ProxyConnector} objects.
- *
- * @param repository the source repository to look for.
- * @return true if there are proxy connectors that use the provided
- * repository as a source repository.
- */
- public boolean hasProxies( ManagedRepositoryContent repository );
-}
default-lazy-init="true">
<context:annotation-config/>
- <context:component-scan base-package="org.apache.maven.archiva.proxy"/>
+ <context:component-scan base-package="org.apache.archiva.proxy"/>
</beans>
\ No newline at end of file
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import net.sf.ehcache.CacheManager;
+import org.apache.archiva.admin.model.beans.ManagedRepository;
+import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
+import org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin;
+import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.maven.archiva.configuration.ArchivaConfiguration;
+import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
+import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
+import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.PropagateErrorsDownloadPolicy;
+import org.apache.maven.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.apache.maven.archiva.repository.ManagedRepositoryContent;
+import org.apache.maven.wagon.Wagon;
+import org.codehaus.plexus.util.FileUtils;
+import org.easymock.ArgumentsMatcher;
+import org.easymock.MockControl;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.inject.Inject;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Locale;
+
+import static org.junit.Assert.*;
+
+/**
+ * AbstractProxyTestCase
+ *
+ * @version $Id$
+ */
+@RunWith( SpringJUnit4ClassRunner.class )
+@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
+public abstract class AbstractProxyTestCase
+{
+ @Inject
+ protected ApplicationContext applicationContext;
+
+ protected static final String ID_LEGACY_PROXIED = "legacy-proxied";
+
+ protected static final String ID_PROXIED1 = "proxied1";
+
+ protected static final String ID_PROXIED1_TARGET = "proxied1-target";
+
+ protected static final String ID_PROXIED2 = "proxied2";
+
+ protected static final String ID_PROXIED2_TARGET = "proxied2-target";
+
+ protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
+
+ protected static final String ID_LEGACY_MANAGED = "legacy-managed-repository";
+
+ protected static final String REPOPATH_PROXIED_LEGACY = "src/test/repositories/legacy-proxied";
+
+ protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
+
+ protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
+
+ protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
+
+ protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
+
+ protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
+
+ // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
+
+ protected static final String REPOPATH_LEGACY_MANAGED = "src/test/repositories/legacy-managed";
+
+ protected static final String REPOPATH_LEGACY_MANAGED_TARGET = "target/test-repository/legacy-managed";
+
+ protected MockControl wagonMockControl;
+
+ protected Wagon wagonMock;
+
+
+ protected RepositoryProxyConnectors proxyHandler;
+
+ protected ManagedRepositoryContent managedDefaultRepository;
+
+ protected File managedDefaultDir;
+
+ protected ManagedRepositoryContent managedLegacyRepository;
+
+ protected File managedLegacyDir;
+
+ protected MockConfiguration config;
+
+ protected Logger log = LoggerFactory.getLogger( getClass() );
+
+ WagonDelegate delegate;
+
+ @Inject
+ protected ManagedRepositoryAdmin managedRepositoryAdmin;
+
+ @Inject
+ PlexusSisuBridge plexusSisuBridge;
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ config =
+ (MockConfiguration) applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
+
+ config.getConfiguration().setManagedRepositories( new ArrayList<ManagedRepositoryConfiguration>() );
+ config.getConfiguration().setRemoteRepositories( new ArrayList<RemoteRepositoryConfiguration>() );
+ config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() );
+
+ // Setup source repository (using default layout)
+ String name = getClass().getSimpleName();
+ String repoPath = "target/test-repository/managed/" + name;
+ File repoLocation = new File( repoPath );
+
+ managedDefaultRepository =
+ createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath, "default" );
+
+ managedDefaultDir = new File( managedDefaultRepository.getRepoRoot() );
+
+ ManagedRepository repoConfig = managedDefaultRepository.getRepository();
+
+ ( (DefaultManagedRepositoryAdmin) applicationContext.getBean(
+ ManagedRepositoryAdmin.class ) ).setArchivaConfiguration( config );
+
+ applicationContext.getBean( ManagedRepositoryAdmin.class ).addManagedRepository( repoConfig, false, null );
+ //config.getConfiguration().addManagedRepository( repoConfig );
+
+ // Setup source repository (using legacy layout)
+ repoLocation = new File( REPOPATH_LEGACY_MANAGED_TARGET );
+ if ( repoLocation.exists() )
+ {
+ FileUtils.deleteDirectory( repoLocation );
+ }
+ copyDirectoryStructure( new File( REPOPATH_LEGACY_MANAGED ), repoLocation );
+
+ managedLegacyRepository =
+ createRepository( ID_LEGACY_MANAGED, "Legacy Managed Repository", REPOPATH_LEGACY_MANAGED_TARGET,
+ "legacy" );
+
+ managedLegacyDir = new File( managedLegacyRepository.getRepoRoot() );
+
+ repoConfig = managedLegacyRepository.getRepository();
+
+ //config.getConfiguration().addManagedRepository( repoConfig );
+ applicationContext.getBean( ManagedRepositoryAdmin.class ).addManagedRepository( repoConfig, false, null );
+
+ // Setup target (proxied to) repository.
+ saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1",
+ new File( REPOPATH_PROXIED1 ).toURL().toExternalForm(), "default" );
+
+ // Setup target (proxied to) repository.
+ saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2",
+ new File( REPOPATH_PROXIED2 ).toURL().toExternalForm(), "default" );
+
+ // Setup target (proxied to) repository using legacy layout.
+ saveRemoteRepositoryConfig( ID_LEGACY_PROXIED, "Proxied Legacy Repository",
+ new File( REPOPATH_PROXIED_LEGACY ).toURL().toExternalForm(), "legacy" );
+
+ // Setup the proxy handler.
+ //proxyHandler = applicationContext.getBean (RepositoryProxyConnectors) lookup( RepositoryProxyConnectors.class.getName() );
+
+ proxyHandler = applicationContext.getBean( "repositoryProxyConnectors#test", RepositoryProxyConnectors.class );
+
+ // Setup the wagon mock.
+ wagonMockControl = MockControl.createNiceControl( Wagon.class );
+ wagonMock = (Wagon) wagonMockControl.getMock();
+
+ delegate = (WagonDelegate) plexusSisuBridge.lookup( Wagon.class, "test" );
+
+ delegate.setDelegate( wagonMock );
+
+ CacheManager.getInstance().clearAll();
+
+ log.info( "\n.\\ " + name + "() \\._________________________________________\n" );
+ }
+
+ protected static final ArgumentsMatcher customWagonGetIfNewerMatcher = new ArgumentsMatcher()
+ {
+
+ public boolean matches( Object[] expected, Object[] actual )
+ {
+ if ( expected.length < 1 || actual.length < 1 )
+ {
+ return false;
+ }
+ return MockControl.ARRAY_MATCHER.matches( ArrayUtils.remove( expected, 1 ),
+ ArrayUtils.remove( actual, 1 ) );
+ }
+
+ public String toString( Object[] arguments )
+ {
+ return ArrayUtils.toString( arguments );
+ }
+ };
+
+ protected static final ArgumentsMatcher customWagonGetMatcher = new ArgumentsMatcher()
+ {
+
+ public boolean matches( Object[] expected, Object[] actual )
+ {
+ if ( expected.length == 2 && actual.length == 2 )
+ {
+ if ( expected[0] == null && actual[0] == null )
+ {
+ return true;
+ }
+
+ if ( expected[0] == null )
+ {
+ return actual[0] == null;
+ }
+
+ if ( actual[0] == null )
+ {
+ return expected[0] == null;
+ }
+
+ return expected[0].equals( actual[0] );
+ }
+ return false;
+ }
+
+ public String toString( Object[] arguments )
+ {
+ return ArrayUtils.toString( arguments );
+ }
+ };
+
+
+ protected void assertChecksums( File expectedFile, String expectedSha1Contents, String expectedMd5Contents )
+ throws Exception
+ {
+ File sha1File = new File( expectedFile.getAbsolutePath() + ".sha1" );
+ File md5File = new File( expectedFile.getAbsolutePath() + ".md5" );
+
+ if ( expectedSha1Contents == null )
+ {
+ assertFalse( "SHA1 File should NOT exist: " + sha1File.getPath(), sha1File.exists() );
+ }
+ else
+ {
+ assertTrue( "SHA1 File should exist: " + sha1File.getPath(), sha1File.exists() );
+ String actualSha1Contents = readChecksumFile( sha1File );
+ assertEquals( "SHA1 File contents: " + sha1File.getPath(), expectedSha1Contents, actualSha1Contents );
+ }
+
+ if ( expectedMd5Contents == null )
+ {
+ assertFalse( "MD5 File should NOT exist: " + md5File.getPath(), md5File.exists() );
+ }
+ else
+ {
+ assertTrue( "MD5 File should exist: " + md5File.getPath(), md5File.exists() );
+ String actualMd5Contents = readChecksumFile( md5File );
+ assertEquals( "MD5 File contents: " + md5File.getPath(), expectedMd5Contents, actualMd5Contents );
+ }
+ }
+
+ protected void assertFileEquals( File expectedFile, File actualFile, File sourceFile )
+ throws Exception
+ {
+ assertNotNull( "Expected File should not be null.", expectedFile );
+ assertNotNull( "Actual File should not be null.", actualFile );
+
+ assertTrue( "Check actual file exists.", actualFile.exists() );
+ assertEquals( "Check filename path is appropriate.", expectedFile.getCanonicalPath(),
+ actualFile.getCanonicalPath() );
+ assertEquals( "Check file path matches.", expectedFile.getAbsolutePath(), actualFile.getAbsolutePath() );
+
+ String expectedContents = org.apache.commons.io.FileUtils.readFileToString( sourceFile, null );
+ String actualContents = org.apache.commons.io.FileUtils.readFileToString( actualFile, null );
+ assertEquals( "Check file contents.", expectedContents, actualContents );
+ }
+
+ protected void assertNotDownloaded( File downloadedFile )
+ {
+ assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
+ }
+
+ @SuppressWarnings( "unchecked" )
+ protected void assertNoTempFiles( File expectedFile )
+ {
+ File workingDir = expectedFile.getParentFile();
+ if ( ( workingDir == null ) || !workingDir.isDirectory() )
+ {
+ return;
+ }
+
+ Collection<File> tmpFiles =
+ org.apache.commons.io.FileUtils.listFiles( workingDir, new String[]{ "tmp" }, false );
+ if ( !tmpFiles.isEmpty() )
+ {
+ StringBuffer emsg = new StringBuffer();
+ emsg.append( "Found Temp Files in dir: " ).append( workingDir.getPath() );
+ for ( File tfile : tmpFiles )
+ {
+ emsg.append( "\n " ).append( tfile.getName() );
+ }
+ fail( emsg.toString() );
+ }
+ }
+
+ /**
+ * A faster recursive copy that omits .svn directories.
+ *
+ * @param sourceDirectory the source directory to copy
+ * @param destDirectory the target location
+ * @throws java.io.IOException if there is a copying problem
+ * @todo get back into plexus-utils, share with converter module
+ */
+ protected void copyDirectoryStructure( File sourceDirectory, File destDirectory )
+ throws IOException
+ {
+ if ( !sourceDirectory.exists() )
+ {
+ throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." );
+ }
+
+ File[] files = sourceDirectory.listFiles();
+
+ String sourcePath = sourceDirectory.getAbsolutePath();
+
+ for ( int i = 0; i < files.length; i++ )
+ {
+ File file = files[i];
+
+ String dest = file.getAbsolutePath();
+
+ dest = dest.substring( sourcePath.length() + 1 );
+
+ File destination = new File( destDirectory, dest );
+
+ if ( file.isFile() )
+ {
+ destination = destination.getParentFile();
+
+ org.apache.commons.io.FileUtils.copyFile( file, new File( destination, file.getName() ), false );
+ // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
+ //FileUtils.copyFileToDirectory( file, destination );
+ }
+ else if ( file.isDirectory() )
+ {
+ if ( !".svn".equals( file.getName() ) )
+ {
+ if ( !destination.exists() && !destination.mkdirs() )
+ {
+ throw new IOException(
+ "Could not create destination directory '" + destination.getAbsolutePath() + "'." );
+ }
+
+ copyDirectoryStructure( file, destination );
+ }
+ }
+ else
+ {
+ throw new IOException( "Unknown file type: " + file.getAbsolutePath() );
+ }
+ }
+ }
+
+ protected ManagedRepositoryContent createManagedLegacyRepository()
+ throws Exception
+ {
+ return createRepository( "testManagedLegacyRepo", "Test Managed (Legacy) Repository",
+ "src/test/repositories/legacy-managed", "legacy" );
+ }
+
+ protected ManagedRepositoryContent createProxiedLegacyRepository()
+ throws Exception
+ {
+ return createRepository( "testProxiedLegacyRepo", "Test Proxied (Legacy) Repository",
+ "src/test/repositories/legacy-proxied", "legacy" );
+ }
+
+ protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
+ throws Exception
+ {
+ ManagedRepository repo = new ManagedRepository();
+ repo.setId( id );
+ repo.setName( name );
+ repo.setLocation( path );
+ repo.setLayout( layout );
+
+ ManagedRepositoryContent repoContent =
+ applicationContext.getBean( "managedRepositoryContent#" + layout, ManagedRepositoryContent.class );
+ repoContent.setRepository( repo );
+ return repoContent;
+ }
+
+ /**
+ * Read the first line from the checksum file, and return it (trimmed).
+ */
+ protected String readChecksumFile( File checksumFile )
+ throws Exception
+ {
+ FileReader freader = null;
+ BufferedReader buf = null;
+
+ try
+ {
+ freader = new FileReader( checksumFile );
+ buf = new BufferedReader( freader );
+ return buf.readLine();
+ }
+ finally
+ {
+ if ( buf != null )
+ {
+ buf.close();
+ }
+
+ if ( freader != null )
+ {
+ freader.close();
+ }
+ }
+ }
+
+ protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
+ {
+ saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
+ CachedFailuresPolicy.NO, disabled );
+ }
+
+ protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
+ String snapshotPolicy, String cacheFailuresPolicy, boolean disabled )
+ {
+ saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
+ PropagateErrorsDownloadPolicy.QUEUE, disabled );
+ }
+
+ protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
+ String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
+ boolean disabled )
+ {
+ saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
+ errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
+ }
+
+ protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
+ String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
+ String errorOnUpdatePolicy, boolean disabled )
+ {
+ ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
+ connectorConfig.setSourceRepoId( sourceRepoId );
+ connectorConfig.setTargetRepoId( targetRepoId );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy );
+ connectorConfig.setDisabled( disabled );
+
+ int count = config.getConfiguration().getProxyConnectors().size();
+ config.getConfiguration().addProxyConnector( connectorConfig );
+
+ // Proper Triggering ...
+ String prefix = "proxyConnectors.proxyConnector(" + count + ")";
+ config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
+ config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
+ config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
+ config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
+ config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
+ config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
+ config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
+ config.triggerChange( prefix + ".policies.propagate-errors",
+ connectorConfig.getPolicy( "propagate-errors", "" ) );
+ config.triggerChange( prefix + ".policies.propagate-errors-on-update",
+ connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
+ }
+
+ protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
+ {
+ ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
+
+ repoConfig.setId( id );
+ repoConfig.setName( name );
+ repoConfig.setLayout( layout );
+
+ repoConfig.setLocation( path );
+
+ int count = config.getConfiguration().getManagedRepositories().size();
+ config.getConfiguration().addManagedRepository( repoConfig );
+
+ String prefix = "managedRepositories.managedRepository(" + count + ")";
+ config.triggerChange( prefix + ".id", repoConfig.getId() );
+ config.triggerChange( prefix + ".name", repoConfig.getName() );
+ config.triggerChange( prefix + ".location", repoConfig.getLocation() );
+ config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
+ }
+
+ protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
+ {
+ RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
+
+ repoConfig.setId( id );
+ repoConfig.setName( name );
+ repoConfig.setLayout( layout );
+ repoConfig.setUrl( url );
+
+ int count = config.getConfiguration().getRemoteRepositories().size();
+ config.getConfiguration().addRemoteRepository( repoConfig );
+
+ String prefix = "remoteRepositories.remoteRepository(" + count + ")";
+ config.triggerChange( prefix + ".id", repoConfig.getId() );
+ config.triggerChange( prefix + ".name", repoConfig.getName() );
+ config.triggerChange( prefix + ".url", repoConfig.getUrl() );
+ config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
+ }
+
+ protected File saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
+ throws IOException
+ {
+ File repoLocation = new File( targetPath );
+ FileUtils.deleteDirectory( repoLocation );
+ copyDirectoryStructure( new File( originalPath ), repoLocation );
+
+ saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
+
+ return repoLocation;
+ }
+
+
+ /**
+ * Copy the specified resource directory from the src/test/repository/managed/ to
+ * the testable directory under target/test-repository/managed/${testName}/
+ *
+ * @param resourcePath
+ * @throws IOException
+ */
+ protected void setupTestableManagedRepository( String resourcePath )
+ throws IOException
+ {
+ String resourceDir = resourcePath;
+
+ if ( !resourcePath.endsWith( "/" ) )
+ {
+ int idx = resourcePath.lastIndexOf( '/' );
+ resourceDir = resourcePath.substring( 0, idx );
+ }
+
+ File sourceRepoDir = new File( REPOPATH_DEFAULT_MANAGED );
+ File sourceDir = new File( sourceRepoDir, resourceDir );
+
+ File destRepoDir = managedDefaultDir;
+ File destDir = new File( destRepoDir, resourceDir );
+
+ // Cleanout destination dirs.
+ if ( destDir.exists() )
+ {
+ FileUtils.deleteDirectory( destDir );
+ }
+
+ // Make the destination dir.
+ destDir.mkdirs();
+
+ // Test the source dir.
+ if ( !sourceDir.exists() )
+ {
+ // This is just a warning.
+ System.err.println(
+ "[WARN] Skipping setup of testable managed repository, source dir does not exist: " + sourceDir );
+ }
+ else
+ {
+
+ // Test that the source is a dir.
+ if ( !sourceDir.isDirectory() )
+ {
+ fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
+ }
+
+ // Copy directory structure.
+ copyDirectoryStructure( sourceDir, destDir );
+ }
+ }
+
+ protected void setManagedNewerThanRemote( File managedFile, File remoteFile )
+ {
+ setManagedNewerThanRemote( managedFile, remoteFile, 55000 );
+ }
+
+ protected void setManagedNewerThanRemote( File managedFile, File remoteFile, long time )
+ {
+ assertTrue( "Managed File should exist: ", managedFile.exists() );
+ assertTrue( "Remote File should exist: ", remoteFile.exists() );
+
+ managedFile.setLastModified( remoteFile.lastModified() + time );
+
+ assertTrue( managedFile.lastModified() > remoteFile.lastModified() );
+ }
+
+ protected void setManagedOlderThanRemote( File managedFile, File remoteFile )
+ {
+ setManagedOlderThanRemote( managedFile, remoteFile, 55000 );
+ }
+
+ protected void setManagedOlderThanRemote( File managedFile, File remoteFile, long time )
+ {
+ assertTrue( "Managed File should exist: ", managedFile.exists() );
+ assertTrue( "Remote File should exist: ", remoteFile.exists() );
+
+ managedFile.setLastModified( remoteFile.lastModified() - time );
+
+ assertTrue( managedFile.lastModified() < remoteFile.lastModified() );
+
+ }
+
+ protected void assertNotModified( File file, long expectedModificationTime )
+ {
+ assertEquals( "File <" + file.getAbsolutePath() + "> not have been modified.", expectedModificationTime,
+ file.lastModified() );
+ }
+
+ protected void assertNotExistsInManagedLegacyRepo( File file )
+ throws Exception
+ {
+ String managedLegacyPath = managedLegacyDir.getCanonicalPath();
+ String testFile = file.getCanonicalPath();
+
+ assertTrue(
+ "Unit Test Failure: File <" + testFile + "> should be have been defined within the legacy managed path of <"
+ + managedLegacyPath + ">", testFile.startsWith( managedLegacyPath ) );
+
+ assertFalse( "File < " + testFile + "> should not exist in managed legacy repository.", file.exists() );
+ }
+
+ protected void assertNotExistsInManagedDefaultRepo( File file )
+ throws Exception
+ {
+ String managedDefaultPath = managedDefaultDir.getCanonicalPath();
+ String testFile = file.getCanonicalPath();
+
+ assertTrue( "Unit Test Failure: File <" + testFile
+ + "> should be have been defined within the managed default path of <" + managedDefaultPath
+ + ">", testFile.startsWith( managedDefaultPath ) );
+
+ assertFalse( "File < " + testFile + "> should not exist in managed default repository.", file.exists() );
+ }
+
+ protected static Date getFutureDate()
+ throws ParseException
+ {
+ Calendar cal = Calendar.getInstance();
+ cal.add( Calendar.YEAR, 1 );
+ return cal.getTime();
+ }
+
+ protected static Date getPastDate()
+ throws ParseException
+ {
+ return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.archiva.common.utils.PathUtil;
+import org.apache.maven.archiva.model.ArtifactReference;
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.apache.maven.archiva.policies.urlcache.UrlFailureCache;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.junit.Test;
+
+import java.io.File;
+import javax.inject.Inject;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * CacheFailuresTransferTest
+ *
+ * @version $Id$
+ */
+public class CacheFailuresTransferTest
+ extends AbstractProxyTestCase
+{
+ // TODO: test some hard failures (eg TransferFailedException)
+ // TODO: test the various combinations of fetchFrom* (note: need only test when caching is enabled)
+
+ @Test
+ public void testGetWithCacheFailuresOn()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ File expectedFile = new File( managedDefaultDir.getAbsoluteFile(), path );
+ setupTestableManagedRepository( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Configure Repository (usually done within archiva.xml configuration)
+ saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "test://bad.machine.com/repo/", "default" );
+ saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "test://bad.machine.com/anotherrepo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
+
+ wagonMock.get( path, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
+
+ wagonMockControl.setMatcher( customWagonGetMatcher );
+
+ wagonMockControl.setThrowable( new ResourceDoesNotExistException( "resource does not exist." ), 2 );
+
+ wagonMockControl.replay();
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ wagonMockControl.verify();
+
+ // Second attempt to download same artifact use cache
+ wagonMockControl.reset();
+ wagonMockControl.replay();
+ downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+ wagonMockControl.verify();
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetWithCacheFailuresOff()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ File expectedFile = new File( managedDefaultDir.getAbsoluteFile(), path );
+ setupTestableManagedRepository( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Configure Repository (usually done within archiva.xml configuration)
+ saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "test://bad.machine.com/repo/", "default" );
+ saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "test://bad.machine.com/anotherrepo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ wagonMock.get( path, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
+
+ wagonMockControl.setMatcher( customWagonGetMatcher );
+ wagonMockControl.setThrowable( new ResourceDoesNotExistException( "resource does not exist." ), 2 );
+
+ wagonMockControl.replay();
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ wagonMockControl.verify();
+
+ // Second attempt to download same artifact DOES NOT use cache
+ wagonMockControl.reset();
+ wagonMock.get( path, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
+
+ wagonMockControl.setMatcher( customWagonGetMatcher );
+ wagonMockControl.setThrowable( new ResourceDoesNotExistException( "resource does not exist." ), 2 );
+ wagonMockControl.replay();
+
+ downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ wagonMockControl.verify();
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetWhenInBothProxiedButFirstCacheFailure()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ setupTestableManagedRepository( path );
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ expectedFile.delete();
+ assertFalse( expectedFile.exists() );
+
+ String url = PathUtil.toUrl( REPOPATH_PROXIED1 + "/" + path );
+
+ // Intentionally set failure on url in proxied1 (for test)
+ UrlFailureCache failurlCache = lookupUrlFailureCache();
+ failurlCache.cacheFailure( url );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
+ saveConnector( ID_DEFAULT_MANAGED, "proxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ // Validate that file actually came from proxied2 (as intended).
+ File proxied2File = new File( REPOPATH_PROXIED2, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied2File );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Inject
+ UrlFailureCache urlFailureCache;
+
+ protected UrlFailureCache lookupUrlFailureCache()
+ throws Exception
+ {
+ //UrlFailureCache urlFailureCache = (UrlFailureCache) lookup( "urlFailureCache" );
+ assertNotNull( "URL Failure Cache cannot be null.", urlFailureCache );
+ return urlFailureCache;
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.commons.io.FileUtils;
+import org.apache.maven.archiva.model.ArtifactReference;
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+
+/**
+ * ChecksumTransferTest
+ *
+ * @version $Id$
+ */
+public class ChecksumTransferTest
+ extends AbstractProxyTestCase
+{
+ @Test
+ public void testGetChecksumWhenConnectorIsDisabled()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-right/1.0/get-checksum-both-right-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, true );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNull( downloadedFile );
+ }
+
+ @Test
+ public void testGetChecksumBothCorrect()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-right/1.0/get-checksum-both-right-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "066d76e459f7782c312c31e8a11b3c0f1e3e43a7 *get-checksum-both-right-1.0.jar",
+ "e58f30c6a150a2e843552438d18e15cb *get-checksum-both-right-1.0.jar" );
+ }
+
+ @Test
+ public void testGetChecksumCorrectSha1NoMd5()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-only/1.0/get-checksum-sha1-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "748a3a013bf5eacf2bbb40a2ac7d37889b728837 *get-checksum-sha1-only-1.0.jar",
+ null );
+ }
+
+ @Test
+ public void testGetChecksumNoSha1CorrectMd5()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, null, "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
+ }
+
+ @Test
+ public void testGetWithNoChecksumsUsingIgnoredSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, null, null );
+ }
+
+ @Test
+ public void testGetChecksumBadSha1BadMd5IgnoredSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
+ }
+
+ @Test
+ public void testGetChecksumBadSha1BadMd5FailSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertChecksums( expectedFile, null, null );
+ }
+
+ @Test
+ public void testGetChecksumBadSha1BadMd5FixSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "4ec20a12dc91557330bd0b39d1805be5e329ae56 get-checksum-both-bad-1.0.jar",
+ "a292491a35925465e693a44809a078b5 get-checksum-both-bad-1.0.jar" );
+ }
+
+ @Test
+ public void testGetChecksumCorrectSha1BadMd5UsingFailSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertChecksums( expectedFile, null, null );
+ }
+
+ @Test
+ public void testGetChecksumNoSha1CorrectMd5UsingFailSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ // This is a success situation. No SHA1 with a Good MD5.
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, null, "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
+ }
+
+ @Test
+ public void testGetWithNoChecksumsUsingFailSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertChecksums( expectedFile, null, null );
+ }
+
+ @Test
+ public void testGetChecksumCorrectSha1BadMd5UsingIgnoredSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "3dd1a3a57b807d3ef3fbc6013d926c891cbb8670 *get-checksum-sha1-bad-md5-1.0.jar",
+ "invalid checksum file" );
+ }
+
+ @Test
+ public void testGetChecksumCorrectSha1BadMd5UsingFixSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "3dd1a3a57b807d3ef3fbc6013d926c891cbb8670 *get-checksum-sha1-bad-md5-1.0.jar",
+ "c35f3b76268b73a4ba617f6f275c49ab get-checksum-sha1-bad-md5-1.0.jar" );
+ }
+
+ @Test
+ public void testGetChecksumNoSha1CorrectMd5UsingFixSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "71f7dc3f72053a3f2d9fdd6fef9db055ef957ffb get-checksum-md5-only-1.0.jar",
+ "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
+ }
+
+ @Test
+ public void testGetWithNoChecksumsUsingFixSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "1f12821c5e43e1a0b76b9564a6ddb0548ccb9486 get-default-layout-1.0.jar",
+ "3f7341545f21226b6f49a3c2704cb9be get-default-layout-1.0.jar" );
+ }
+
+ @Test
+ public void testGetChecksumNotFoundOnRemote()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-checksum-sha1-only/1.0/get-checksum-sha1-only-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ FileUtils.deleteDirectory( expectedFile.getParentFile() );
+ assertFalse( expectedFile.getParentFile().exists() );
+ assertFalse( expectedFile.exists() );
+
+ saveRemoteRepositoryConfig( "badproxied", "Bad Proxied", "test://bad.machine.com/repo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ wagonMock.get( path, new File( expectedFile.getAbsolutePath() + ".tmp" ) );
+ wagonMockControl.setMatcher( customWagonGetMatcher );
+ wagonMockControl.setVoidCallable();
+ wagonMock.get( path + ".sha1", new File( expectedFile.getAbsolutePath() + ".sha1.tmp" ) );
+ wagonMockControl.setMatcher( customWagonGetMatcher );
+ wagonMockControl.setVoidCallable();
+ wagonMock.get( path + ".md5", new File( expectedFile.getAbsolutePath() + ".md5.tmp" ) );
+ wagonMockControl.setMatcher( customWagonGetMatcher );
+ wagonMockControl.setThrowable( new ResourceDoesNotExistException( "Resource does not exist." ) );
+ wagonMockControl.replay();
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ wagonMockControl.verify();
+
+ // Do what the mock doesn't do.
+ String proxyPath = new File( REPOPATH_PROXIED1, path ).getAbsolutePath();
+ String localPath = new File( managedDefaultDir, path ).getAbsolutePath();
+ FileUtils.copyFile( new File( proxyPath ), new File( localPath ) );
+ FileUtils.copyFile( new File( proxyPath + ".sha1" ), new File( localPath + ".sha1" ) );
+
+ // Test results.
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "748a3a013bf5eacf2bbb40a2ac7d37889b728837 *get-checksum-sha1-only-1.0.jar",
+ null );
+ }
+
+ @Test
+ public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingIgnoredSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, path );
+
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ // There are no hashcodes on the proxy side to download, hence the local ones should remain invalid.
+ assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
+ }
+
+ @Test
+ public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingFailSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, path );
+
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ // There are no hashcodes on the proxy side to download.
+ // The FAIL policy will delete the checksums as bad.
+
+ assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
+ }
+
+ @Test
+ public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingFixSetting()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, path );
+
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+ assertChecksums( expectedFile, "96a08dc80a108cba8efd3b20aec91b32a0b2cbd4 get-bad-local-checksum-1.0.jar",
+ "46fdd6ca55bf1d7a7eb0c858f41e0ccd get-bad-local-checksum-1.0.jar" );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.PropagateErrorsDownloadPolicy;
+import org.apache.maven.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
+import org.apache.maven.archiva.policies.ProxyDownloadException;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.apache.maven.archiva.repository.layout.LayoutException;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.apache.maven.wagon.TransferFailedException;
+import org.apache.maven.wagon.authorization.AuthorizationException;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.*;
+
+/**
+ * ErrorHandlingTest
+ *
+ * @version $Id$
+ */
+public class ErrorHandlingTest
+ extends AbstractProxyTestCase
+{
+ private static final String PATH_IN_BOTH_REMOTES_NOT_LOCAL =
+ "org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
+
+ private static final String PATH_IN_BOTH_REMOTES_AND_LOCAL =
+ "org/apache/maven/test/get-on-multiple-repos/1.0/get-on-multiple-repos-1.0.pom";
+
+ private static final String ID_MOCKED_PROXIED1 = "badproxied1";
+
+ private static final String NAME_MOCKED_PROXIED1 = "Bad Proxied 1";
+
+ private static final String ID_MOCKED_PROXIED2 = "badproxied2";
+
+ private static final String NAME_MOCKED_PROXIED2 = "Bad Proxied 2";
+
+ @Test
+ public void testPropagateErrorImmediatelyWithErrorThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorImmediatelyWithNotFoundThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
+ }
+
+ @Test
+ public void testPropagateErrorImmediatelyWithSuccessThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorImmediatelyWithNotFoundThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithErrorThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithSuccessThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithNotFoundThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithErrorThenNotFound()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithErrorThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmFailures( path, new String[]{ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2} );
+ }
+
+ @Test
+ public void testPropagateErrorAtEndWithNotFoundThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
+ }
+
+ @Test
+ public void testIgnoreErrorWithErrorThenSuccess()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
+ }
+
+ @Test
+ public void testIgnoreErrorWithSuccessThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
+
+ confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
+ }
+
+ @Test
+ public void testIgnoreErrorWithNotFoundThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testIgnoreErrorWithErrorThenNotFound()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ simulateGetError( path, expectedFile, createResourceNotFoundException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testIgnoreErrorWithErrorThenError()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysQueueArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysQueueArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysIgnoreArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testPropagateOnUpdateAlwaysIgnoreArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ assertTrue( expectedFile.exists() );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ assertTrue( expectedFile.exists() );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentQueueArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentQueueArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ assertTrue( expectedFile.exists() );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentIgnoreArtifactNotPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetError( path, expectedFile, createTransferException() );
+ simulateGetError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ }
+
+ @Test
+ public void testPropagateOnUpdateNotPresentIgnoreArtifactPresent()
+ throws Exception
+ {
+ String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
+ File expectedFile = setupRepositoriesWithLocalFilePresent( path );
+
+ createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+ createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+ simulateGetIfNewerError( path, expectedFile, createTransferException() );
+
+ confirmNotDownloadedNoError( path );
+ assertTrue( expectedFile.exists() );
+ }
+
+ // ------------------------------------------
+ // HELPER METHODS
+ // ------------------------------------------
+
+ private void createMockedProxyConnector( String id, String name, String errorPolicy )
+ {
+ saveRemoteRepositoryConfig( id, name, "test://bad.machine.com/repo/", "default" );
+ saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
+ CachedFailuresPolicy.NO, errorPolicy, false );
+ }
+
+ private void createMockedProxyConnector( String id, String name, String errorPolicy, String errorOnUpdatePolicy )
+ {
+ saveRemoteRepositoryConfig( id, name, "test://bad.machine.com/repo/", "default" );
+ saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
+ CachedFailuresPolicy.NO, errorPolicy, errorOnUpdatePolicy, false );
+ }
+
+ private File setupRepositoriesWithLocalFileNotPresent( String path )
+ throws Exception
+ {
+ setupTestableManagedRepository( path );
+
+ File file = new File( managedDefaultDir, path );
+
+ assertNotExistsInManagedDefaultRepo( file );
+
+ return file;
+ }
+
+ private File setupRepositoriesWithLocalFilePresent( String path )
+ throws Exception
+ {
+ setupTestableManagedRepository( path );
+
+ File file = new File( managedDefaultDir, path );
+
+ assertTrue( file.exists() );
+
+ return file;
+ }
+
+ private void simulateGetError( String path, File expectedFile, Exception throwable )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ wagonMock.get( path, createExpectedTempFile( expectedFile ) );
+ wagonMockControl.setMatcher(customWagonGetMatcher);
+ wagonMockControl.setThrowable( throwable, 1 );
+ }
+
+ private void simulateGetIfNewerError( String path, File expectedFile, TransferFailedException exception )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ wagonMock.getIfNewer( path, createExpectedTempFile( expectedFile ), expectedFile.lastModified() );
+ wagonMockControl.setMatcher(customWagonGetIfNewerMatcher);
+ wagonMockControl.setThrowable( exception, 1 );
+ }
+
+ private File createExpectedTempFile( File expectedFile )
+ {
+ return new File( managedDefaultDir, expectedFile.getName() + ".tmp" ).getAbsoluteFile();
+ }
+
+ private void confirmSingleFailure( String path, String id )
+ throws LayoutException
+ {
+ confirmFailures( path, new String[]{id} );
+ }
+
+ private void confirmFailures( String path, String[] ids )
+ throws LayoutException
+ {
+ wagonMockControl.replay();
+
+ // Attempt the proxy fetch.
+ File downloadedFile = null;
+ try
+ {
+ downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository,
+ managedDefaultRepository.toArtifactReference( path ) );
+ fail( "Proxy should not have succeeded" );
+ }
+ catch ( ProxyDownloadException e )
+ {
+ assertEquals( ids.length, e.getFailures().size() );
+ for ( String id : ids )
+ {
+ assertTrue( e.getFailures().keySet().contains( id ) );
+ }
+ }
+
+ wagonMockControl.verify();
+
+ assertNotDownloaded( downloadedFile );
+ }
+
+ private void confirmSuccess( String path, File expectedFile, String basedir )
+ throws Exception
+ {
+ File downloadedFile = performDownload( path );
+
+ File proxied1File = new File( basedir, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ }
+
+ private void confirmNotDownloadedNoError( String path )
+ throws Exception
+ {
+ File downloadedFile = performDownload( path );
+
+ assertNotDownloaded( downloadedFile );
+ }
+
+ private File performDownload( String path )
+ throws ProxyDownloadException, LayoutException
+ {
+ wagonMockControl.replay();
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository,
+ managedDefaultRepository.toArtifactReference( path ) );
+
+ wagonMockControl.verify();
+ return downloadedFile;
+ }
+
+ private static TransferFailedException createTransferException()
+ {
+ return new TransferFailedException( "test download exception" );
+ }
+
+ private static ResourceDoesNotExistException createResourceNotFoundException()
+ {
+ return new ResourceDoesNotExistException( "test download not found" );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.archiva.admin.model.beans.ManagedRepository;
+import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
+import org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin;
+import org.apache.commons.io.FileUtils;
+import org.apache.maven.archiva.configuration.ArchivaConfiguration;
+import org.apache.maven.archiva.configuration.NetworkProxyConfiguration;
+import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
+import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
+import org.apache.maven.archiva.model.ArtifactReference;
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.PropagateErrorsDownloadPolicy;
+import org.apache.maven.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.apache.maven.archiva.repository.ManagedRepositoryContent;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mortbay.jetty.Handler;
+import org.mortbay.jetty.Request;
+import org.mortbay.jetty.Server;
+import org.mortbay.jetty.handler.AbstractHandler;
+import org.springframework.context.ApplicationContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.inject.Inject;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.IOException;
+
+import static org.junit.Assert.*;
+
+/**
+ * Integration test for connecting over a HTTP proxy.
+ *
+ * @version $Id: ManagedDefaultTransferTest.java 677852 2008-07-18 08:16:24Z brett $
+ */
+@RunWith( SpringJUnit4ClassRunner.class )
+@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
+public class HttpProxyTransferTest
+{
+ private static final String PROXY_ID = "proxy";
+
+ private static final String MANAGED_ID = "default-managed-repository";
+
+ private static final String PROXIED_ID = "proxied1";
+
+ private static final String PROXIED_BASEDIR = "src/test/repositories/proxied1";
+
+ private RepositoryProxyConnectors proxyHandler;
+
+ private ArchivaConfiguration config;
+
+ private ManagedRepositoryContent managedDefaultRepository;
+
+ @Inject
+ private ApplicationContext applicationContext;
+
+ private Server server;
+
+ @Before
+ public void setUp()
+ throws Exception
+ {
+ proxyHandler = applicationContext.getBean( "repositoryProxyConnectors#test", RepositoryProxyConnectors.class );
+
+ config = applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
+
+ // clear from previous tests - TODO the spring context should be initialised per test instead, or the config
+ // made a complete mock
+ config.getConfiguration().getProxyConnectors().clear();
+
+ // Setup source repository (using default layout)
+ String repoPath = "target/test-repository/managed/" + getClass().getSimpleName();
+
+ File destRepoDir = new File( repoPath );
+
+ // Cleanout destination dirs.
+ if ( destRepoDir.exists() )
+ {
+ FileUtils.deleteDirectory( destRepoDir );
+ }
+
+ // Make the destination dir.
+ destRepoDir.mkdirs();
+
+ ManagedRepository repo = new ManagedRepository();
+ repo.setId( MANAGED_ID );
+ repo.setName( "Default Managed Repository" );
+ repo.setLocation( repoPath );
+ repo.setLayout( "default" );
+
+ ManagedRepositoryContent repoContent =
+ applicationContext.getBean( "managedRepositoryContent#default", ManagedRepositoryContent.class );
+
+ repoContent.setRepository( repo );
+ managedDefaultRepository = repoContent;
+
+ ( (DefaultManagedRepositoryAdmin) applicationContext.getBean(
+ ManagedRepositoryAdmin.class ) ).setArchivaConfiguration( config );
+
+ ManagedRepositoryAdmin managedRepositoryAdmin = applicationContext.getBean( ManagedRepositoryAdmin.class );
+ if ( managedRepositoryAdmin.getManagedRepository( repo.getId() ) == null )
+ {
+ managedRepositoryAdmin.addManagedRepository( repo, false, null );
+ }
+
+ //config.getConfiguration().addManagedRepository( repo );
+
+ Handler handler = new AbstractHandler()
+ {
+ public void handle( String target, HttpServletRequest request, HttpServletResponse response, int dispatch )
+ throws IOException, ServletException
+ {
+ response.setContentType( "text/plain" );
+ response.setStatus( HttpServletResponse.SC_OK );
+ response.getWriter().print( "get-default-layout-1.0.jar\n\n" );
+ assertNotNull( request.getHeader( "Proxy-Connection" ) );
+
+ ( (Request) request ).setHandled( true );
+ }
+ };
+
+ server = new Server( 0 );
+ server.setHandler( handler );
+ server.start();
+
+ int port = server.getConnectors()[0].getLocalPort();
+
+ NetworkProxyConfiguration proxyConfig = new NetworkProxyConfiguration();
+ proxyConfig.setHost( "localhost" );
+ proxyConfig.setPort( port );
+ proxyConfig.setProtocol( "http" );
+ proxyConfig.setId( PROXY_ID );
+ config.getConfiguration().addNetworkProxy( proxyConfig );
+
+ // Setup target (proxied to) repository.
+ RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
+
+ repoConfig.setId( PROXIED_ID );
+ repoConfig.setName( "Proxied Repository 1" );
+ repoConfig.setLayout( "default" );
+ repoConfig.setUrl( "http://www.example.com/" );
+
+ config.getConfiguration().addRemoteRepository( repoConfig );
+
+ }
+
+ @After
+ public void tearDown()
+ throws Exception
+ {
+ server.stop();
+ }
+
+ @Test
+ public void testGetOverHttpProxy()
+ throws Exception
+ {
+ assertNull( System.getProperty( "http.proxyHost" ) );
+ assertNull( System.getProperty( "http.proxyPort" ) );
+
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ addConnector();
+
+ File expectedFile = new File( new File( managedDefaultRepository.getRepoRoot() ), path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File sourceFile = new File( PROXIED_BASEDIR, path );
+ assertNotNull( "Expected File should not be null.", expectedFile );
+ assertNotNull( "Actual File should not be null.", downloadedFile );
+
+ assertTrue( "Check actual file exists.", downloadedFile.exists() );
+ assertEquals( "Check filename path is appropriate.", expectedFile.getCanonicalPath(),
+ downloadedFile.getCanonicalPath() );
+ assertEquals( "Check file path matches.", expectedFile.getAbsolutePath(), downloadedFile.getAbsolutePath() );
+
+ String expectedContents = FileUtils.readFileToString( sourceFile, null );
+ String actualContents = FileUtils.readFileToString( downloadedFile, null );
+ assertEquals( "Check file contents.", expectedContents, actualContents );
+
+ assertNull( System.getProperty( "http.proxyHost" ) );
+ assertNull( System.getProperty( "http.proxyPort" ) );
+ }
+
+ private void addConnector()
+ {
+ ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
+ connectorConfig.setProxyId( PROXY_ID );
+ connectorConfig.setSourceRepoId( MANAGED_ID );
+ connectorConfig.setTargetRepoId( PROXIED_ID );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, ChecksumPolicy.FIX );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, ReleasesPolicy.ONCE );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, SnapshotsPolicy.ONCE );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, CachedFailuresPolicy.NO );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS,
+ PropagateErrorsDownloadPolicy.QUEUE );
+ connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE,
+ PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
+
+ int count = config.getConfiguration().getProxyConnectors().size();
+ config.getConfiguration().addProxyConnector( connectorConfig );
+
+ // Proper Triggering ...
+ String prefix = "proxyConnectors.proxyConnector(" + count + ")";
+ ( (MockConfiguration) config ).triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.maven.archiva.model.ArtifactReference;
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.*;
+
+/**
+ * ManagedDefaultTransferTest
+ *
+ * @version $Id$
+ */
+public class ManagedDefaultTransferTest
+ extends AbstractProxyTestCase
+{
+ @Test
+ public void testGetDefaultLayoutNotPresentConnectorOffline()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Ensure file isn't present first.
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, true );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+ assertNull("File should not have been downloaded", downloadedFile);
+ }
+
+ @Test
+ public void testGetDefaultLayoutNotPresent()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Ensure file isn't present first.
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File sourceFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, sourceFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetDefaultLayoutNotPresentPassthrough()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar.asc";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+
+ // Ensure file isn't present first.
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, path );
+
+ File sourceFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, sourceFile );
+ assertFalse( new File( downloadedFile.getParentFile(), downloadedFile.getName() + ".sha1" ).exists() );
+ assertFalse( new File( downloadedFile.getParentFile(), downloadedFile.getName() + ".md5" ).exists() );
+ assertFalse( new File( downloadedFile.getParentFile(), downloadedFile.getName() + ".asc" ).exists() );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * The attempt here should result in no file being transferred.
+ * <p/>
+ * The file exists locally, and the policy is ONCE.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutAlreadyPresentPolicyOnce()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertFileEquals( expectedFile, downloadedFile, expectedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * The attempt here should result in no file being transferred.
+ * <p/>
+ * The file exists locally, and the policy is ONCE.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutAlreadyPresentPassthrough()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar.asc";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, path );
+
+ assertTrue( expectedFile.exists() );
+
+ // Set the managed File to be newer than local.
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+ long originalModificationTime = expectedFile.lastModified();
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, path );
+
+ assertNotDownloaded( downloadedFile );
+ assertNotModified( expectedFile, originalModificationTime );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * <p>
+ * Request a file, that exists locally, and remotely.
+ * </p>
+ * <p>
+ * All policies are set to IGNORE.
+ * </p>
+ * <p>
+ * Managed file is newer than remote file.
+ * </p>
+ * <p>
+ * Transfer should not have occured, as managed file is newer.
+ * </p>
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutAlreadyPresentNewerThanRemotePolicyIgnored()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, path );
+
+ // Set the managed File to be newer than local.
+ setManagedNewerThanRemote( expectedFile, remoteFile );
+
+ long originalModificationTime = expectedFile.lastModified();
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNotModified( expectedFile, originalModificationTime );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * <p>
+ * Request a file, that exists locally, and remotely.
+ * </p>
+ * <p>
+ * All policies are set to IGNORE.
+ * </p>
+ * <p>
+ * Managed file is older than Remote file.
+ * </p>
+ * <p>
+ * Transfer should have occured, as managed file is older than remote.
+ * </p>
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutAlreadyPresentOlderThanRemotePolicyIgnored()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, path );
+
+ // Set the managed file to be newer than remote file.
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * The attempt here should result in file being transferred.
+ * <p/>
+ * The file exists locally, is over 6 years old, and the policy is DAILY.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGetDefaultLayoutRemoteUpdate()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+ expectedFile.setLastModified( getPastDate().getTime() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.DAILY, SnapshotsPolicy.DAILY,
+ CachedFailuresPolicy.NO, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetWhenInBothProxiedRepos()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1 , false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2 , false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied1File = new File( REPOPATH_PROXIED1, path );
+ File proxied2File = new File( REPOPATH_PROXIED2, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied1File );
+ assertNoTempFiles( expectedFile );
+
+ // TODO: is this check even needed if it passes above?
+ String actualContents = FileUtils.readFileToString( downloadedFile, null );
+ String badContents = FileUtils.readFileToString( proxied2File, null );
+ assertFalse( "Downloaded file contents should not be that of proxy 2",
+ StringUtils.equals( actualContents, badContents ) );
+ }
+
+ @Test
+ public void testGetInSecondProxiedRepo()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxied2File = new File( REPOPATH_PROXIED2, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied2File );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testNotFoundInAnyProxies()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/does-not-exist/1.0/does-not-exist-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNull( "File returned was: " + downloadedFile + "; should have got a not found exception",
+ downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetInSecondProxiedRepoFirstFails()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Repository (usually done within archiva.xml configuration)
+ saveRemoteRepositoryConfig( "badproxied", "Bad Proxied", "test://bad.machine.com/repo/", "default" );
+
+ wagonMock.get( path, new File( expectedFile.getAbsolutePath() + ".tmp" ) );
+ wagonMockControl.setMatcher(customWagonGetMatcher);
+ wagonMockControl.setThrowable( new ResourceDoesNotExistException( "transfer failed" ) );
+ wagonMockControl.replay();
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied", false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
+
+ // Attempt the proxy fetch.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ wagonMockControl.verify();
+
+ File proxied2File = new File( REPOPATH_PROXIED2, path );
+ assertFileEquals( expectedFile, downloadedFile, proxied2File );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetAllRepositoriesFail()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir.getAbsoluteFile(), path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Repository (usually done within archiva.xml configuration)
+ saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "test://bad.machine.com/repo/", "default" );
+ saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "test://dead.machine.com/repo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied1", false );
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied2", false );
+
+ File tmpFile = new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" );
+ wagonMock.get( path, tmpFile );
+
+ wagonMockControl.setMatcher(customWagonGetMatcher);
+ wagonMockControl.setThrowable( new ResourceDoesNotExistException( "Can't find resource." ) );
+
+ wagonMock.get( path, tmpFile );
+
+ wagonMockControl.setMatcher(customWagonGetMatcher);
+ wagonMockControl.setThrowable( new ResourceDoesNotExistException( "Can't find resource." ) );
+
+ wagonMockControl.replay();
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+
+ wagonMockControl.verify();
+ assertNoTempFiles( expectedFile );
+
+ // TODO: do not want failures to present as a not found [MRM-492]
+ // TODO: How much information on each failure should we pass back to the user vs. logging in the proxy?
+ }
+
+ @Test
+ public void testGetFromLegacyProxyAlreadyPresentInManaged_NewerThanRemote()
+ throws Exception
+ {
+ String legacyPath = "org.apache.maven.test/jars/get-default-layout-present-1.0.jar";
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
+
+ // Set the managed file to be newer than remote.
+ setManagedNewerThanRemote( expectedFile, remoteFile );
+ long expectedTimestamp = expectedFile.lastModified();
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNotModified( expectedFile, expectedTimestamp );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetFromLegacyProxyAlreadyPresentInManaged_OlderThanRemote()
+ throws Exception
+ {
+ String legacyPath = "org.apache.maven.test/jars/get-default-layout-present-1.0.jar";
+ String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
+
+ // Set the managed file to be older than remote.
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetFromLegacyProxyNotPresentInManaged()
+ throws Exception
+ {
+ String legacyPath = "org.apache.maven.test/jars/example-lib-2.2.jar";
+ String path = "org/apache/maven/test/example-lib/2.2/example-lib-2.2.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetFromLegacyProxyPluginNotPresentInManaged()
+ throws Exception
+ {
+ String legacyPath = "org.apache.maven.test/maven-plugins/example-maven-plugin-0.42.jar";
+ String path = "org/apache/maven/test/example-maven-plugin/0.42/example-maven-plugin-0.42.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedDefaultRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.maven.archiva.model.ArtifactReference;
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.assertTrue;
+
+/**
+ * ManagedLegacyTransferTest
+ *
+ * @version $Id$
+ */
+public class ManagedLegacyTransferTest
+ extends AbstractProxyTestCase
+{
+ /**
+ * Incoming request on a Managed Legacy repository, for content that does not
+ * exist in the managed legacy repository, but does exist on a remote default layout repository.
+ */
+ @Test
+ public void testManagedLegacyNotPresentRemoteDefaultPresent()
+ throws Exception
+ {
+ String path = "org.apache.maven.test/jars/get-default-layout-1.0.jar";
+ File expectedFile = new File( managedLegacyDir, path );
+ ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedLegacyRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_LEGACY_MANAGED, ID_PROXIED1, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
+
+ File proxied2File = new File( REPOPATH_PROXIED1,
+ "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar" );
+ assertFileEquals( expectedFile, downloadedFile, proxied2File );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Incoming request on a Managed Legacy repository, for content that already
+ * exist in the managed legacy repository, and also exist on a remote default layout repository.
+ */
+ @Test
+ public void testManagedLegacyPresentRemoteDefaultPresent()
+ throws Exception
+ {
+ String path = "org.apache.maven.test/jars/get-default-layout-present-1.0.jar";
+ String remotePath = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
+
+ File expectedFile = new File( managedLegacyDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, remotePath );
+
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_LEGACY_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
+
+ assertFileEquals( expectedFile, downloadedFile, remoteFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Incoming request on a Managed Legacy repository, for content that does not
+ * exist in the managed legacy repository, and does not exist on a remote legacy layout repository.
+ */
+ @Test
+ public void testManagedLegacyNotPresentRemoteLegacyPresent()
+ throws Exception
+ {
+ String path = "org.apache.maven.test/plugins/get-legacy-plugin-1.0.jar";
+ File expectedFile = new File( managedLegacyDir, path );
+ ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedLegacyRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_LEGACY_MANAGED, ID_LEGACY_PROXIED, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED_LEGACY, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Incoming request on a Managed Legacy repository, for content that does exist in the
+ * managed legacy repository, and also exists on a remote legacy layout repository.
+ */
+ @Test
+ public void testManagedLegacyPresentRemoteLegacyPresent()
+ throws Exception
+ {
+ String path = "org.apache.maven.test/jars/get-default-layout-present-1.0.jar";
+ File expectedFile = new File( managedLegacyDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED_LEGACY, path );
+
+ setManagedOlderThanRemote( expectedFile, remoteFile );
+
+ ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_LEGACY_MANAGED, ID_LEGACY_PROXIED, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
+
+ assertFileEquals( expectedFile, downloadedFile, remoteFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Incoming request on a Managed Legacy repository, for content that does exist in the
+ * managed legacy repository, and does not exist on a remote legacy layout repository.
+ */
+ @Test
+ public void testManagedLegacyPresentRemoteLegacyNotPresent()
+ throws Exception
+ {
+ String path = "org.apache.maven.test/jars/managed-only-lib-2.1.jar";
+ File expectedFile = new File( managedLegacyDir, path );
+ ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_LEGACY_MANAGED, ID_LEGACY_PROXIED, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Incoming request on a Managed Legacy repository, for content that does exist in the
+ * managed legacy repository, and does not exists on a remote default layout repository.
+ */
+ @Test
+ public void testManagedLegacyPresentRemoteDefaultNotPresent()
+ throws Exception
+ {
+ String path = "org.apache.maven.test/jars/managed-only-lib-2.1.jar";
+ File expectedFile = new File( managedLegacyDir, path );
+ ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_LEGACY_MANAGED, ID_PROXIED1, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Incoming request on a Managed Legacy repository, for content that does not exist in the
+ * managed legacy repository, and does not exists on a remote legacy layout repository.
+ */
+ @Test
+ public void testManagedLegacyNotPresentRemoteLegacyNotPresent()
+ throws Exception
+ {
+ String path = "org.apache.archiva.test/jars/mystery-lib-1.0.jar";
+ File expectedFile = new File( managedLegacyDir, path );
+ ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedLegacyRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_LEGACY_MANAGED, ID_LEGACY_PROXIED, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Incoming request on a Managed Legacy repository, for content that does not exist in the
+ * managed legacy repository, and does not exists on a remote default layout repository.
+ */
+ @Test
+ public void testManagedLegacyNotPresentRemoteDefaultNotPresent()
+ throws Exception
+ {
+ String path = "org.apache.archiva.test/jars/mystery-lib-2.1.jar";
+ File expectedFile = new File( managedLegacyDir, path );
+ ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
+
+ assertNotExistsInManagedLegacyRepo( expectedFile );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_LEGACY_MANAGED, ID_PROXIED1, false );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.archiva.common.utils.VersionUtil;
+import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
+import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
+import org.apache.maven.archiva.model.Plugin;
+import org.apache.maven.archiva.model.ProjectReference;
+import org.apache.maven.archiva.model.SnapshotVersion;
+import org.apache.maven.archiva.model.VersionedReference;
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.apache.maven.archiva.repository.metadata.MetadataTools;
+import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
+import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
+import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
+import org.apache.maven.wagon.TransferFailedException;
+import org.custommonkey.xmlunit.DetailedDiff;
+import org.custommonkey.xmlunit.Diff;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import static org.junit.Assert.*;
+
+/**
+ * MetadataTransferTest - Tests the various fetching / merging concepts surrounding the maven-metadata.xml files
+ * present in the repository.
+ * <p/>
+ * Test Case Naming is as follows.
+ * <p/>
+ * <code>
+ * public void testGet[Release|Snapshot|Project]Metadata[Not]Proxied[Not|On]Local[Not|On|Multiple]Remote
+ * </code>
+ * <p/>
+ * <pre>
+ * Which should leave the following matrix of test cases.
+ *
+ * Metadata | Proxied | Local | Remote
+ * ----------+----------+-------+---------
+ * Release | Not | Not | n/a (1)
+ * Release | Not | On | n/a (1)
+ * Release | | Not | Not
+ * Release | | Not | On
+ * Release | | Not | Multiple
+ * Release | | On | Not
+ * Release | | On | On
+ * Release | | On | Multiple
+ * Snapshot | Not | Not | n/a (1)
+ * Snapshot | Not | On | n/a (1)
+ * Snapshot | | Not | Not
+ * Snapshot | | Not | On
+ * Snapshot | | Not | Multiple
+ * Snapshot | | On | Not
+ * Snapshot | | On | On
+ * Snapshot | | On | Multiple
+ * Project | Not | Not | n/a (1)
+ * Project | Not | On | n/a (1)
+ * Project | | Not | Not
+ * Project | | Not | On
+ * Project | | Not | Multiple
+ * Project | | On | Not
+ * Project | | On | On
+ * Project | | On | Multiple
+ *
+ * (1) If it isn't proxied, no point in having a remote.
+ * </pre>
+ *
+ * @version $Id$
+ */
+public class MetadataTransferTest
+ extends AbstractProxyTestCase
+{
+
+ @Inject
+ @Named(value = "metadataTools#mocked")
+ private MetadataTools metadataTools;
+
+ @Before
+ public void init()
+ throws Exception
+ {
+ super.setUp();
+ //metadataTools = applicationContext.getBean( MetadataTools.class );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedNotLocalOnRemoteConnectoDisabled()
+ throws Exception
+ {
+ // New project metadata that does not exist locally but exists on remote.
+ String requestedResource = "org/apache/maven/test/get-found-in-proxy/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, true );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ File expectedFile = new File( managedDefaultDir, requestedResource );
+
+ ProjectReference metadata = createProjectReference( requestedResource );
+
+ File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
+ managedDefaultRepository.toMetadataPath(
+ metadata ) );
+
+ assertNull( "Should not have downloaded a file.", downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ // TODO: same test for other fetch* methods
+ @Test
+ public void testFetchFromTwoProxiesWhenFirstConnectionFails()
+ throws Exception
+ {
+ // Project metadata that does not exist locally, but has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/get-default-layout/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "test://bad.machine.com/repo/", "default" );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( "badproxied1", requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // ensure that a hard failure in the first proxy connector is skipped and the second repository checked
+ File expectedFile = new File( managedDefaultDir.getAbsoluteFile(),
+ metadataTools.getRepositorySpecificName( "badproxied1", requestedResource ) );
+ wagonMock.get( requestedResource, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
+
+ wagonMockControl.setMatcher( customWagonGetMatcher );
+
+ wagonMockControl.setThrowable( new TransferFailedException( "can't connect" ) );
+
+ wagonMockControl.replay();
+
+ assertFetchProjectOrGroup( requestedResource );
+
+ wagonMockControl.verify();
+
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0.1" }, "1.0.1", "1.0.1" );
+ assertNoRepoMetadata( "badproxied1", requestedResource );
+ assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0.1" } );
+ }
+
+ /**
+ * Attempt to get the project metadata for non-existant artifact.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is not created on the managed repository, nor returned
+ * to the requesting client.
+ */
+ @Test
+ public void testGetProjectMetadataNotProxiedNotLocal()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource = "org/apache/maven/test/get-default-metadata-nonexistant/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
+
+ assertResourceNotFound( requestedResource );
+
+ // No proxy setup, nothing fetched, failure expected.
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertResourceNotFound( requestedResource );
+ }
+
+ @Test
+ public void testGetProjectMetadataNotProxiedOnLocal()
+ throws Exception
+ {
+
+ // Project metadata that exists and has multiple versions
+ String requestedResource = "org/apache/maven/test/get-project-metadata/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
+
+ assertResourceExists( requestedResource );
+
+ // No proxy setup, nothing fetched from remote, but local exists.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Nothing fetched. Should only contain contents of what is in the repository.
+ // A metadata update is not performed in this use case. Local metadata content is only
+ // updated via the metadata updater consumer.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0" }, null, null );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedNotLocalMultipleRemotes()
+ throws Exception
+ {
+ // Project metadata that does not exist locally, but has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/get-default-layout/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetched from both remotes.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Nothing fetched. Should only contain contents of what is in the repository.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0", "1.0.1" }, "1.0.1", "1.0.1" );
+ assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0" } );
+ assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0.1" } );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedNotLocalNotRemote()
+ throws Exception
+ {
+ // Non-existant project metadata that does not exist locally and doesn't exist on remotes.
+ String requestedResource = "org/apache/maven/test/get-bogus-artifact/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, nothing fetched from remotes, local does not exist.
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ // Nothing fetched. Nothing should exist.
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedNotLocalOnRemote()
+ throws Exception
+ {
+ // New project metadata that does not exist locally but exists on remote.
+ String requestedResource = "org/apache/maven/test/get-found-in-proxy/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // One proxy setup, metadata fetched from remote, local does not exist.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Remote fetched. Local created/updated.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0.5" }, "1.0.5", "1.0.5" );
+ assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0.5" } );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedOnLocalMultipleRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally, and has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/get-on-multiple-repos/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0" }, null, null );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetched from both remotes.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // metadata fetched from both repos, and merged with local version.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0", "1.0.1", "2.0" }, "2.0", "2.0" );
+ assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0", "2.0" } );
+ assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0", "1.0.1" } );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedOnLocalNotRemote()
+ throws Exception
+ {
+
+ // Project metadata that exist locally, and does not exist in remote repos.
+ String requestedResource = "org/apache/maven/test/get-not-on-remotes/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+
+ config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0-beta-2" }, null, null );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetch from remotes fail (because they dont exist).
+ assertFetchProjectOrGroup( requestedResource );
+
+ // metadata not fetched from both repos, and local version exists.
+ // Since there was no updated metadata content from a remote/proxy, a metadata update on
+ // the local file never ran. Local only updates are performed via the metadata updater consumer.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0-beta-2" }, null, null );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetProjectMetadataProxiedOnLocalOnRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally and exists on remote.
+ String requestedResource = "org/apache/maven/test/get-on-local-on-remote/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0.8", "1.0.22" }, null, null );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // One proxy setup, metadata fetched from remote, local exists.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Remote fetched. Local updated.
+ assertProjectMetadataContents( requestedResource, new String[]{ "1.0.8", "1.0.22", "2.0" }, "2.0", "2.0" );
+ assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0.22", "2.0" } );
+ }
+
+ /**
+ * A request for a release maven-metadata.xml file that does not exist locally, and the managed
+ * repository has no proxied repositories set up.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is not created on the managed repository, nor returned
+ * to the requesting client.
+ */
+ @Test
+ public void testGetReleaseMetadataNotProxiedNotLocal()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource = "org/apache/maven/test/get-default-metadata-nonexistant/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertNoMetadata( requestedResource );
+
+ // No proxy setup, nothing fetched, failure expected.
+ assertFetchVersionedFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertNoMetadata( requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that does exist locally, and the managed
+ * repository has no proxied repositories set up.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is updated locally, based off of the managed repository
+ * information, and then returned to the client.
+ */
+ @Test
+ public void testGetReleaseMetadataNotProxiedOnLocal()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-default-metadata/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertResourceExists( requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ }
+
+ /**
+ * A request for a release maven-metadata.xml file that does not exist on the managed repository, but
+ * exists on multiple remote repositories.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is downloaded from the remote into the repository specific
+ * file location on the managed repository, a merge of the contents to the requested
+ * maven-metadata.xml is performed, and then the merged maven-metadata.xml file is
+ * returned to the client.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedNotLocalMultipleRemotes()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-default-layout/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED2, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that does not exist locally, nor does it exist in a remote
+ * proxied repository.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is created locally, based off of managed repository
+ * information, and then return to the client.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedNotLocalNotRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-bad-metadata/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that does not exist on the managed repository, but
+ * exists on 1 remote repository.
+ * <p/>
+ * Expected result: the maven-metadata.xml file is downloaded from the remote into the repository specific
+ * file location on the managed repository, a merge of the contents to the requested
+ * maven-metadata.xml is performed, and then the merged maven-metadata.xml file is
+ * returned to the client.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedNotLocalOnRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-default-layout/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that exists in the managed repository, but
+ * not on any remote repository.
+ * <p/>
+ * Expected result: the maven-metadata.xml file does not exist on the remote proxied repository and
+ * is not downloaded. There is no repository specific metadata file on the managed
+ * repository. The managed repository maven-metadata.xml is returned to the
+ * client as-is.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedOnLocalNotRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-not-on-remotes/1.0-beta-2/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertReleaseMetadataContents( requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that exists in the managed repository, and on multiple
+ * remote repositories.
+ * <p/>
+ * Expected result: the maven-metadata.xml file on the remote proxied repository is downloaded
+ * and merged into the contents of the existing managed repository copy of
+ * the maven-metadata.xml file.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedOnLocalMultipleRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-on-multiple-repos/1.0/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED2, requestedResource );
+ }
+
+ /**
+ * A request for a maven-metadata.xml file that exists in the managed repository, and on one
+ * remote repository.
+ * <p/>
+ * Expected result: the maven-metadata.xml file on the remote proxied repository is downloaded
+ * and merged into the contents of the existing managed repository copy of
+ * the maven-metadata.xml file.
+ */
+ @Test
+ public void testGetReleaseMetadataProxiedOnLocalOnRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-on-local-on-remote/1.0.22/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ assertFetchVersioned( requestedResource );
+
+ assertReleaseMetadataContents( requestedResource );
+ assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataNotProxiedNotLocal()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource =
+ "org/apache/maven/test/get-default-metadata-nonexistant/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertNoMetadata( requestedResource );
+
+ // No proxy setup, nothing fetched, no local file, failure expected.
+ assertFetchVersionedFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertNoMetadata( requestedResource );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataNotProxiedOnLocal()
+ throws Exception
+ {
+ // The artifactId exists locally (but not on a remote repo)
+ String requestedResource =
+ "org/apache/maven/test/get-snapshot-on-local-not-remote/2.0-alpha-2-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertResourceExists( requestedResource );
+
+ // No proxy setup, nothing fetched from remote, local file exists, fetch should succeed.
+ assertFetchVersioned( requestedResource );
+
+ // Local metadata exists, should be updated to reflect the latest release.
+ assertSnapshotMetadataContents( requestedResource, "20070821", "220304", 2 );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedNotLocalMultipleRemotes()
+ throws Exception
+ {
+ String requestedResource =
+ "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Proxying 2 repos, both have content, local file updated.
+ assertFetchVersioned( requestedResource );
+
+ assertSnapshotMetadataContents( requestedResource, "20070101", "000103", 2 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20061227", "112101", 2 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED2, requestedResource, "20070101", "000103", 2 );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedNotLocalNotRemote()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource =
+ "org/apache/maven/test/get-default-metadata-nonexistant/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertNoMetadata( requestedResource );
+
+ // One proxy setup, nothing fetched, no local file, failure expected.
+ assertFetchVersionedFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertNoMetadata( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedNotLocalOnRemote()
+ throws Exception
+ {
+ // Artifact exists only in the proxied1 location.
+ String requestedResource = "org/apache/maven/test/get-metadata-snapshot/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+
+ // One proxy setup, one metadata fetched, local file created/updated.
+ assertFetchVersioned( requestedResource );
+
+ // Local artifact Id should contain latest (which in this case is from proxied download)
+ assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20050831", "101112", 1 );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedOnLocalMultipleRemote()
+ throws Exception
+ {
+ String requestedResource = "org/apache/maven/test/get-snapshot-popular/2.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertSnapshotMetadataContents( requestedResource, "20070822", "021008", 3 );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Proxying 2 repos, both have content, local file updated.
+ assertFetchVersioned( requestedResource );
+
+ assertSnapshotMetadataContents( requestedResource, "20070823", "212711", 6 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20070822", "145534", 9 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED2, requestedResource, "20070823", "212711", 6 );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedOnLocalNotRemote()
+ throws Exception
+ {
+ // The artifactId exists locally (but not on a remote repo)
+ String requestedResource =
+ "org/apache/maven/test/get-snapshot-on-local-not-remote/2.0-alpha-2-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceExists( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // two proxies setup, nothing fetched from either remote, local file exists, fetch should succeed.
+ assertFetchVersioned( requestedResource );
+
+ // Local metadata exists, repo metadatas should not exist, local file updated.
+ assertSnapshotMetadataContents( requestedResource, "20070821", "220304", 2 );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetSnapshotMetadataProxiedOnLocalOnRemote()
+ throws Exception
+ {
+ // The artifactId exists locally (but not on a remote repo)
+ String requestedResource =
+ "org/apache/maven/test/get-present-metadata-snapshot/1.0-SNAPSHOT/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // two proxies setup, nothing fetched from either remote, local file exists, fetch should succeed.
+ assertFetchVersioned( requestedResource );
+
+ // Local metadata exists, repo metadata exists, local file updated.
+ assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
+ assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20050831", "101112", 1 );
+ }
+
+ @Test
+ public void testGetGroupMetadataNotProxiedNotLocal()
+ throws Exception
+ {
+ // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
+ String requestedResource = "org/apache/maven/test/groups/get-default-metadata-nonexistant/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertResourceNotFound( requestedResource );
+
+ // No proxy setup, nothing fetched, failure expected.
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
+ assertResourceNotFound( requestedResource );
+ }
+
+ @Test
+ public void testGetGroupMetadataNotProxiedOnLocal()
+ throws Exception
+ {
+ // Project metadata that exists and has multiple versions
+ String requestedResource = "org/apache/maven/test/groups/get-project-metadata/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ assertResourceExists( requestedResource );
+
+ // No proxy setup, nothing fetched from remote, but local exists.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Nothing fetched. Should only contain contents of what is in the repository.
+ // A metadata update is not performed in this use case. Local metadata content is only
+ // updated via the metadata updater consumer.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin1" } );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedNotLocalMultipleRemotes()
+ throws Exception
+ {
+ // Project metadata that does not exist locally, but has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/groups/get-default-layout/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetched from both remotes.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Nothing fetched. Should only contain contents of what is in the repository.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin2", "plugin1" } );
+ assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin1" } );
+ assertRepoGroupMetadataContents( ID_PROXIED2, requestedResource, new String[]{ "plugin2" } );
+ }
+
+ @Test
+ public void testGetGroupsMetadataProxiedNotLocalNotRemote()
+ throws Exception
+ {
+ // Non-existant project metadata that does not exist locally and doesn't exist on remotes.
+ String requestedResource = "org/apache/maven/test/groups/get-bogus-artifact/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, nothing fetched from remotes, local does not exist.
+ assertFetchProjectOrGroupFailed( requestedResource );
+
+ // Nothing fetched. Nothing should exist.
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedNotLocalOnRemote()
+ throws Exception
+ {
+ // New project metadata that does not exist locally but exists on remote.
+ String requestedResource = "org/apache/maven/test/groups/get-found-in-proxy/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertResourceNotFound( requestedResource );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // One proxy setup, metadata fetched from remote, local does not exist.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Remote fetched. Local created/updated.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin3" } );
+ assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin3" } );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedOnLocalMultipleRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally, and has multiple versions in remote repos
+ String requestedResource = "org/apache/maven/test/groups/get-on-multiple-repos/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin1" } );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetched from both remotes.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // metadata fetched from both repos, and merged with local version.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin1", "plugin2", "plugin4" } );
+ assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin1", "plugin4" } );
+ assertRepoGroupMetadataContents( ID_PROXIED2, requestedResource, new String[]{ "plugin1", "plugin2" } );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedOnLocalNotRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally, and does not exist in remote repos.
+ String requestedResource = "org/apache/maven/test/groups/get-not-on-remotes/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin5" } );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+
+ // Two proxies setup, metadata fetch from remotes fail (because they dont exist).
+ assertFetchProjectOrGroup( requestedResource );
+
+ // metadata not fetched from both repos, and local version exists.
+ // Since there was no updated metadata content from a remote/proxy, a metadata update on
+ // the local file never ran. Local only updates are performed via the metadata updater consumer.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin5" } );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+ assertNoRepoMetadata( ID_PROXIED2, requestedResource );
+ }
+
+ @Test
+ public void testGetGroupMetadataProxiedOnLocalOnRemote()
+ throws Exception
+ {
+ // Project metadata that exist locally and exists on remote.
+ String requestedResource = "org/apache/maven/test/groups/get-on-local-on-remote/maven-metadata.xml";
+ setupTestableManagedRepository( requestedResource );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
+
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin6", "plugin7" } );
+ assertNoRepoMetadata( ID_PROXIED1, requestedResource );
+
+ // One proxy setup, metadata fetched from remote, local exists.
+ assertFetchProjectOrGroup( requestedResource );
+
+ // Remote fetched. Local updated.
+ assertGroupMetadataContents( requestedResource, new String[]{ "plugin6", "plugin7", "plugin4" } );
+ assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin7", "plugin4" } );
+ }
+
+ /**
+ * Transfer the metadata file.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertFetchProjectOrGroup( String requestedResource )
+ throws Exception
+ {
+ File expectedFile = new File( managedDefaultDir, requestedResource );
+
+ ProjectReference metadata = createProjectReference( requestedResource );
+
+ File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
+ managedDefaultRepository.toMetadataPath(
+ metadata ) );
+
+ assertNotNull( "Should have downloaded a file.", downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ private ProjectReference createProjectReference( String path )
+ throws RepositoryMetadataException
+ {
+ return metadataTools.toProjectReference( path );
+ }
+
+ /**
+ * Transfer the metadata file, not expected to succeed.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertFetchProjectOrGroupFailed( String requestedResource )
+ throws Exception
+ {
+ File expectedFile = new File( managedDefaultDir, requestedResource );
+ ProjectReference metadata = createProjectReference( requestedResource );
+
+ File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
+ managedDefaultRepository.toMetadataPath(
+ metadata ) );
+
+ assertNull( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Transfer the metadata file.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertFetchVersioned( String requestedResource )
+ throws Exception
+ {
+ File expectedFile = new File( managedDefaultDir, requestedResource );
+
+ VersionedReference metadata = createVersionedReference( requestedResource );
+
+ File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
+ managedDefaultRepository.toMetadataPath(
+ metadata ) );
+
+ assertNotNull( "Should have downloaded a file.", downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ private VersionedReference createVersionedReference( String path )
+ throws RepositoryMetadataException
+ {
+ return metadataTools.toVersionedReference( path );
+ }
+
+ /**
+ * Transfer the metadata file, not expected to succeed.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertFetchVersionedFailed( String requestedResource )
+ throws Exception
+ {
+ File expectedFile = new File( managedDefaultDir, requestedResource );
+ VersionedReference metadata = createVersionedReference( requestedResource );
+
+ File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
+ managedDefaultRepository.toMetadataPath(
+ metadata ) );
+
+ assertNull( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * Test for the existance of the requestedResource in the default managed repository.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertResourceExists( String requestedResource )
+ throws Exception
+ {
+ File actualFile = new File( managedDefaultDir, requestedResource );
+ assertTrue( "Resource should exist: " + requestedResource, actualFile.exists() );
+ }
+
+ private void assertMetadataEquals( String expectedMetadataXml, File actualFile )
+ throws Exception
+ {
+ assertNotNull( "Actual File should not be null.", actualFile );
+
+ assertTrue( "Actual file exists.", actualFile.exists() );
+
+ StringWriter actualContents = new StringWriter();
+ ArchivaRepositoryMetadata metadata = RepositoryMetadataReader.read( actualFile );
+ RepositoryMetadataWriter.write( metadata, actualContents );
+
+ DetailedDiff detailedDiff = new DetailedDiff( new Diff( expectedMetadataXml, actualContents.toString() ) );
+ if ( !detailedDiff.similar() )
+ {
+ assertEquals( expectedMetadataXml, actualContents );
+ }
+
+ // assertEquals( "Check file contents.", expectedMetadataXml, actualContents );
+ }
+
+ /**
+ * Ensures that the requested resource is not present in the managed repository.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertNoMetadata( String requestedResource )
+ throws Exception
+ {
+ File expectedFile = new File( managedDefaultDir, requestedResource );
+ assertFalse( "metadata should not exist: " + expectedFile, expectedFile.exists() );
+ }
+
+ /**
+ * Ensures that the proxied repository specific maven metadata file does NOT exist in the
+ * managed repository.
+ *
+ * @param proxiedRepoId the proxied repository id to validate with.
+ * @param requestedResource the resource requested.
+ */
+ private void assertNoRepoMetadata( String proxiedRepoId, String requestedResource )
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ File actualFile = new File( managedDefaultDir, proxiedFile );
+ assertFalse( "Repo specific metadata should not exist: " + actualFile, actualFile.exists() );
+ }
+
+ private void assertGroupMetadataContents( String requestedResource, String expectedPlugins[] )
+ throws Exception
+ {
+ File actualFile = new File( managedDefaultDir, requestedResource );
+ assertTrue( "Snapshot Metadata should exist: " + requestedResource, actualFile.exists() );
+
+ ProjectReference actualMetadata = createGroupReference( requestedResource );
+
+ assertGroupMetadata( actualFile, actualMetadata, expectedPlugins );
+ }
+
+ private ProjectReference createGroupReference( String requestedResource )
+ throws RepositoryMetadataException
+ {
+ ProjectReference projectReference = createProjectReference( requestedResource );
+ projectReference.setGroupId( projectReference.getGroupId() + "." + projectReference.getArtifactId() );
+ projectReference.setArtifactId( null );
+ return projectReference;
+ }
+
+ private void assertRepoGroupMetadataContents( String proxiedRepoId, String requestedResource,
+ String expectedPlugins[] )
+ throws Exception
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ File actualFile = new File( managedDefaultDir, proxiedFile );
+ assertTrue( "Repo Specific Group Metadata should exist: " + requestedResource, actualFile.exists() );
+
+ ProjectReference actualMetadata = createGroupReference( requestedResource );
+
+ assertGroupMetadata( actualFile, actualMetadata, expectedPlugins );
+ }
+
+ private void assertGroupMetadata( File actualFile, ProjectReference actualMetadata, String expectedPlugins[] )
+ throws Exception
+ {
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( actualMetadata.getGroupId() );
+
+ for ( String pluginId : expectedPlugins )
+ {
+ Plugin p = new Plugin();
+ p.setPrefix( pluginId );
+ p.setArtifactId( pluginId + "-maven-plugin" );
+ p.setName( "The " + pluginId + " Plugin" );
+ m.getPlugins().add( p );
+ }
+
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Test for the existance of the requestedResource in the default managed repository, and if it exists,
+ * does it contain the specified list of expected versions?
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertProjectMetadataContents( String requestedResource, String expectedVersions[],
+ String latestVersion, String releaseVersion )
+ throws Exception
+ {
+ File actualFile = new File( managedDefaultDir, requestedResource );
+ assertTrue( actualFile.exists() );
+
+ ProjectReference metadata = createProjectReference( requestedResource );
+
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( metadata.getGroupId() );
+ m.setArtifactId( metadata.getArtifactId() );
+ m.setLatestVersion( latestVersion );
+ m.setReleasedVersion( releaseVersion );
+
+ if ( expectedVersions != null )
+ {
+ m.getAvailableVersions().addAll( Arrays.asList( expectedVersions ) );
+ }
+
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Test for the existance of the requestedResource in the default managed repository, and if it exists,
+ * does it contain the expected release maven-metadata.xml contents?
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertReleaseMetadataContents( String requestedResource )
+ throws Exception
+ {
+ File actualFile = new File( managedDefaultDir, requestedResource );
+ assertTrue( "Release Metadata should exist: " + requestedResource, actualFile.exists() );
+
+ VersionedReference metadata = createVersionedReference( requestedResource );
+
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( metadata.getGroupId() );
+ m.setArtifactId( metadata.getArtifactId() );
+ m.setVersion( metadata.getVersion() );
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Test for the existance of the snapshot metadata in the default managed repository, and if it exists,
+ * does it contain the expected release maven-metadata.xml contents?
+ *
+ * @param requestedResource the requested resource
+ * @param expectedDate the date in "yyyyMMdd" format
+ * @param expectedTime the time in "hhmmss" format
+ * @param expectedBuildnumber the build number
+ * @throws Exception
+ */
+ private void assertSnapshotMetadataContents( String requestedResource, String expectedDate, String expectedTime,
+ int expectedBuildnumber )
+ throws Exception
+ {
+ File actualFile = new File( managedDefaultDir, requestedResource );
+ assertTrue( "Snapshot Metadata should exist: " + requestedResource, actualFile.exists() );
+
+ VersionedReference actualMetadata = createVersionedReference( requestedResource );
+
+ assertSnapshotMetadata( actualFile, actualMetadata, expectedDate, expectedTime, expectedBuildnumber );
+ }
+
+ /**
+ * Test for the existance of the proxied repository specific snapshot metadata in the default managed
+ * repository, and if it exists, does it contain the expected release maven-metadata.xml contents?
+ *
+ * @param proxiedRepoId the repository id of the proxied repository.
+ * @param requestedResource the requested resource
+ * @param expectedDate the date in "yyyyMMdd" format
+ * @param expectedTime the time in "hhmmss" format
+ * @param expectedBuildnumber the build number
+ * @throws Exception
+ */
+ private void assertRepoSnapshotMetadataContents( String proxiedRepoId, String requestedResource,
+ String expectedDate, String expectedTime, int expectedBuildnumber )
+ throws Exception
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ File actualFile = new File( managedDefaultDir, proxiedFile );
+ assertTrue( "Repo Specific Snapshot Metadata should exist: " + requestedResource, actualFile.exists() );
+
+ VersionedReference actualMetadata = createVersionedReference( requestedResource );
+
+ assertSnapshotMetadata( actualFile, actualMetadata, expectedDate, expectedTime, expectedBuildnumber );
+ }
+
+ private void assertSnapshotMetadata( File actualFile, VersionedReference actualMetadata, String expectedDate,
+ String expectedTime, int expectedBuildnumber )
+ throws RepositoryMetadataException, Exception
+ {
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( actualMetadata.getGroupId() );
+ m.setArtifactId( actualMetadata.getArtifactId() );
+ m.setVersion( VersionUtil.getBaseVersion( actualMetadata.getVersion() ) );
+
+ m.setSnapshotVersion( new SnapshotVersion() );
+
+ if ( StringUtils.isNotBlank( expectedDate ) && StringUtils.isNotBlank( expectedTime ) )
+ {
+ m.getSnapshotVersion().setTimestamp( expectedDate + "." + expectedTime );
+ }
+
+ m.getSnapshotVersion().setBuildNumber( expectedBuildnumber );
+
+ m.setLastUpdated( expectedDate + expectedTime );
+
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Ensures that the repository specific maven metadata file exists, and contains the appropriate
+ * list of expected versions within.
+ *
+ * @param proxiedRepoId
+ * @param requestedResource
+ * @param expectedProxyVersions
+ */
+ private void assertRepoProjectMetadata( String proxiedRepoId, String requestedResource,
+ String[] expectedProxyVersions )
+ throws Exception
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ File actualFile = new File( managedDefaultDir, proxiedFile );
+ assertTrue( actualFile.exists() );
+
+ ProjectReference metadata = createProjectReference( requestedResource );
+
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( metadata.getGroupId() );
+ m.setArtifactId( metadata.getArtifactId() );
+
+ if ( expectedProxyVersions != null )
+ {
+ m.getAvailableVersions().addAll( Arrays.asList( expectedProxyVersions ) );
+ }
+
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Ensures that the repository specific maven metadata file exists, and contains the appropriate
+ * list of expected versions within.
+ *
+ * @param proxiedRepoId
+ * @param requestedResource
+ */
+ private void assertRepoReleaseMetadataContents( String proxiedRepoId, String requestedResource )
+ throws Exception
+ {
+ String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
+
+ File actualFile = new File( managedDefaultDir, proxiedFile );
+ assertTrue( "Release metadata for repo should exist: " + actualFile, actualFile.exists() );
+
+ VersionedReference metadata = createVersionedReference( requestedResource );
+
+ // Build expected metadata XML
+ StringWriter expectedMetadataXml = new StringWriter();
+ ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
+ m.setGroupId( metadata.getGroupId() );
+ m.setArtifactId( metadata.getArtifactId() );
+ m.setVersion( metadata.getVersion() );
+ RepositoryMetadataWriter.write( m, expectedMetadataXml );
+
+ // Compare the file to the actual contents.
+ assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
+ }
+
+ /**
+ * Test for the non-existance of the requestedResource in the default managed repository.
+ *
+ * @param requestedResource the requested resource
+ * @throws Exception
+ */
+ private void assertResourceNotFound( String requestedResource )
+ throws Exception
+ {
+ File actualFile = new File( managedDefaultDir, requestedResource );
+ assertFalse( "Resource should not exist: " + requestedResource, actualFile.exists() );
+ }
+
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.maven.archiva.configuration.ArchivaConfiguration;
+import org.apache.maven.archiva.configuration.Configuration;
+import org.apache.maven.archiva.configuration.ConfigurationListener;
+import org.apache.maven.archiva.configuration.FileType;
+import org.apache.maven.archiva.configuration.FileTypes;
+import org.apache.maven.archiva.configuration.RepositoryScanningConfiguration;
+import org.codehaus.plexus.registry.Registry;
+import org.codehaus.plexus.registry.RegistryException;
+import org.codehaus.plexus.registry.RegistryListener;
+import org.easymock.MockControl;
+import org.springframework.stereotype.Service;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import javax.annotation.PostConstruct;
+
+/**
+ * MockConfiguration
+ *
+ * @version $Id$
+ */
+@Service( "archivaConfiguration#mock" )
+public class MockConfiguration
+ implements ArchivaConfiguration
+{
+
+ private Configuration configuration = new Configuration();
+
+ private Set<RegistryListener> registryListeners = new HashSet<RegistryListener>();
+
+ private Set<ConfigurationListener> configListeners = new HashSet<ConfigurationListener>();
+
+ private MockControl registryControl;
+
+ private Registry registryMock;
+
+ public MockConfiguration()
+ {
+ registryControl = MockControl.createNiceControl( Registry.class );
+ registryMock = (Registry) registryControl.getMock();
+ }
+
+ @PostConstruct
+ public void initialize()
+ throws Exception
+ {
+
+ configuration.setRepositoryScanning( new RepositoryScanningConfiguration()
+ {
+ @Override
+ public List<FileType> getFileTypes()
+ {
+ FileType fileType = new FileType();
+ fileType.setId( FileTypes.ARTIFACTS );
+ fileType.setPatterns( Collections.singletonList( "**/*" ) );
+ return Collections.singletonList( fileType );
+ }
+ } );
+ }
+
+ public void addChangeListener( RegistryListener listener )
+ {
+ registryListeners.add( listener );
+ }
+
+ public Configuration getConfiguration()
+ {
+ return configuration;
+ }
+
+ public void save( Configuration configuration )
+ throws RegistryException
+ {
+ /* do nothing */
+ }
+
+ public void triggerChange( String name, String value )
+ {
+ for ( RegistryListener listener : registryListeners )
+ {
+ try
+ {
+ listener.afterConfigurationChange( registryMock, name, value );
+ }
+ catch ( Exception e )
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public void addListener( ConfigurationListener listener )
+ {
+ configListeners.add( listener );
+ }
+
+ public void removeListener( ConfigurationListener listener )
+ {
+ configListeners.remove( listener );
+ }
+
+ public boolean isDefaulted()
+ {
+ return false;
+ }
+
+ public void reload()
+ {
+ // no op
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import org.apache.maven.archiva.model.ArtifactReference;
+import org.apache.maven.archiva.policies.CachedFailuresPolicy;
+import org.apache.maven.archiva.policies.ChecksumPolicy;
+import org.apache.maven.archiva.policies.ReleasesPolicy;
+import org.apache.maven.archiva.policies.SnapshotsPolicy;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * SnapshotTransferTest
+ *
+ * @version $Id$
+ */
+public class SnapshotTransferTest
+ extends AbstractProxyTestCase
+{
+ @Test
+ public void testSnapshotNonExistant()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/does-not-exist/1.0-SNAPSHOT/does-not-exist-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ expectedFile.delete();
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testTimestampDrivenSnapshotNotPresentAlready()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-timestamped-snapshot/1.0-SNAPSHOT/get-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ expectedFile.delete();
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testNewerTimestampDrivenSnapshotOnFirstRepo()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+ expectedFile.setLastModified( getPastDate().getTime() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testOlderTimestampDrivenSnapshotOnFirstRepo()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, path );
+
+ setManagedNewerThanRemote( expectedFile, remoteFile );
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
+
+ // Attempt to download.
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ // Should not have downloaded as managed is newer than remote.
+ assertNotDownloaded( downloadedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ /**
+ * TODO: Has problems with wagon implementation not preserving timestamp.
+ */
+ /*
+ public void testNewerTimestampDrivenSnapshotOnSecondRepoThanFirstNotPresentAlready()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/get-timestamped-snapshot-in-both-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = createArtifactReference( "default", path );
+
+ expectedFile.delete();
+ assertFalse( expectedFile.exists() );
+
+ // Create customized proxy / target repository
+ File targetProxyDir = saveTargetedRepositoryConfig( ID_PROXIED1_TARGET, REPOPATH_PROXIED1,
+ REPOPATH_PROXIED1_TARGET, "default" );
+
+ new File( targetProxyDir, path ).setLastModified( getPastDate().getTime() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1_TARGET, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
+ SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
+ SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ // Should have downloaded the content from proxy2, as proxy1 has an old (by file.lastModified check) version.
+ File proxiedFile = new File( REPOPATH_PROXIED2, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ public void testOlderTimestampDrivenSnapshotOnSecondRepoThanFirstNotPresentAlready()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/get-timestamped-snapshot-in-both-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = createArtifactReference( "default", path );
+
+ expectedFile.delete();
+ assertFalse( expectedFile.exists() );
+
+ // Create customized proxy / target repository
+ File targetProxyDir = saveTargetedRepositoryConfig( ID_PROXIED2_TARGET, REPOPATH_PROXIED2,
+ REPOPATH_PROXIED2_TARGET, "default" );
+
+ new File( targetProxyDir, path ).setLastModified( getPastDate().getTime() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
+ SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2_TARGET, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
+ SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1_TARGET, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ } */
+
+ @Test
+ public void testTimestampDrivenSnapshotNotExpired()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1, path );
+ proxiedFile.setLastModified( getFutureDate().getTime() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testTimestampDrivenSnapshotNotUpdated()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ File remoteFile = new File( REPOPATH_PROXIED1, path );
+
+ setManagedNewerThanRemote( expectedFile, remoteFile, 12000000 );
+ long expectedTimestamp = expectedFile.lastModified();
+
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ assertNotDownloaded( downloadedFile );
+ assertNotModified( expectedFile, expectedTimestamp );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testTimestampDrivenSnapshotNotPresentAlreadyExpiredCacheFailure()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-timestamped-snapshot/1.0-SNAPSHOT/get-timestamped-snapshot-1.0-SNAPSHOT.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ expectedFile.delete();
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES , false);
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
+ SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES , false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testMetadataDrivenSnapshotNotPresentAlready()
+ throws Exception
+ {
+ String path = "org/apache/maven/test/get-metadata-snapshot/1.0-SNAPSHOT/get-metadata-snapshot-1.0-20050831.101112-1.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ expectedFile.delete();
+ assertFalse( expectedFile.exists() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+
+ @Test
+ public void testGetMetadataDrivenSnapshotRemoteUpdate()
+ throws Exception
+ {
+ // Metadata driven snapshots (using a full timestamp) are treated like a release. It is the timing of the
+ // updates to the metadata files that triggers which will be downloaded
+
+ String path = "org/apache/maven/test/get-present-metadata-snapshot/1.0-SNAPSHOT/get-present-metadata-snapshot-1.0-20050831.101112-1.jar";
+ setupTestableManagedRepository( path );
+
+ File expectedFile = new File( managedDefaultDir, path );
+ ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
+
+ assertTrue( expectedFile.exists() );
+
+ expectedFile.setLastModified( getPastDate().getTime() );
+
+ // Configure Connector (usually done within archiva.xml configuration)
+ saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
+
+ File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
+
+ File proxiedFile = new File( REPOPATH_PROXIED1, path );
+ assertFileEquals( expectedFile, downloadedFile, proxiedFile );
+ assertNoTempFiles( expectedFile );
+ }
+}
--- /dev/null
+package org.apache.archiva.proxy;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.maven.wagon.ConnectionException;
+import org.apache.maven.wagon.ResourceDoesNotExistException;
+import org.apache.maven.wagon.TransferFailedException;
+import org.apache.maven.wagon.Wagon;
+import org.apache.maven.wagon.authentication.AuthenticationException;
+import org.apache.maven.wagon.authentication.AuthenticationInfo;
+import org.apache.maven.wagon.authorization.AuthorizationException;
+import org.apache.maven.wagon.events.SessionListener;
+import org.apache.maven.wagon.events.TransferListener;
+import org.apache.maven.wagon.proxy.ProxyInfo;
+import org.apache.maven.wagon.proxy.ProxyInfoProvider;
+import org.apache.maven.wagon.repository.Repository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+/**
+ * A dummy wagon implementation
+ *
+ */
+@Service("wagon#test")
+public class WagonDelegate
+ implements Wagon
+{
+ private Logger log = LoggerFactory.getLogger( WagonDelegate.class );
+
+ private Wagon delegate;
+
+ private String contentToGet;
+
+ public void get( String resourceName, File destination )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ log.debug( ".get({}, {})", resourceName, destination );
+ delegate.get( resourceName, destination );
+ create( destination );
+ }
+
+ public boolean getIfNewer( String resourceName, File destination, long timestamp )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ log.info( ".getIfNewer(" + resourceName + ", " + destination + ", " + timestamp + ")" );
+
+ boolean result = delegate.getIfNewer( resourceName, destination, timestamp );
+ createIfMissing( destination );
+ return result;
+ }
+
+ public void put( File source, String destination )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ delegate.put( source, destination );
+ }
+
+ public void putDirectory( File sourceDirectory, String destinationDirectory )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ delegate.putDirectory( sourceDirectory, destinationDirectory );
+ }
+
+ public boolean resourceExists( String resourceName )
+ throws TransferFailedException, AuthorizationException
+ {
+ return delegate.resourceExists( resourceName );
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<String> getFileList( String destinationDirectory )
+ throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
+ {
+ return delegate.getFileList( destinationDirectory );
+ }
+
+ public boolean supportsDirectoryCopy()
+ {
+ return delegate.supportsDirectoryCopy();
+ }
+
+ public void setTimeout(int val)
+ {
+ // ignore
+ }
+
+ public int getTimeout()
+ {
+ return 0;
+ }
+
+ public Repository getRepository()
+ {
+ return delegate.getRepository();
+ }
+
+ public void connect( Repository source )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source );
+ }
+
+ public void connect( Repository source, ProxyInfo proxyInfo )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, proxyInfo );
+ }
+
+ public void connect( Repository source, ProxyInfoProvider proxyInfoProvider )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, proxyInfoProvider );
+ }
+
+ public void connect( Repository source, AuthenticationInfo authenticationInfo )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, authenticationInfo );
+ }
+
+ public void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfo proxyInfo )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, authenticationInfo, proxyInfo );
+ }
+
+ public void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfoProvider proxyInfoProvider )
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.connect( source, authenticationInfo, proxyInfoProvider );
+ }
+
+ @SuppressWarnings("deprecation")
+ public void openConnection()
+ throws ConnectionException, AuthenticationException
+ {
+ delegate.openConnection();
+ }
+
+ public void disconnect()
+ throws ConnectionException
+ {
+ delegate.disconnect();
+ }
+
+ public void addSessionListener( SessionListener listener )
+ {
+ delegate.addSessionListener( listener );
+ }
+
+ public void removeSessionListener( SessionListener listener )
+ {
+ delegate.removeSessionListener( listener );
+ }
+
+ public boolean hasSessionListener( SessionListener listener )
+ {
+ return delegate.hasSessionListener( listener );
+ }
+
+ public void addTransferListener( TransferListener listener )
+ {
+ delegate.addTransferListener( listener );
+ }
+
+ public void removeTransferListener( TransferListener listener )
+ {
+ delegate.removeTransferListener( listener );
+ }
+
+ public boolean hasTransferListener( TransferListener listener )
+ {
+ return delegate.hasTransferListener( listener );
+ }
+
+ public boolean isInteractive()
+ {
+ return delegate.isInteractive();
+ }
+
+ public void setInteractive( boolean interactive )
+ {
+ delegate.setInteractive( interactive );
+ }
+
+ public void setDelegate( Wagon delegate )
+ {
+ this.delegate = delegate;
+ }
+
+ void setContentToGet( String content )
+ {
+ contentToGet = content;
+ }
+
+ private void createIfMissing( File destination )
+ {
+ // since the mock won't actually copy a file, create an empty one to simulate file existence
+ if ( !destination.exists() )
+ {
+ create( destination );
+ }
+ }
+
+ private void create( File destination )
+ {
+ try
+ {
+ destination.getParentFile().mkdirs();
+ if ( contentToGet == null )
+ {
+ destination.createNewFile();
+ }
+ else
+ {
+ FileUtils.writeStringToFile( new File( destination.getAbsolutePath() ), contentToGet, null );
+ }
+ }
+ catch ( IOException e )
+ {
+ throw new RuntimeException( e.getMessage(), e );
+ }
+ }
+}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import net.sf.ehcache.CacheManager;
-import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
-import org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin;
-import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.maven.archiva.configuration.ArchivaConfiguration;
-import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
-import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
-import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.PropagateErrorsDownloadPolicy;
-import org.apache.maven.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.apache.maven.archiva.repository.ManagedRepositoryContent;
-import org.apache.maven.wagon.Wagon;
-import org.codehaus.plexus.util.FileUtils;
-import org.easymock.ArgumentsMatcher;
-import org.easymock.MockControl;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import javax.inject.Inject;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.Locale;
-
-import static org.junit.Assert.*;
-
-/**
- * AbstractProxyTestCase
- *
- * @version $Id$
- */
-@RunWith( SpringJUnit4ClassRunner.class )
-@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
-public abstract class AbstractProxyTestCase
-{
- @Inject
- protected ApplicationContext applicationContext;
-
- protected static final String ID_LEGACY_PROXIED = "legacy-proxied";
-
- protected static final String ID_PROXIED1 = "proxied1";
-
- protected static final String ID_PROXIED1_TARGET = "proxied1-target";
-
- protected static final String ID_PROXIED2 = "proxied2";
-
- protected static final String ID_PROXIED2_TARGET = "proxied2-target";
-
- protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
-
- protected static final String ID_LEGACY_MANAGED = "legacy-managed-repository";
-
- protected static final String REPOPATH_PROXIED_LEGACY = "src/test/repositories/legacy-proxied";
-
- protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
-
- protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
-
- protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
-
- protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
-
- protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
-
- // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
-
- protected static final String REPOPATH_LEGACY_MANAGED = "src/test/repositories/legacy-managed";
-
- protected static final String REPOPATH_LEGACY_MANAGED_TARGET = "target/test-repository/legacy-managed";
-
- protected MockControl wagonMockControl;
-
- protected Wagon wagonMock;
-
-
- protected RepositoryProxyConnectors proxyHandler;
-
- protected ManagedRepositoryContent managedDefaultRepository;
-
- protected File managedDefaultDir;
-
- protected ManagedRepositoryContent managedLegacyRepository;
-
- protected File managedLegacyDir;
-
- protected MockConfiguration config;
-
- protected Logger log = LoggerFactory.getLogger( getClass() );
-
- WagonDelegate delegate;
-
- @Inject
- protected ManagedRepositoryAdmin managedRepositoryAdmin;
-
- @Inject
- PlexusSisuBridge plexusSisuBridge;
-
- @Before
- public void setUp()
- throws Exception
- {
- config =
- (MockConfiguration) applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
-
- config.getConfiguration().setManagedRepositories( new ArrayList<ManagedRepositoryConfiguration>() );
- config.getConfiguration().setRemoteRepositories( new ArrayList<RemoteRepositoryConfiguration>() );
- config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() );
-
- // Setup source repository (using default layout)
- String name = getClass().getSimpleName();
- String repoPath = "target/test-repository/managed/" + name;
- File repoLocation = new File( repoPath );
-
- managedDefaultRepository =
- createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath, "default" );
-
- managedDefaultDir = new File( managedDefaultRepository.getRepoRoot() );
-
- ManagedRepository repoConfig = managedDefaultRepository.getRepository();
-
- ( (DefaultManagedRepositoryAdmin) applicationContext.getBean(
- ManagedRepositoryAdmin.class ) ).setArchivaConfiguration( config );
-
- applicationContext.getBean( ManagedRepositoryAdmin.class ).addManagedRepository( repoConfig, false, null );
- //config.getConfiguration().addManagedRepository( repoConfig );
-
- // Setup source repository (using legacy layout)
- repoLocation = new File( REPOPATH_LEGACY_MANAGED_TARGET );
- if ( repoLocation.exists() )
- {
- FileUtils.deleteDirectory( repoLocation );
- }
- copyDirectoryStructure( new File( REPOPATH_LEGACY_MANAGED ), repoLocation );
-
- managedLegacyRepository =
- createRepository( ID_LEGACY_MANAGED, "Legacy Managed Repository", REPOPATH_LEGACY_MANAGED_TARGET,
- "legacy" );
-
- managedLegacyDir = new File( managedLegacyRepository.getRepoRoot() );
-
- repoConfig = managedLegacyRepository.getRepository();
-
- //config.getConfiguration().addManagedRepository( repoConfig );
- applicationContext.getBean( ManagedRepositoryAdmin.class ).addManagedRepository( repoConfig, false, null );
-
- // Setup target (proxied to) repository.
- saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1",
- new File( REPOPATH_PROXIED1 ).toURL().toExternalForm(), "default" );
-
- // Setup target (proxied to) repository.
- saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2",
- new File( REPOPATH_PROXIED2 ).toURL().toExternalForm(), "default" );
-
- // Setup target (proxied to) repository using legacy layout.
- saveRemoteRepositoryConfig( ID_LEGACY_PROXIED, "Proxied Legacy Repository",
- new File( REPOPATH_PROXIED_LEGACY ).toURL().toExternalForm(), "legacy" );
-
- // Setup the proxy handler.
- //proxyHandler = applicationContext.getBean (RepositoryProxyConnectors) lookup( RepositoryProxyConnectors.class.getName() );
-
- proxyHandler = applicationContext.getBean( "repositoryProxyConnectors#test", RepositoryProxyConnectors.class );
-
- // Setup the wagon mock.
- wagonMockControl = MockControl.createNiceControl( Wagon.class );
- wagonMock = (Wagon) wagonMockControl.getMock();
-
- delegate = (WagonDelegate) plexusSisuBridge.lookup( Wagon.class, "test" );
-
- delegate.setDelegate( wagonMock );
-
- CacheManager.getInstance().clearAll();
-
- log.info( "\n.\\ " + name + "() \\._________________________________________\n" );
- }
-
- protected static final ArgumentsMatcher customWagonGetIfNewerMatcher = new ArgumentsMatcher()
- {
-
- public boolean matches( Object[] expected, Object[] actual )
- {
- if ( expected.length < 1 || actual.length < 1 )
- {
- return false;
- }
- return MockControl.ARRAY_MATCHER.matches( ArrayUtils.remove( expected, 1 ),
- ArrayUtils.remove( actual, 1 ) );
- }
-
- public String toString( Object[] arguments )
- {
- return ArrayUtils.toString( arguments );
- }
- };
-
- protected static final ArgumentsMatcher customWagonGetMatcher = new ArgumentsMatcher()
- {
-
- public boolean matches( Object[] expected, Object[] actual )
- {
- if ( expected.length == 2 && actual.length == 2 )
- {
- if ( expected[0] == null && actual[0] == null )
- {
- return true;
- }
-
- if ( expected[0] == null )
- {
- return actual[0] == null;
- }
-
- if ( actual[0] == null )
- {
- return expected[0] == null;
- }
-
- return expected[0].equals( actual[0] );
- }
- return false;
- }
-
- public String toString( Object[] arguments )
- {
- return ArrayUtils.toString( arguments );
- }
- };
-
-
- protected void assertChecksums( File expectedFile, String expectedSha1Contents, String expectedMd5Contents )
- throws Exception
- {
- File sha1File = new File( expectedFile.getAbsolutePath() + ".sha1" );
- File md5File = new File( expectedFile.getAbsolutePath() + ".md5" );
-
- if ( expectedSha1Contents == null )
- {
- assertFalse( "SHA1 File should NOT exist: " + sha1File.getPath(), sha1File.exists() );
- }
- else
- {
- assertTrue( "SHA1 File should exist: " + sha1File.getPath(), sha1File.exists() );
- String actualSha1Contents = readChecksumFile( sha1File );
- assertEquals( "SHA1 File contents: " + sha1File.getPath(), expectedSha1Contents, actualSha1Contents );
- }
-
- if ( expectedMd5Contents == null )
- {
- assertFalse( "MD5 File should NOT exist: " + md5File.getPath(), md5File.exists() );
- }
- else
- {
- assertTrue( "MD5 File should exist: " + md5File.getPath(), md5File.exists() );
- String actualMd5Contents = readChecksumFile( md5File );
- assertEquals( "MD5 File contents: " + md5File.getPath(), expectedMd5Contents, actualMd5Contents );
- }
- }
-
- protected void assertFileEquals( File expectedFile, File actualFile, File sourceFile )
- throws Exception
- {
- assertNotNull( "Expected File should not be null.", expectedFile );
- assertNotNull( "Actual File should not be null.", actualFile );
-
- assertTrue( "Check actual file exists.", actualFile.exists() );
- assertEquals( "Check filename path is appropriate.", expectedFile.getCanonicalPath(),
- actualFile.getCanonicalPath() );
- assertEquals( "Check file path matches.", expectedFile.getAbsolutePath(), actualFile.getAbsolutePath() );
-
- String expectedContents = org.apache.commons.io.FileUtils.readFileToString( sourceFile, null );
- String actualContents = org.apache.commons.io.FileUtils.readFileToString( actualFile, null );
- assertEquals( "Check file contents.", expectedContents, actualContents );
- }
-
- protected void assertNotDownloaded( File downloadedFile )
- {
- assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
- }
-
- @SuppressWarnings( "unchecked" )
- protected void assertNoTempFiles( File expectedFile )
- {
- File workingDir = expectedFile.getParentFile();
- if ( ( workingDir == null ) || !workingDir.isDirectory() )
- {
- return;
- }
-
- Collection<File> tmpFiles =
- org.apache.commons.io.FileUtils.listFiles( workingDir, new String[]{ "tmp" }, false );
- if ( !tmpFiles.isEmpty() )
- {
- StringBuffer emsg = new StringBuffer();
- emsg.append( "Found Temp Files in dir: " ).append( workingDir.getPath() );
- for ( File tfile : tmpFiles )
- {
- emsg.append( "\n " ).append( tfile.getName() );
- }
- fail( emsg.toString() );
- }
- }
-
- /**
- * A faster recursive copy that omits .svn directories.
- *
- * @param sourceDirectory the source directory to copy
- * @param destDirectory the target location
- * @throws java.io.IOException if there is a copying problem
- * @todo get back into plexus-utils, share with converter module
- */
- protected void copyDirectoryStructure( File sourceDirectory, File destDirectory )
- throws IOException
- {
- if ( !sourceDirectory.exists() )
- {
- throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." );
- }
-
- File[] files = sourceDirectory.listFiles();
-
- String sourcePath = sourceDirectory.getAbsolutePath();
-
- for ( int i = 0; i < files.length; i++ )
- {
- File file = files[i];
-
- String dest = file.getAbsolutePath();
-
- dest = dest.substring( sourcePath.length() + 1 );
-
- File destination = new File( destDirectory, dest );
-
- if ( file.isFile() )
- {
- destination = destination.getParentFile();
-
- org.apache.commons.io.FileUtils.copyFile( file, new File( destination, file.getName() ), false );
- // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
- //FileUtils.copyFileToDirectory( file, destination );
- }
- else if ( file.isDirectory() )
- {
- if ( !".svn".equals( file.getName() ) )
- {
- if ( !destination.exists() && !destination.mkdirs() )
- {
- throw new IOException(
- "Could not create destination directory '" + destination.getAbsolutePath() + "'." );
- }
-
- copyDirectoryStructure( file, destination );
- }
- }
- else
- {
- throw new IOException( "Unknown file type: " + file.getAbsolutePath() );
- }
- }
- }
-
- protected ManagedRepositoryContent createManagedLegacyRepository()
- throws Exception
- {
- return createRepository( "testManagedLegacyRepo", "Test Managed (Legacy) Repository",
- "src/test/repositories/legacy-managed", "legacy" );
- }
-
- protected ManagedRepositoryContent createProxiedLegacyRepository()
- throws Exception
- {
- return createRepository( "testProxiedLegacyRepo", "Test Proxied (Legacy) Repository",
- "src/test/repositories/legacy-proxied", "legacy" );
- }
-
- protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
- throws Exception
- {
- ManagedRepository repo = new ManagedRepository();
- repo.setId( id );
- repo.setName( name );
- repo.setLocation( path );
- repo.setLayout( layout );
-
- ManagedRepositoryContent repoContent =
- applicationContext.getBean( "managedRepositoryContent#" + layout, ManagedRepositoryContent.class );
- repoContent.setRepository( repo );
- return repoContent;
- }
-
- /**
- * Read the first line from the checksum file, and return it (trimmed).
- */
- protected String readChecksumFile( File checksumFile )
- throws Exception
- {
- FileReader freader = null;
- BufferedReader buf = null;
-
- try
- {
- freader = new FileReader( checksumFile );
- buf = new BufferedReader( freader );
- return buf.readLine();
- }
- finally
- {
- if ( buf != null )
- {
- buf.close();
- }
-
- if ( freader != null )
- {
- freader.close();
- }
- }
- }
-
- protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
- {
- saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
- CachedFailuresPolicy.NO, disabled );
- }
-
- protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
- String snapshotPolicy, String cacheFailuresPolicy, boolean disabled )
- {
- saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
- PropagateErrorsDownloadPolicy.QUEUE, disabled );
- }
-
- protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
- String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
- boolean disabled )
- {
- saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
- errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
- }
-
- protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
- String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
- String errorOnUpdatePolicy, boolean disabled )
- {
- ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
- connectorConfig.setSourceRepoId( sourceRepoId );
- connectorConfig.setTargetRepoId( targetRepoId );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy );
- connectorConfig.setDisabled( disabled );
-
- int count = config.getConfiguration().getProxyConnectors().size();
- config.getConfiguration().addProxyConnector( connectorConfig );
-
- // Proper Triggering ...
- String prefix = "proxyConnectors.proxyConnector(" + count + ")";
- config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
- config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
- config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
- config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
- config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
- config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
- config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
- config.triggerChange( prefix + ".policies.propagate-errors",
- connectorConfig.getPolicy( "propagate-errors", "" ) );
- config.triggerChange( prefix + ".policies.propagate-errors-on-update",
- connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
- }
-
- protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
- {
- ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
-
- repoConfig.setId( id );
- repoConfig.setName( name );
- repoConfig.setLayout( layout );
-
- repoConfig.setLocation( path );
-
- int count = config.getConfiguration().getManagedRepositories().size();
- config.getConfiguration().addManagedRepository( repoConfig );
-
- String prefix = "managedRepositories.managedRepository(" + count + ")";
- config.triggerChange( prefix + ".id", repoConfig.getId() );
- config.triggerChange( prefix + ".name", repoConfig.getName() );
- config.triggerChange( prefix + ".location", repoConfig.getLocation() );
- config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
- }
-
- protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
- {
- RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
-
- repoConfig.setId( id );
- repoConfig.setName( name );
- repoConfig.setLayout( layout );
- repoConfig.setUrl( url );
-
- int count = config.getConfiguration().getRemoteRepositories().size();
- config.getConfiguration().addRemoteRepository( repoConfig );
-
- String prefix = "remoteRepositories.remoteRepository(" + count + ")";
- config.triggerChange( prefix + ".id", repoConfig.getId() );
- config.triggerChange( prefix + ".name", repoConfig.getName() );
- config.triggerChange( prefix + ".url", repoConfig.getUrl() );
- config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
- }
-
- protected File saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
- throws IOException
- {
- File repoLocation = new File( targetPath );
- FileUtils.deleteDirectory( repoLocation );
- copyDirectoryStructure( new File( originalPath ), repoLocation );
-
- saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
-
- return repoLocation;
- }
-
-
- /**
- * Copy the specified resource directory from the src/test/repository/managed/ to
- * the testable directory under target/test-repository/managed/${testName}/
- *
- * @param resourcePath
- * @throws IOException
- */
- protected void setupTestableManagedRepository( String resourcePath )
- throws IOException
- {
- String resourceDir = resourcePath;
-
- if ( !resourcePath.endsWith( "/" ) )
- {
- int idx = resourcePath.lastIndexOf( '/' );
- resourceDir = resourcePath.substring( 0, idx );
- }
-
- File sourceRepoDir = new File( REPOPATH_DEFAULT_MANAGED );
- File sourceDir = new File( sourceRepoDir, resourceDir );
-
- File destRepoDir = managedDefaultDir;
- File destDir = new File( destRepoDir, resourceDir );
-
- // Cleanout destination dirs.
- if ( destDir.exists() )
- {
- FileUtils.deleteDirectory( destDir );
- }
-
- // Make the destination dir.
- destDir.mkdirs();
-
- // Test the source dir.
- if ( !sourceDir.exists() )
- {
- // This is just a warning.
- System.err.println(
- "[WARN] Skipping setup of testable managed repository, source dir does not exist: " + sourceDir );
- }
- else
- {
-
- // Test that the source is a dir.
- if ( !sourceDir.isDirectory() )
- {
- fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
- }
-
- // Copy directory structure.
- copyDirectoryStructure( sourceDir, destDir );
- }
- }
-
- protected void setManagedNewerThanRemote( File managedFile, File remoteFile )
- {
- setManagedNewerThanRemote( managedFile, remoteFile, 55000 );
- }
-
- protected void setManagedNewerThanRemote( File managedFile, File remoteFile, long time )
- {
- assertTrue( "Managed File should exist: ", managedFile.exists() );
- assertTrue( "Remote File should exist: ", remoteFile.exists() );
-
- managedFile.setLastModified( remoteFile.lastModified() + time );
-
- assertTrue( managedFile.lastModified() > remoteFile.lastModified() );
- }
-
- protected void setManagedOlderThanRemote( File managedFile, File remoteFile )
- {
- setManagedOlderThanRemote( managedFile, remoteFile, 55000 );
- }
-
- protected void setManagedOlderThanRemote( File managedFile, File remoteFile, long time )
- {
- assertTrue( "Managed File should exist: ", managedFile.exists() );
- assertTrue( "Remote File should exist: ", remoteFile.exists() );
-
- managedFile.setLastModified( remoteFile.lastModified() - time );
-
- assertTrue( managedFile.lastModified() < remoteFile.lastModified() );
-
- }
-
- protected void assertNotModified( File file, long expectedModificationTime )
- {
- assertEquals( "File <" + file.getAbsolutePath() + "> not have been modified.", expectedModificationTime,
- file.lastModified() );
- }
-
- protected void assertNotExistsInManagedLegacyRepo( File file )
- throws Exception
- {
- String managedLegacyPath = managedLegacyDir.getCanonicalPath();
- String testFile = file.getCanonicalPath();
-
- assertTrue(
- "Unit Test Failure: File <" + testFile + "> should be have been defined within the legacy managed path of <"
- + managedLegacyPath + ">", testFile.startsWith( managedLegacyPath ) );
-
- assertFalse( "File < " + testFile + "> should not exist in managed legacy repository.", file.exists() );
- }
-
- protected void assertNotExistsInManagedDefaultRepo( File file )
- throws Exception
- {
- String managedDefaultPath = managedDefaultDir.getCanonicalPath();
- String testFile = file.getCanonicalPath();
-
- assertTrue( "Unit Test Failure: File <" + testFile
- + "> should be have been defined within the managed default path of <" + managedDefaultPath
- + ">", testFile.startsWith( managedDefaultPath ) );
-
- assertFalse( "File < " + testFile + "> should not exist in managed default repository.", file.exists() );
- }
-
- protected static Date getFutureDate()
- throws ParseException
- {
- Calendar cal = Calendar.getInstance();
- cal.add( Calendar.YEAR, 1 );
- return cal.getTime();
- }
-
- protected static Date getPastDate()
- throws ParseException
- {
- return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.archiva.common.utils.PathUtil;
-import org.apache.maven.archiva.model.ArtifactReference;
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.apache.maven.archiva.policies.urlcache.UrlFailureCache;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.junit.Test;
-
-import java.io.File;
-import javax.inject.Inject;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-
-/**
- * CacheFailuresTransferTest
- *
- * @version $Id$
- */
-public class CacheFailuresTransferTest
- extends AbstractProxyTestCase
-{
- // TODO: test some hard failures (eg TransferFailedException)
- // TODO: test the various combinations of fetchFrom* (note: need only test when caching is enabled)
-
- @Test
- public void testGetWithCacheFailuresOn()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- File expectedFile = new File( managedDefaultDir.getAbsoluteFile(), path );
- setupTestableManagedRepository( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Configure Repository (usually done within archiva.xml configuration)
- saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "test://bad.machine.com/repo/", "default" );
- saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "test://bad.machine.com/anotherrepo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
- saveConnector( ID_DEFAULT_MANAGED, "badproxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
-
- wagonMock.get( path, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
-
- wagonMockControl.setMatcher( customWagonGetMatcher );
-
- wagonMockControl.setThrowable( new ResourceDoesNotExistException( "resource does not exist." ), 2 );
-
- wagonMockControl.replay();
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- wagonMockControl.verify();
-
- // Second attempt to download same artifact use cache
- wagonMockControl.reset();
- wagonMockControl.replay();
- downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
- wagonMockControl.verify();
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetWithCacheFailuresOff()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- File expectedFile = new File( managedDefaultDir.getAbsoluteFile(), path );
- setupTestableManagedRepository( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Configure Repository (usually done within archiva.xml configuration)
- saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "test://bad.machine.com/repo/", "default" );
- saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "test://bad.machine.com/anotherrepo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, "badproxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- wagonMock.get( path, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
-
- wagonMockControl.setMatcher( customWagonGetMatcher );
- wagonMockControl.setThrowable( new ResourceDoesNotExistException( "resource does not exist." ), 2 );
-
- wagonMockControl.replay();
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- wagonMockControl.verify();
-
- // Second attempt to download same artifact DOES NOT use cache
- wagonMockControl.reset();
- wagonMock.get( path, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
-
- wagonMockControl.setMatcher( customWagonGetMatcher );
- wagonMockControl.setThrowable( new ResourceDoesNotExistException( "resource does not exist." ), 2 );
- wagonMockControl.replay();
-
- downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- wagonMockControl.verify();
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetWhenInBothProxiedButFirstCacheFailure()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- setupTestableManagedRepository( path );
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- expectedFile.delete();
- assertFalse( expectedFile.exists() );
-
- String url = PathUtil.toUrl( REPOPATH_PROXIED1 + "/" + path );
-
- // Intentionally set failure on url in proxied1 (for test)
- UrlFailureCache failurlCache = lookupUrlFailureCache();
- failurlCache.cacheFailure( url );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
- saveConnector( ID_DEFAULT_MANAGED, "proxied2", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- // Validate that file actually came from proxied2 (as intended).
- File proxied2File = new File( REPOPATH_PROXIED2, path );
- assertFileEquals( expectedFile, downloadedFile, proxied2File );
- assertNoTempFiles( expectedFile );
- }
-
- @Inject
- UrlFailureCache urlFailureCache;
-
- protected UrlFailureCache lookupUrlFailureCache()
- throws Exception
- {
- //UrlFailureCache urlFailureCache = (UrlFailureCache) lookup( "urlFailureCache" );
- assertNotNull( "URL Failure Cache cannot be null.", urlFailureCache );
- return urlFailureCache;
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.commons.io.FileUtils;
-import org.apache.maven.archiva.model.ArtifactReference;
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.junit.Test;
-
-import java.io.File;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-
-/**
- * ChecksumTransferTest
- *
- * @version $Id$
- */
-public class ChecksumTransferTest
- extends AbstractProxyTestCase
-{
- @Test
- public void testGetChecksumWhenConnectorIsDisabled()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-right/1.0/get-checksum-both-right-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, true );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNull( downloadedFile );
- }
-
- @Test
- public void testGetChecksumBothCorrect()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-right/1.0/get-checksum-both-right-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "066d76e459f7782c312c31e8a11b3c0f1e3e43a7 *get-checksum-both-right-1.0.jar",
- "e58f30c6a150a2e843552438d18e15cb *get-checksum-both-right-1.0.jar" );
- }
-
- @Test
- public void testGetChecksumCorrectSha1NoMd5()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-only/1.0/get-checksum-sha1-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "748a3a013bf5eacf2bbb40a2ac7d37889b728837 *get-checksum-sha1-only-1.0.jar",
- null );
- }
-
- @Test
- public void testGetChecksumNoSha1CorrectMd5()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, null, "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
- }
-
- @Test
- public void testGetWithNoChecksumsUsingIgnoredSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, null, null );
- }
-
- @Test
- public void testGetChecksumBadSha1BadMd5IgnoredSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
- }
-
- @Test
- public void testGetChecksumBadSha1BadMd5FailSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertChecksums( expectedFile, null, null );
- }
-
- @Test
- public void testGetChecksumBadSha1BadMd5FixSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-both-bad/1.0/get-checksum-both-bad-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "4ec20a12dc91557330bd0b39d1805be5e329ae56 get-checksum-both-bad-1.0.jar",
- "a292491a35925465e693a44809a078b5 get-checksum-both-bad-1.0.jar" );
- }
-
- @Test
- public void testGetChecksumCorrectSha1BadMd5UsingFailSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertChecksums( expectedFile, null, null );
- }
-
- @Test
- public void testGetChecksumNoSha1CorrectMd5UsingFailSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- // This is a success situation. No SHA1 with a Good MD5.
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, null, "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
- }
-
- @Test
- public void testGetWithNoChecksumsUsingFailSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertChecksums( expectedFile, null, null );
- }
-
- @Test
- public void testGetChecksumCorrectSha1BadMd5UsingIgnoredSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "3dd1a3a57b807d3ef3fbc6013d926c891cbb8670 *get-checksum-sha1-bad-md5-1.0.jar",
- "invalid checksum file" );
- }
-
- @Test
- public void testGetChecksumCorrectSha1BadMd5UsingFixSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-bad-md5/1.0/get-checksum-sha1-bad-md5-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "3dd1a3a57b807d3ef3fbc6013d926c891cbb8670 *get-checksum-sha1-bad-md5-1.0.jar",
- "c35f3b76268b73a4ba617f6f275c49ab get-checksum-sha1-bad-md5-1.0.jar" );
- }
-
- @Test
- public void testGetChecksumNoSha1CorrectMd5UsingFixSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-md5-only/1.0/get-checksum-md5-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "71f7dc3f72053a3f2d9fdd6fef9db055ef957ffb get-checksum-md5-only-1.0.jar",
- "f3af5201bf8da801da37db8842846e1c *get-checksum-md5-only-1.0.jar" );
- }
-
- @Test
- public void testGetWithNoChecksumsUsingFixSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "1f12821c5e43e1a0b76b9564a6ddb0548ccb9486 get-default-layout-1.0.jar",
- "3f7341545f21226b6f49a3c2704cb9be get-default-layout-1.0.jar" );
- }
-
- @Test
- public void testGetChecksumNotFoundOnRemote()
- throws Exception
- {
- String path = "org/apache/maven/test/get-checksum-sha1-only/1.0/get-checksum-sha1-only-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- FileUtils.deleteDirectory( expectedFile.getParentFile() );
- assertFalse( expectedFile.getParentFile().exists() );
- assertFalse( expectedFile.exists() );
-
- saveRemoteRepositoryConfig( "badproxied", "Bad Proxied", "test://bad.machine.com/repo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- wagonMock.get( path, new File( expectedFile.getAbsolutePath() + ".tmp" ) );
- wagonMockControl.setMatcher( customWagonGetMatcher );
- wagonMockControl.setVoidCallable();
- wagonMock.get( path + ".sha1", new File( expectedFile.getAbsolutePath() + ".sha1.tmp" ) );
- wagonMockControl.setMatcher( customWagonGetMatcher );
- wagonMockControl.setVoidCallable();
- wagonMock.get( path + ".md5", new File( expectedFile.getAbsolutePath() + ".md5.tmp" ) );
- wagonMockControl.setMatcher( customWagonGetMatcher );
- wagonMockControl.setThrowable( new ResourceDoesNotExistException( "Resource does not exist." ) );
- wagonMockControl.replay();
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- wagonMockControl.verify();
-
- // Do what the mock doesn't do.
- String proxyPath = new File( REPOPATH_PROXIED1, path ).getAbsolutePath();
- String localPath = new File( managedDefaultDir, path ).getAbsolutePath();
- FileUtils.copyFile( new File( proxyPath ), new File( localPath ) );
- FileUtils.copyFile( new File( proxyPath + ".sha1" ), new File( localPath + ".sha1" ) );
-
- // Test results.
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "748a3a013bf5eacf2bbb40a2ac7d37889b728837 *get-checksum-sha1-only-1.0.jar",
- null );
- }
-
- @Test
- public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingIgnoredSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, path );
-
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- // There are no hashcodes on the proxy side to download, hence the local ones should remain invalid.
- assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
- }
-
- @Test
- public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingFailSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, path );
-
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FAIL, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- // There are no hashcodes on the proxy side to download.
- // The FAIL policy will delete the checksums as bad.
-
- assertChecksums( expectedFile, "invalid checksum file", "invalid checksum file" );
- }
-
- @Test
- public void testGetAlwaysBadChecksumPresentLocallyAbsentRemoteUsingFixSetting()
- throws Exception
- {
- String path = "org/apache/maven/test/get-bad-local-checksum/1.0/get-bad-local-checksum-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, path );
-
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "proxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
- assertChecksums( expectedFile, "96a08dc80a108cba8efd3b20aec91b32a0b2cbd4 get-bad-local-checksum-1.0.jar",
- "46fdd6ca55bf1d7a7eb0c858f41e0ccd get-bad-local-checksum-1.0.jar" );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.PropagateErrorsDownloadPolicy;
-import org.apache.maven.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
-import org.apache.maven.archiva.policies.ProxyDownloadException;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.apache.maven.archiva.repository.layout.LayoutException;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.apache.maven.wagon.TransferFailedException;
-import org.apache.maven.wagon.authorization.AuthorizationException;
-import org.junit.Test;
-
-import java.io.File;
-
-import static org.junit.Assert.*;
-
-/**
- * ErrorHandlingTest
- *
- * @version $Id$
- */
-public class ErrorHandlingTest
- extends AbstractProxyTestCase
-{
- private static final String PATH_IN_BOTH_REMOTES_NOT_LOCAL =
- "org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
-
- private static final String PATH_IN_BOTH_REMOTES_AND_LOCAL =
- "org/apache/maven/test/get-on-multiple-repos/1.0/get-on-multiple-repos-1.0.pom";
-
- private static final String ID_MOCKED_PROXIED1 = "badproxied1";
-
- private static final String NAME_MOCKED_PROXIED1 = "Bad Proxied 1";
-
- private static final String ID_MOCKED_PROXIED2 = "badproxied2";
-
- private static final String NAME_MOCKED_PROXIED2 = "Bad Proxied 2";
-
- @Test
- public void testPropagateErrorImmediatelyWithErrorThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorImmediatelyWithNotFoundThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
- }
-
- @Test
- public void testPropagateErrorImmediatelyWithSuccessThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorImmediatelyWithNotFoundThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithErrorThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithSuccessThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithNotFoundThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED2 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithErrorThenNotFound()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateErrorAtEndWithErrorThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmFailures( path, new String[]{ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2} );
- }
-
- @Test
- public void testPropagateErrorAtEndWithNotFoundThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
- }
-
- @Test
- public void testIgnoreErrorWithErrorThenSuccess()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED2 );
- }
-
- @Test
- public void testIgnoreErrorWithSuccessThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
-
- confirmSuccess( path, expectedFile, REPOPATH_PROXIED1 );
- }
-
- @Test
- public void testIgnoreErrorWithNotFoundThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testIgnoreErrorWithErrorThenNotFound()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- simulateGetError( path, expectedFile, createResourceNotFoundException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testIgnoreErrorWithErrorThenError()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysQueueArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetError( path, expectedFile, createTransferException() );
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysQueueArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysIgnoreArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetError( path, expectedFile, createTransferException() );
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testPropagateOnUpdateAlwaysIgnoreArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.ALWAYS );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- assertTrue( expectedFile.exists() );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmSingleFailure( path, ID_MOCKED_PROXIED1 );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.STOP,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- assertTrue( expectedFile.exists() );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentQueueArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetError( path, expectedFile, createTransferException() );
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmFailures( path, new String[] { ID_MOCKED_PROXIED1, ID_MOCKED_PROXIED2 } );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentQueueArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.QUEUE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- assertTrue( expectedFile.exists() );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentIgnoreArtifactNotPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_NOT_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFileNotPresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetError( path, expectedFile, createTransferException() );
- simulateGetError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- }
-
- @Test
- public void testPropagateOnUpdateNotPresentIgnoreArtifactPresent()
- throws Exception
- {
- String path = PATH_IN_BOTH_REMOTES_AND_LOCAL;
- File expectedFile = setupRepositoriesWithLocalFilePresent( path );
-
- createMockedProxyConnector( ID_MOCKED_PROXIED1, NAME_MOCKED_PROXIED1, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
- createMockedProxyConnector( ID_MOCKED_PROXIED2, NAME_MOCKED_PROXIED2, PropagateErrorsDownloadPolicy.IGNORE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
- simulateGetIfNewerError( path, expectedFile, createTransferException() );
-
- confirmNotDownloadedNoError( path );
- assertTrue( expectedFile.exists() );
- }
-
- // ------------------------------------------
- // HELPER METHODS
- // ------------------------------------------
-
- private void createMockedProxyConnector( String id, String name, String errorPolicy )
- {
- saveRemoteRepositoryConfig( id, name, "test://bad.machine.com/repo/", "default" );
- saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
- CachedFailuresPolicy.NO, errorPolicy, false );
- }
-
- private void createMockedProxyConnector( String id, String name, String errorPolicy, String errorOnUpdatePolicy )
- {
- saveRemoteRepositoryConfig( id, name, "test://bad.machine.com/repo/", "default" );
- saveConnector( ID_DEFAULT_MANAGED, id, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
- CachedFailuresPolicy.NO, errorPolicy, errorOnUpdatePolicy, false );
- }
-
- private File setupRepositoriesWithLocalFileNotPresent( String path )
- throws Exception
- {
- setupTestableManagedRepository( path );
-
- File file = new File( managedDefaultDir, path );
-
- assertNotExistsInManagedDefaultRepo( file );
-
- return file;
- }
-
- private File setupRepositoriesWithLocalFilePresent( String path )
- throws Exception
- {
- setupTestableManagedRepository( path );
-
- File file = new File( managedDefaultDir, path );
-
- assertTrue( file.exists() );
-
- return file;
- }
-
- private void simulateGetError( String path, File expectedFile, Exception throwable )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- wagonMock.get( path, createExpectedTempFile( expectedFile ) );
- wagonMockControl.setMatcher(customWagonGetMatcher);
- wagonMockControl.setThrowable( throwable, 1 );
- }
-
- private void simulateGetIfNewerError( String path, File expectedFile, TransferFailedException exception )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- wagonMock.getIfNewer( path, createExpectedTempFile( expectedFile ), expectedFile.lastModified() );
- wagonMockControl.setMatcher(customWagonGetIfNewerMatcher);
- wagonMockControl.setThrowable( exception, 1 );
- }
-
- private File createExpectedTempFile( File expectedFile )
- {
- return new File( managedDefaultDir, expectedFile.getName() + ".tmp" ).getAbsoluteFile();
- }
-
- private void confirmSingleFailure( String path, String id )
- throws LayoutException
- {
- confirmFailures( path, new String[]{id} );
- }
-
- private void confirmFailures( String path, String[] ids )
- throws LayoutException
- {
- wagonMockControl.replay();
-
- // Attempt the proxy fetch.
- File downloadedFile = null;
- try
- {
- downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository,
- managedDefaultRepository.toArtifactReference( path ) );
- fail( "Proxy should not have succeeded" );
- }
- catch ( ProxyDownloadException e )
- {
- assertEquals( ids.length, e.getFailures().size() );
- for ( String id : ids )
- {
- assertTrue( e.getFailures().keySet().contains( id ) );
- }
- }
-
- wagonMockControl.verify();
-
- assertNotDownloaded( downloadedFile );
- }
-
- private void confirmSuccess( String path, File expectedFile, String basedir )
- throws Exception
- {
- File downloadedFile = performDownload( path );
-
- File proxied1File = new File( basedir, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- }
-
- private void confirmNotDownloadedNoError( String path )
- throws Exception
- {
- File downloadedFile = performDownload( path );
-
- assertNotDownloaded( downloadedFile );
- }
-
- private File performDownload( String path )
- throws ProxyDownloadException, LayoutException
- {
- wagonMockControl.replay();
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository,
- managedDefaultRepository.toArtifactReference( path ) );
-
- wagonMockControl.verify();
- return downloadedFile;
- }
-
- private static TransferFailedException createTransferException()
- {
- return new TransferFailedException( "test download exception" );
- }
-
- private static ResourceDoesNotExistException createResourceNotFoundException()
- {
- return new ResourceDoesNotExistException( "test download not found" );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.archiva.admin.model.beans.ManagedRepository;
-import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
-import org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin;
-import org.apache.commons.io.FileUtils;
-import org.apache.maven.archiva.configuration.ArchivaConfiguration;
-import org.apache.maven.archiva.configuration.NetworkProxyConfiguration;
-import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
-import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
-import org.apache.maven.archiva.model.ArtifactReference;
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.PropagateErrorsDownloadPolicy;
-import org.apache.maven.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.apache.maven.archiva.repository.ManagedRepositoryContent;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mortbay.jetty.Handler;
-import org.mortbay.jetty.Request;
-import org.mortbay.jetty.Server;
-import org.mortbay.jetty.handler.AbstractHandler;
-import org.springframework.context.ApplicationContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import javax.inject.Inject;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.File;
-import java.io.IOException;
-
-import static org.junit.Assert.*;
-
-/**
- * Integration test for connecting over a HTTP proxy.
- *
- * @version $Id: ManagedDefaultTransferTest.java 677852 2008-07-18 08:16:24Z brett $
- */
-@RunWith( SpringJUnit4ClassRunner.class )
-@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
-public class HttpProxyTransferTest
-{
- private static final String PROXY_ID = "proxy";
-
- private static final String MANAGED_ID = "default-managed-repository";
-
- private static final String PROXIED_ID = "proxied1";
-
- private static final String PROXIED_BASEDIR = "src/test/repositories/proxied1";
-
- private RepositoryProxyConnectors proxyHandler;
-
- private ArchivaConfiguration config;
-
- private ManagedRepositoryContent managedDefaultRepository;
-
- @Inject
- private ApplicationContext applicationContext;
-
- private Server server;
-
- @Before
- public void setUp()
- throws Exception
- {
- proxyHandler = applicationContext.getBean( "repositoryProxyConnectors#test", RepositoryProxyConnectors.class );
-
- config = applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
-
- // clear from previous tests - TODO the spring context should be initialised per test instead, or the config
- // made a complete mock
- config.getConfiguration().getProxyConnectors().clear();
-
- // Setup source repository (using default layout)
- String repoPath = "target/test-repository/managed/" + getClass().getSimpleName();
-
- File destRepoDir = new File( repoPath );
-
- // Cleanout destination dirs.
- if ( destRepoDir.exists() )
- {
- FileUtils.deleteDirectory( destRepoDir );
- }
-
- // Make the destination dir.
- destRepoDir.mkdirs();
-
- ManagedRepository repo = new ManagedRepository();
- repo.setId( MANAGED_ID );
- repo.setName( "Default Managed Repository" );
- repo.setLocation( repoPath );
- repo.setLayout( "default" );
-
- ManagedRepositoryContent repoContent =
- applicationContext.getBean( "managedRepositoryContent#default", ManagedRepositoryContent.class );
-
- repoContent.setRepository( repo );
- managedDefaultRepository = repoContent;
-
- ( (DefaultManagedRepositoryAdmin) applicationContext.getBean(
- ManagedRepositoryAdmin.class ) ).setArchivaConfiguration( config );
-
- ManagedRepositoryAdmin managedRepositoryAdmin = applicationContext.getBean( ManagedRepositoryAdmin.class );
- if ( managedRepositoryAdmin.getManagedRepository( repo.getId() ) == null )
- {
- managedRepositoryAdmin.addManagedRepository( repo, false, null );
- }
-
- //config.getConfiguration().addManagedRepository( repo );
-
- Handler handler = new AbstractHandler()
- {
- public void handle( String target, HttpServletRequest request, HttpServletResponse response, int dispatch )
- throws IOException, ServletException
- {
- response.setContentType( "text/plain" );
- response.setStatus( HttpServletResponse.SC_OK );
- response.getWriter().print( "get-default-layout-1.0.jar\n\n" );
- assertNotNull( request.getHeader( "Proxy-Connection" ) );
-
- ( (Request) request ).setHandled( true );
- }
- };
-
- server = new Server( 0 );
- server.setHandler( handler );
- server.start();
-
- int port = server.getConnectors()[0].getLocalPort();
-
- NetworkProxyConfiguration proxyConfig = new NetworkProxyConfiguration();
- proxyConfig.setHost( "localhost" );
- proxyConfig.setPort( port );
- proxyConfig.setProtocol( "http" );
- proxyConfig.setId( PROXY_ID );
- config.getConfiguration().addNetworkProxy( proxyConfig );
-
- // Setup target (proxied to) repository.
- RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
-
- repoConfig.setId( PROXIED_ID );
- repoConfig.setName( "Proxied Repository 1" );
- repoConfig.setLayout( "default" );
- repoConfig.setUrl( "http://www.example.com/" );
-
- config.getConfiguration().addRemoteRepository( repoConfig );
-
- }
-
- @After
- public void tearDown()
- throws Exception
- {
- server.stop();
- }
-
- @Test
- public void testGetOverHttpProxy()
- throws Exception
- {
- assertNull( System.getProperty( "http.proxyHost" ) );
- assertNull( System.getProperty( "http.proxyPort" ) );
-
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
-
- // Configure Connector (usually done within archiva.xml configuration)
- addConnector();
-
- File expectedFile = new File( new File( managedDefaultRepository.getRepoRoot() ), path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File sourceFile = new File( PROXIED_BASEDIR, path );
- assertNotNull( "Expected File should not be null.", expectedFile );
- assertNotNull( "Actual File should not be null.", downloadedFile );
-
- assertTrue( "Check actual file exists.", downloadedFile.exists() );
- assertEquals( "Check filename path is appropriate.", expectedFile.getCanonicalPath(),
- downloadedFile.getCanonicalPath() );
- assertEquals( "Check file path matches.", expectedFile.getAbsolutePath(), downloadedFile.getAbsolutePath() );
-
- String expectedContents = FileUtils.readFileToString( sourceFile, null );
- String actualContents = FileUtils.readFileToString( downloadedFile, null );
- assertEquals( "Check file contents.", expectedContents, actualContents );
-
- assertNull( System.getProperty( "http.proxyHost" ) );
- assertNull( System.getProperty( "http.proxyPort" ) );
- }
-
- private void addConnector()
- {
- ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
- connectorConfig.setProxyId( PROXY_ID );
- connectorConfig.setSourceRepoId( MANAGED_ID );
- connectorConfig.setTargetRepoId( PROXIED_ID );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, ChecksumPolicy.FIX );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, ReleasesPolicy.ONCE );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, SnapshotsPolicy.ONCE );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, CachedFailuresPolicy.NO );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS,
- PropagateErrorsDownloadPolicy.QUEUE );
- connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE,
- PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
-
- int count = config.getConfiguration().getProxyConnectors().size();
- config.getConfiguration().addProxyConnector( connectorConfig );
-
- // Proper Triggering ...
- String prefix = "proxyConnectors.proxyConnector(" + count + ")";
- ( (MockConfiguration) config ).triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringUtils;
-import org.apache.maven.archiva.model.ArtifactReference;
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.junit.Test;
-
-import java.io.File;
-
-import static org.junit.Assert.*;
-
-/**
- * ManagedDefaultTransferTest
- *
- * @version $Id$
- */
-public class ManagedDefaultTransferTest
- extends AbstractProxyTestCase
-{
- @Test
- public void testGetDefaultLayoutNotPresentConnectorOffline()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Ensure file isn't present first.
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, true );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
- assertNull("File should not have been downloaded", downloadedFile);
- }
-
- @Test
- public void testGetDefaultLayoutNotPresent()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Ensure file isn't present first.
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File sourceFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, sourceFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetDefaultLayoutNotPresentPassthrough()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar.asc";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
-
- // Ensure file isn't present first.
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, path );
-
- File sourceFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, sourceFile );
- assertFalse( new File( downloadedFile.getParentFile(), downloadedFile.getName() + ".sha1" ).exists() );
- assertFalse( new File( downloadedFile.getParentFile(), downloadedFile.getName() + ".md5" ).exists() );
- assertFalse( new File( downloadedFile.getParentFile(), downloadedFile.getName() + ".asc" ).exists() );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * The attempt here should result in no file being transferred.
- * <p/>
- * The file exists locally, and the policy is ONCE.
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutAlreadyPresentPolicyOnce()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertFileEquals( expectedFile, downloadedFile, expectedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * The attempt here should result in no file being transferred.
- * <p/>
- * The file exists locally, and the policy is ONCE.
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutAlreadyPresentPassthrough()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar.asc";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, path );
-
- assertTrue( expectedFile.exists() );
-
- // Set the managed File to be newer than local.
- setManagedOlderThanRemote( expectedFile, remoteFile );
- long originalModificationTime = expectedFile.lastModified();
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ONCE, SnapshotsPolicy.ONCE,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, path );
-
- assertNotDownloaded( downloadedFile );
- assertNotModified( expectedFile, originalModificationTime );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * <p>
- * Request a file, that exists locally, and remotely.
- * </p>
- * <p>
- * All policies are set to IGNORE.
- * </p>
- * <p>
- * Managed file is newer than remote file.
- * </p>
- * <p>
- * Transfer should not have occured, as managed file is newer.
- * </p>
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutAlreadyPresentNewerThanRemotePolicyIgnored()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, path );
-
- // Set the managed File to be newer than local.
- setManagedNewerThanRemote( expectedFile, remoteFile );
-
- long originalModificationTime = expectedFile.lastModified();
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNotModified( expectedFile, originalModificationTime );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * <p>
- * Request a file, that exists locally, and remotely.
- * </p>
- * <p>
- * All policies are set to IGNORE.
- * </p>
- * <p>
- * Managed file is older than Remote file.
- * </p>
- * <p>
- * Transfer should have occured, as managed file is older than remote.
- * </p>
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutAlreadyPresentOlderThanRemotePolicyIgnored()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, path );
-
- // Set the managed file to be newer than remote file.
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * The attempt here should result in file being transferred.
- * <p/>
- * The file exists locally, is over 6 years old, and the policy is DAILY.
- *
- * @throws Exception
- */
- @Test
- public void testGetDefaultLayoutRemoteUpdate()
- throws Exception
- {
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
- expectedFile.setLastModified( getPastDate().getTime() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.DAILY, SnapshotsPolicy.DAILY,
- CachedFailuresPolicy.NO, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetWhenInBothProxiedRepos()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-both-proxies/1.0/get-in-both-proxies-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1 , false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2 , false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied1File = new File( REPOPATH_PROXIED1, path );
- File proxied2File = new File( REPOPATH_PROXIED2, path );
- assertFileEquals( expectedFile, downloadedFile, proxied1File );
- assertNoTempFiles( expectedFile );
-
- // TODO: is this check even needed if it passes above?
- String actualContents = FileUtils.readFileToString( downloadedFile, null );
- String badContents = FileUtils.readFileToString( proxied2File, null );
- assertFalse( "Downloaded file contents should not be that of proxy 2",
- StringUtils.equals( actualContents, badContents ) );
- }
-
- @Test
- public void testGetInSecondProxiedRepo()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxied2File = new File( REPOPATH_PROXIED2, path );
- assertFileEquals( expectedFile, downloadedFile, proxied2File );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testNotFoundInAnyProxies()
- throws Exception
- {
- String path = "org/apache/maven/test/does-not-exist/1.0/does-not-exist-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNull( "File returned was: " + downloadedFile + "; should have got a not found exception",
- downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetInSecondProxiedRepoFirstFails()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Repository (usually done within archiva.xml configuration)
- saveRemoteRepositoryConfig( "badproxied", "Bad Proxied", "test://bad.machine.com/repo/", "default" );
-
- wagonMock.get( path, new File( expectedFile.getAbsolutePath() + ".tmp" ) );
- wagonMockControl.setMatcher(customWagonGetMatcher);
- wagonMockControl.setThrowable( new ResourceDoesNotExistException( "transfer failed" ) );
- wagonMockControl.replay();
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied", false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, false );
-
- // Attempt the proxy fetch.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- wagonMockControl.verify();
-
- File proxied2File = new File( REPOPATH_PROXIED2, path );
- assertFileEquals( expectedFile, downloadedFile, proxied2File );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetAllRepositoriesFail()
- throws Exception
- {
- String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir.getAbsoluteFile(), path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Repository (usually done within archiva.xml configuration)
- saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "test://bad.machine.com/repo/", "default" );
- saveRemoteRepositoryConfig( "badproxied2", "Bad Proxied 2", "test://dead.machine.com/repo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied1", false );
- saveConnector( ID_DEFAULT_MANAGED, "badproxied2", false );
-
- File tmpFile = new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" );
- wagonMock.get( path, tmpFile );
-
- wagonMockControl.setMatcher(customWagonGetMatcher);
- wagonMockControl.setThrowable( new ResourceDoesNotExistException( "Can't find resource." ) );
-
- wagonMock.get( path, tmpFile );
-
- wagonMockControl.setMatcher(customWagonGetMatcher);
- wagonMockControl.setThrowable( new ResourceDoesNotExistException( "Can't find resource." ) );
-
- wagonMockControl.replay();
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
-
- wagonMockControl.verify();
- assertNoTempFiles( expectedFile );
-
- // TODO: do not want failures to present as a not found [MRM-492]
- // TODO: How much information on each failure should we pass back to the user vs. logging in the proxy?
- }
-
- @Test
- public void testGetFromLegacyProxyAlreadyPresentInManaged_NewerThanRemote()
- throws Exception
- {
- String legacyPath = "org.apache.maven.test/jars/get-default-layout-present-1.0.jar";
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
-
- // Set the managed file to be newer than remote.
- setManagedNewerThanRemote( expectedFile, remoteFile );
- long expectedTimestamp = expectedFile.lastModified();
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNotModified( expectedFile, expectedTimestamp );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetFromLegacyProxyAlreadyPresentInManaged_OlderThanRemote()
- throws Exception
- {
- String legacyPath = "org.apache.maven.test/jars/get-default-layout-present-1.0.jar";
- String path = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
-
- // Set the managed file to be older than remote.
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetFromLegacyProxyNotPresentInManaged()
- throws Exception
- {
- String legacyPath = "org.apache.maven.test/jars/example-lib-2.2.jar";
- String path = "org/apache/maven/test/example-lib/2.2/example-lib-2.2.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetFromLegacyProxyPluginNotPresentInManaged()
- throws Exception
- {
- String legacyPath = "org.apache.maven.test/maven-plugins/example-maven-plugin-0.42.jar";
- String path = "org/apache/maven/test/example-maven-plugin/0.42/example-maven-plugin-0.42.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertNotExistsInManagedDefaultRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_LEGACY_PROXIED, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED_LEGACY, legacyPath );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.maven.archiva.model.ArtifactReference;
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.junit.Test;
-
-import java.io.File;
-
-import static org.junit.Assert.assertTrue;
-
-/**
- * ManagedLegacyTransferTest
- *
- * @version $Id$
- */
-public class ManagedLegacyTransferTest
- extends AbstractProxyTestCase
-{
- /**
- * Incoming request on a Managed Legacy repository, for content that does not
- * exist in the managed legacy repository, but does exist on a remote default layout repository.
- */
- @Test
- public void testManagedLegacyNotPresentRemoteDefaultPresent()
- throws Exception
- {
- String path = "org.apache.maven.test/jars/get-default-layout-1.0.jar";
- File expectedFile = new File( managedLegacyDir, path );
- ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
-
- assertNotExistsInManagedLegacyRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_LEGACY_MANAGED, ID_PROXIED1, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
-
- File proxied2File = new File( REPOPATH_PROXIED1,
- "org/apache/maven/test/get-default-layout/1.0/get-default-layout-1.0.jar" );
- assertFileEquals( expectedFile, downloadedFile, proxied2File );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Incoming request on a Managed Legacy repository, for content that already
- * exist in the managed legacy repository, and also exist on a remote default layout repository.
- */
- @Test
- public void testManagedLegacyPresentRemoteDefaultPresent()
- throws Exception
- {
- String path = "org.apache.maven.test/jars/get-default-layout-present-1.0.jar";
- String remotePath = "org/apache/maven/test/get-default-layout-present/1.0/get-default-layout-present-1.0.jar";
-
- File expectedFile = new File( managedLegacyDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, remotePath );
-
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_LEGACY_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
-
- assertFileEquals( expectedFile, downloadedFile, remoteFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Incoming request on a Managed Legacy repository, for content that does not
- * exist in the managed legacy repository, and does not exist on a remote legacy layout repository.
- */
- @Test
- public void testManagedLegacyNotPresentRemoteLegacyPresent()
- throws Exception
- {
- String path = "org.apache.maven.test/plugins/get-legacy-plugin-1.0.jar";
- File expectedFile = new File( managedLegacyDir, path );
- ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
-
- assertNotExistsInManagedLegacyRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_LEGACY_MANAGED, ID_LEGACY_PROXIED, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED_LEGACY, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Incoming request on a Managed Legacy repository, for content that does exist in the
- * managed legacy repository, and also exists on a remote legacy layout repository.
- */
- @Test
- public void testManagedLegacyPresentRemoteLegacyPresent()
- throws Exception
- {
- String path = "org.apache.maven.test/jars/get-default-layout-present-1.0.jar";
- File expectedFile = new File( managedLegacyDir, path );
- File remoteFile = new File( REPOPATH_PROXIED_LEGACY, path );
-
- setManagedOlderThanRemote( expectedFile, remoteFile );
-
- ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_LEGACY_MANAGED, ID_LEGACY_PROXIED, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
-
- assertFileEquals( expectedFile, downloadedFile, remoteFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Incoming request on a Managed Legacy repository, for content that does exist in the
- * managed legacy repository, and does not exist on a remote legacy layout repository.
- */
- @Test
- public void testManagedLegacyPresentRemoteLegacyNotPresent()
- throws Exception
- {
- String path = "org.apache.maven.test/jars/managed-only-lib-2.1.jar";
- File expectedFile = new File( managedLegacyDir, path );
- ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_LEGACY_MANAGED, ID_LEGACY_PROXIED, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Incoming request on a Managed Legacy repository, for content that does exist in the
- * managed legacy repository, and does not exists on a remote default layout repository.
- */
- @Test
- public void testManagedLegacyPresentRemoteDefaultNotPresent()
- throws Exception
- {
- String path = "org.apache.maven.test/jars/managed-only-lib-2.1.jar";
- File expectedFile = new File( managedLegacyDir, path );
- ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_LEGACY_MANAGED, ID_PROXIED1, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Incoming request on a Managed Legacy repository, for content that does not exist in the
- * managed legacy repository, and does not exists on a remote legacy layout repository.
- */
- @Test
- public void testManagedLegacyNotPresentRemoteLegacyNotPresent()
- throws Exception
- {
- String path = "org.apache.archiva.test/jars/mystery-lib-1.0.jar";
- File expectedFile = new File( managedLegacyDir, path );
- ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
-
- assertNotExistsInManagedLegacyRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_LEGACY_MANAGED, ID_LEGACY_PROXIED, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Incoming request on a Managed Legacy repository, for content that does not exist in the
- * managed legacy repository, and does not exists on a remote default layout repository.
- */
- @Test
- public void testManagedLegacyNotPresentRemoteDefaultNotPresent()
- throws Exception
- {
- String path = "org.apache.archiva.test/jars/mystery-lib-2.1.jar";
- File expectedFile = new File( managedLegacyDir, path );
- ArtifactReference artifact = managedLegacyRepository.toArtifactReference( path );
-
- assertNotExistsInManagedLegacyRepo( expectedFile );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_LEGACY_MANAGED, ID_PROXIED1, false );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedLegacyRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.archiva.common.utils.VersionUtil;
-import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
-import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
-import org.apache.maven.archiva.model.Plugin;
-import org.apache.maven.archiva.model.ProjectReference;
-import org.apache.maven.archiva.model.SnapshotVersion;
-import org.apache.maven.archiva.model.VersionedReference;
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.apache.maven.archiva.repository.metadata.MetadataTools;
-import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
-import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
-import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
-import org.apache.maven.wagon.TransferFailedException;
-import org.custommonkey.xmlunit.DetailedDiff;
-import org.custommonkey.xmlunit.Diff;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import javax.inject.Inject;
-import javax.inject.Named;
-
-import static org.junit.Assert.*;
-
-/**
- * MetadataTransferTest - Tests the various fetching / merging concepts surrounding the maven-metadata.xml files
- * present in the repository.
- * <p/>
- * Test Case Naming is as follows.
- * <p/>
- * <code>
- * public void testGet[Release|Snapshot|Project]Metadata[Not]Proxied[Not|On]Local[Not|On|Multiple]Remote
- * </code>
- * <p/>
- * <pre>
- * Which should leave the following matrix of test cases.
- *
- * Metadata | Proxied | Local | Remote
- * ----------+----------+-------+---------
- * Release | Not | Not | n/a (1)
- * Release | Not | On | n/a (1)
- * Release | | Not | Not
- * Release | | Not | On
- * Release | | Not | Multiple
- * Release | | On | Not
- * Release | | On | On
- * Release | | On | Multiple
- * Snapshot | Not | Not | n/a (1)
- * Snapshot | Not | On | n/a (1)
- * Snapshot | | Not | Not
- * Snapshot | | Not | On
- * Snapshot | | Not | Multiple
- * Snapshot | | On | Not
- * Snapshot | | On | On
- * Snapshot | | On | Multiple
- * Project | Not | Not | n/a (1)
- * Project | Not | On | n/a (1)
- * Project | | Not | Not
- * Project | | Not | On
- * Project | | Not | Multiple
- * Project | | On | Not
- * Project | | On | On
- * Project | | On | Multiple
- *
- * (1) If it isn't proxied, no point in having a remote.
- * </pre>
- *
- * @version $Id$
- */
-public class MetadataTransferTest
- extends AbstractProxyTestCase
-{
-
- @Inject
- @Named(value = "metadataTools#mocked")
- private MetadataTools metadataTools;
-
- @Before
- public void init()
- throws Exception
- {
- super.setUp();
- //metadataTools = applicationContext.getBean( MetadataTools.class );
- }
-
- @Test
- public void testGetProjectMetadataProxiedNotLocalOnRemoteConnectoDisabled()
- throws Exception
- {
- // New project metadata that does not exist locally but exists on remote.
- String requestedResource = "org/apache/maven/test/get-found-in-proxy/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, true );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- File expectedFile = new File( managedDefaultDir, requestedResource );
-
- ProjectReference metadata = createProjectReference( requestedResource );
-
- File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
- managedDefaultRepository.toMetadataPath(
- metadata ) );
-
- assertNull( "Should not have downloaded a file.", downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- // TODO: same test for other fetch* methods
- @Test
- public void testFetchFromTwoProxiesWhenFirstConnectionFails()
- throws Exception
- {
- // Project metadata that does not exist locally, but has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/get-default-layout/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- saveRemoteRepositoryConfig( "badproxied1", "Bad Proxied 1", "test://bad.machine.com/repo/", "default" );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, "badproxied1", ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( "badproxied1", requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // ensure that a hard failure in the first proxy connector is skipped and the second repository checked
- File expectedFile = new File( managedDefaultDir.getAbsoluteFile(),
- metadataTools.getRepositorySpecificName( "badproxied1", requestedResource ) );
- wagonMock.get( requestedResource, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
-
- wagonMockControl.setMatcher( customWagonGetMatcher );
-
- wagonMockControl.setThrowable( new TransferFailedException( "can't connect" ) );
-
- wagonMockControl.replay();
-
- assertFetchProjectOrGroup( requestedResource );
-
- wagonMockControl.verify();
-
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0.1" }, "1.0.1", "1.0.1" );
- assertNoRepoMetadata( "badproxied1", requestedResource );
- assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0.1" } );
- }
-
- /**
- * Attempt to get the project metadata for non-existant artifact.
- * <p/>
- * Expected result: the maven-metadata.xml file is not created on the managed repository, nor returned
- * to the requesting client.
- */
- @Test
- public void testGetProjectMetadataNotProxiedNotLocal()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource = "org/apache/maven/test/get-default-metadata-nonexistant/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
-
- assertResourceNotFound( requestedResource );
-
- // No proxy setup, nothing fetched, failure expected.
- assertFetchProjectOrGroupFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertResourceNotFound( requestedResource );
- }
-
- @Test
- public void testGetProjectMetadataNotProxiedOnLocal()
- throws Exception
- {
-
- // Project metadata that exists and has multiple versions
- String requestedResource = "org/apache/maven/test/get-project-metadata/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
-
- assertResourceExists( requestedResource );
-
- // No proxy setup, nothing fetched from remote, but local exists.
- assertFetchProjectOrGroup( requestedResource );
-
- // Nothing fetched. Should only contain contents of what is in the repository.
- // A metadata update is not performed in this use case. Local metadata content is only
- // updated via the metadata updater consumer.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0" }, null, null );
- }
-
- @Test
- public void testGetProjectMetadataProxiedNotLocalMultipleRemotes()
- throws Exception
- {
- // Project metadata that does not exist locally, but has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/get-default-layout/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetched from both remotes.
- assertFetchProjectOrGroup( requestedResource );
-
- // Nothing fetched. Should only contain contents of what is in the repository.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0", "1.0.1" }, "1.0.1", "1.0.1" );
- assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0" } );
- assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0.1" } );
- }
-
- @Test
- public void testGetProjectMetadataProxiedNotLocalNotRemote()
- throws Exception
- {
- // Non-existant project metadata that does not exist locally and doesn't exist on remotes.
- String requestedResource = "org/apache/maven/test/get-bogus-artifact/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, nothing fetched from remotes, local does not exist.
- assertFetchProjectOrGroupFailed( requestedResource );
-
- // Nothing fetched. Nothing should exist.
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetProjectMetadataProxiedNotLocalOnRemote()
- throws Exception
- {
- // New project metadata that does not exist locally but exists on remote.
- String requestedResource = "org/apache/maven/test/get-found-in-proxy/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // One proxy setup, metadata fetched from remote, local does not exist.
- assertFetchProjectOrGroup( requestedResource );
-
- // Remote fetched. Local created/updated.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0.5" }, "1.0.5", "1.0.5" );
- assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0.5" } );
- }
-
- @Test
- public void testGetProjectMetadataProxiedOnLocalMultipleRemote()
- throws Exception
- {
- // Project metadata that exist locally, and has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/get-on-multiple-repos/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0" }, null, null );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetched from both remotes.
- assertFetchProjectOrGroup( requestedResource );
-
- // metadata fetched from both repos, and merged with local version.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0", "1.0.1", "2.0" }, "2.0", "2.0" );
- assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0", "2.0" } );
- assertRepoProjectMetadata( ID_PROXIED2, requestedResource, new String[]{ "1.0", "1.0.1" } );
- }
-
- @Test
- public void testGetProjectMetadataProxiedOnLocalNotRemote()
- throws Exception
- {
-
- // Project metadata that exist locally, and does not exist in remote repos.
- String requestedResource = "org/apache/maven/test/get-not-on-remotes/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
-
- config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>( ) );
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0-beta-2" }, null, null );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetch from remotes fail (because they dont exist).
- assertFetchProjectOrGroup( requestedResource );
-
- // metadata not fetched from both repos, and local version exists.
- // Since there was no updated metadata content from a remote/proxy, a metadata update on
- // the local file never ran. Local only updates are performed via the metadata updater consumer.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0-beta-2" }, null, null );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetProjectMetadataProxiedOnLocalOnRemote()
- throws Exception
- {
- // Project metadata that exist locally and exists on remote.
- String requestedResource = "org/apache/maven/test/get-on-local-on-remote/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0.8", "1.0.22" }, null, null );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // One proxy setup, metadata fetched from remote, local exists.
- assertFetchProjectOrGroup( requestedResource );
-
- // Remote fetched. Local updated.
- assertProjectMetadataContents( requestedResource, new String[]{ "1.0.8", "1.0.22", "2.0" }, "2.0", "2.0" );
- assertRepoProjectMetadata( ID_PROXIED1, requestedResource, new String[]{ "1.0.22", "2.0" } );
- }
-
- /**
- * A request for a release maven-metadata.xml file that does not exist locally, and the managed
- * repository has no proxied repositories set up.
- * <p/>
- * Expected result: the maven-metadata.xml file is not created on the managed repository, nor returned
- * to the requesting client.
- */
- @Test
- public void testGetReleaseMetadataNotProxiedNotLocal()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource = "org/apache/maven/test/get-default-metadata-nonexistant/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertNoMetadata( requestedResource );
-
- // No proxy setup, nothing fetched, failure expected.
- assertFetchVersionedFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertNoMetadata( requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that does exist locally, and the managed
- * repository has no proxied repositories set up.
- * <p/>
- * Expected result: the maven-metadata.xml file is updated locally, based off of the managed repository
- * information, and then returned to the client.
- */
- @Test
- public void testGetReleaseMetadataNotProxiedOnLocal()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-default-metadata/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertResourceExists( requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- }
-
- /**
- * A request for a release maven-metadata.xml file that does not exist on the managed repository, but
- * exists on multiple remote repositories.
- * <p/>
- * Expected result: the maven-metadata.xml file is downloaded from the remote into the repository specific
- * file location on the managed repository, a merge of the contents to the requested
- * maven-metadata.xml is performed, and then the merged maven-metadata.xml file is
- * returned to the client.
- */
- @Test
- public void testGetReleaseMetadataProxiedNotLocalMultipleRemotes()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-default-layout/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED2, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that does not exist locally, nor does it exist in a remote
- * proxied repository.
- * <p/>
- * Expected result: the maven-metadata.xml file is created locally, based off of managed repository
- * information, and then return to the client.
- */
- @Test
- public void testGetReleaseMetadataProxiedNotLocalNotRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-bad-metadata/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
-
- assertFetchProjectOrGroupFailed( requestedResource );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that does not exist on the managed repository, but
- * exists on 1 remote repository.
- * <p/>
- * Expected result: the maven-metadata.xml file is downloaded from the remote into the repository specific
- * file location on the managed repository, a merge of the contents to the requested
- * maven-metadata.xml is performed, and then the merged maven-metadata.xml file is
- * returned to the client.
- */
- @Test
- public void testGetReleaseMetadataProxiedNotLocalOnRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-default-layout/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that exists in the managed repository, but
- * not on any remote repository.
- * <p/>
- * Expected result: the maven-metadata.xml file does not exist on the remote proxied repository and
- * is not downloaded. There is no repository specific metadata file on the managed
- * repository. The managed repository maven-metadata.xml is returned to the
- * client as-is.
- */
- @Test
- public void testGetReleaseMetadataProxiedOnLocalNotRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-not-on-remotes/1.0-beta-2/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertReleaseMetadataContents( requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that exists in the managed repository, and on multiple
- * remote repositories.
- * <p/>
- * Expected result: the maven-metadata.xml file on the remote proxied repository is downloaded
- * and merged into the contents of the existing managed repository copy of
- * the maven-metadata.xml file.
- */
- @Test
- public void testGetReleaseMetadataProxiedOnLocalMultipleRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-on-multiple-repos/1.0/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertReleaseMetadataContents( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED2, requestedResource );
- }
-
- /**
- * A request for a maven-metadata.xml file that exists in the managed repository, and on one
- * remote repository.
- * <p/>
- * Expected result: the maven-metadata.xml file on the remote proxied repository is downloaded
- * and merged into the contents of the existing managed repository copy of
- * the maven-metadata.xml file.
- */
- @Test
- public void testGetReleaseMetadataProxiedOnLocalOnRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-on-local-on-remote/1.0.22/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertReleaseMetadataContents( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- assertFetchVersioned( requestedResource );
-
- assertReleaseMetadataContents( requestedResource );
- assertRepoReleaseMetadataContents( ID_PROXIED1, requestedResource );
- }
-
- @Test
- public void testGetSnapshotMetadataNotProxiedNotLocal()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource =
- "org/apache/maven/test/get-default-metadata-nonexistant/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertNoMetadata( requestedResource );
-
- // No proxy setup, nothing fetched, no local file, failure expected.
- assertFetchVersionedFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertNoMetadata( requestedResource );
- }
-
- @Test
- public void testGetSnapshotMetadataNotProxiedOnLocal()
- throws Exception
- {
- // The artifactId exists locally (but not on a remote repo)
- String requestedResource =
- "org/apache/maven/test/get-snapshot-on-local-not-remote/2.0-alpha-2-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertResourceExists( requestedResource );
-
- // No proxy setup, nothing fetched from remote, local file exists, fetch should succeed.
- assertFetchVersioned( requestedResource );
-
- // Local metadata exists, should be updated to reflect the latest release.
- assertSnapshotMetadataContents( requestedResource, "20070821", "220304", 2 );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedNotLocalMultipleRemotes()
- throws Exception
- {
- String requestedResource =
- "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Proxying 2 repos, both have content, local file updated.
- assertFetchVersioned( requestedResource );
-
- assertSnapshotMetadataContents( requestedResource, "20070101", "000103", 2 );
- assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20061227", "112101", 2 );
- assertRepoSnapshotMetadataContents( ID_PROXIED2, requestedResource, "20070101", "000103", 2 );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedNotLocalNotRemote()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource =
- "org/apache/maven/test/get-default-metadata-nonexistant/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertNoMetadata( requestedResource );
-
- // One proxy setup, nothing fetched, no local file, failure expected.
- assertFetchVersionedFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertNoMetadata( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedNotLocalOnRemote()
- throws Exception
- {
- // Artifact exists only in the proxied1 location.
- String requestedResource = "org/apache/maven/test/get-metadata-snapshot/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
-
- // One proxy setup, one metadata fetched, local file created/updated.
- assertFetchVersioned( requestedResource );
-
- // Local artifact Id should contain latest (which in this case is from proxied download)
- assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
- assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20050831", "101112", 1 );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedOnLocalMultipleRemote()
- throws Exception
- {
- String requestedResource = "org/apache/maven/test/get-snapshot-popular/2.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertSnapshotMetadataContents( requestedResource, "20070822", "021008", 3 );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Proxying 2 repos, both have content, local file updated.
- assertFetchVersioned( requestedResource );
-
- assertSnapshotMetadataContents( requestedResource, "20070823", "212711", 6 );
- assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20070822", "145534", 9 );
- assertRepoSnapshotMetadataContents( ID_PROXIED2, requestedResource, "20070823", "212711", 6 );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedOnLocalNotRemote()
- throws Exception
- {
- // The artifactId exists locally (but not on a remote repo)
- String requestedResource =
- "org/apache/maven/test/get-snapshot-on-local-not-remote/2.0-alpha-2-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceExists( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // two proxies setup, nothing fetched from either remote, local file exists, fetch should succeed.
- assertFetchVersioned( requestedResource );
-
- // Local metadata exists, repo metadatas should not exist, local file updated.
- assertSnapshotMetadataContents( requestedResource, "20070821", "220304", 2 );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetSnapshotMetadataProxiedOnLocalOnRemote()
- throws Exception
- {
- // The artifactId exists locally (but not on a remote repo)
- String requestedResource =
- "org/apache/maven/test/get-present-metadata-snapshot/1.0-SNAPSHOT/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // two proxies setup, nothing fetched from either remote, local file exists, fetch should succeed.
- assertFetchVersioned( requestedResource );
-
- // Local metadata exists, repo metadata exists, local file updated.
- assertSnapshotMetadataContents( requestedResource, "20050831", "101112", 1 );
- assertRepoSnapshotMetadataContents( ID_PROXIED1, requestedResource, "20050831", "101112", 1 );
- }
-
- @Test
- public void testGetGroupMetadataNotProxiedNotLocal()
- throws Exception
- {
- // The artifactId "get-default-metadata-nonexistant" does not exist (intentionally).
- String requestedResource = "org/apache/maven/test/groups/get-default-metadata-nonexistant/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertResourceNotFound( requestedResource );
-
- // No proxy setup, nothing fetched, failure expected.
- assertFetchProjectOrGroupFailed( requestedResource );
-
- // No local artifactId, and no fetch, should equal no metadata file downloaded / created / updated.
- assertResourceNotFound( requestedResource );
- }
-
- @Test
- public void testGetGroupMetadataNotProxiedOnLocal()
- throws Exception
- {
- // Project metadata that exists and has multiple versions
- String requestedResource = "org/apache/maven/test/groups/get-project-metadata/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- assertResourceExists( requestedResource );
-
- // No proxy setup, nothing fetched from remote, but local exists.
- assertFetchProjectOrGroup( requestedResource );
-
- // Nothing fetched. Should only contain contents of what is in the repository.
- // A metadata update is not performed in this use case. Local metadata content is only
- // updated via the metadata updater consumer.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin1" } );
- }
-
- @Test
- public void testGetGroupMetadataProxiedNotLocalMultipleRemotes()
- throws Exception
- {
- // Project metadata that does not exist locally, but has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/groups/get-default-layout/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetched from both remotes.
- assertFetchProjectOrGroup( requestedResource );
-
- // Nothing fetched. Should only contain contents of what is in the repository.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin2", "plugin1" } );
- assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin1" } );
- assertRepoGroupMetadataContents( ID_PROXIED2, requestedResource, new String[]{ "plugin2" } );
- }
-
- @Test
- public void testGetGroupsMetadataProxiedNotLocalNotRemote()
- throws Exception
- {
- // Non-existant project metadata that does not exist locally and doesn't exist on remotes.
- String requestedResource = "org/apache/maven/test/groups/get-bogus-artifact/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, nothing fetched from remotes, local does not exist.
- assertFetchProjectOrGroupFailed( requestedResource );
-
- // Nothing fetched. Nothing should exist.
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetGroupMetadataProxiedNotLocalOnRemote()
- throws Exception
- {
- // New project metadata that does not exist locally but exists on remote.
- String requestedResource = "org/apache/maven/test/groups/get-found-in-proxy/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertResourceNotFound( requestedResource );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // One proxy setup, metadata fetched from remote, local does not exist.
- assertFetchProjectOrGroup( requestedResource );
-
- // Remote fetched. Local created/updated.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin3" } );
- assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin3" } );
- }
-
- @Test
- public void testGetGroupMetadataProxiedOnLocalMultipleRemote()
- throws Exception
- {
- // Project metadata that exist locally, and has multiple versions in remote repos
- String requestedResource = "org/apache/maven/test/groups/get-on-multiple-repos/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin1" } );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetched from both remotes.
- assertFetchProjectOrGroup( requestedResource );
-
- // metadata fetched from both repos, and merged with local version.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin1", "plugin2", "plugin4" } );
- assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin1", "plugin4" } );
- assertRepoGroupMetadataContents( ID_PROXIED2, requestedResource, new String[]{ "plugin1", "plugin2" } );
- }
-
- @Test
- public void testGetGroupMetadataProxiedOnLocalNotRemote()
- throws Exception
- {
- // Project metadata that exist locally, and does not exist in remote repos.
- String requestedResource = "org/apache/maven/test/groups/get-not-on-remotes/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin5" } );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
-
- // Two proxies setup, metadata fetch from remotes fail (because they dont exist).
- assertFetchProjectOrGroup( requestedResource );
-
- // metadata not fetched from both repos, and local version exists.
- // Since there was no updated metadata content from a remote/proxy, a metadata update on
- // the local file never ran. Local only updates are performed via the metadata updater consumer.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin5" } );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
- assertNoRepoMetadata( ID_PROXIED2, requestedResource );
- }
-
- @Test
- public void testGetGroupMetadataProxiedOnLocalOnRemote()
- throws Exception
- {
- // Project metadata that exist locally and exists on remote.
- String requestedResource = "org/apache/maven/test/groups/get-on-local-on-remote/maven-metadata.xml";
- setupTestableManagedRepository( requestedResource );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.FIX, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, false );
-
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin6", "plugin7" } );
- assertNoRepoMetadata( ID_PROXIED1, requestedResource );
-
- // One proxy setup, metadata fetched from remote, local exists.
- assertFetchProjectOrGroup( requestedResource );
-
- // Remote fetched. Local updated.
- assertGroupMetadataContents( requestedResource, new String[]{ "plugin6", "plugin7", "plugin4" } );
- assertRepoGroupMetadataContents( ID_PROXIED1, requestedResource, new String[]{ "plugin7", "plugin4" } );
- }
-
- /**
- * Transfer the metadata file.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertFetchProjectOrGroup( String requestedResource )
- throws Exception
- {
- File expectedFile = new File( managedDefaultDir, requestedResource );
-
- ProjectReference metadata = createProjectReference( requestedResource );
-
- File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
- managedDefaultRepository.toMetadataPath(
- metadata ) );
-
- assertNotNull( "Should have downloaded a file.", downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- private ProjectReference createProjectReference( String path )
- throws RepositoryMetadataException
- {
- return metadataTools.toProjectReference( path );
- }
-
- /**
- * Transfer the metadata file, not expected to succeed.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertFetchProjectOrGroupFailed( String requestedResource )
- throws Exception
- {
- File expectedFile = new File( managedDefaultDir, requestedResource );
- ProjectReference metadata = createProjectReference( requestedResource );
-
- File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
- managedDefaultRepository.toMetadataPath(
- metadata ) );
-
- assertNull( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Transfer the metadata file.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertFetchVersioned( String requestedResource )
- throws Exception
- {
- File expectedFile = new File( managedDefaultDir, requestedResource );
-
- VersionedReference metadata = createVersionedReference( requestedResource );
-
- File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
- managedDefaultRepository.toMetadataPath(
- metadata ) );
-
- assertNotNull( "Should have downloaded a file.", downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- private VersionedReference createVersionedReference( String path )
- throws RepositoryMetadataException
- {
- return metadataTools.toVersionedReference( path );
- }
-
- /**
- * Transfer the metadata file, not expected to succeed.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertFetchVersionedFailed( String requestedResource )
- throws Exception
- {
- File expectedFile = new File( managedDefaultDir, requestedResource );
- VersionedReference metadata = createVersionedReference( requestedResource );
-
- File downloadedFile = proxyHandler.fetchMetatadaFromProxies( managedDefaultRepository,
- managedDefaultRepository.toMetadataPath(
- metadata ) );
-
- assertNull( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * Test for the existance of the requestedResource in the default managed repository.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertResourceExists( String requestedResource )
- throws Exception
- {
- File actualFile = new File( managedDefaultDir, requestedResource );
- assertTrue( "Resource should exist: " + requestedResource, actualFile.exists() );
- }
-
- private void assertMetadataEquals( String expectedMetadataXml, File actualFile )
- throws Exception
- {
- assertNotNull( "Actual File should not be null.", actualFile );
-
- assertTrue( "Actual file exists.", actualFile.exists() );
-
- StringWriter actualContents = new StringWriter();
- ArchivaRepositoryMetadata metadata = RepositoryMetadataReader.read( actualFile );
- RepositoryMetadataWriter.write( metadata, actualContents );
-
- DetailedDiff detailedDiff = new DetailedDiff( new Diff( expectedMetadataXml, actualContents.toString() ) );
- if ( !detailedDiff.similar() )
- {
- assertEquals( expectedMetadataXml, actualContents );
- }
-
- // assertEquals( "Check file contents.", expectedMetadataXml, actualContents );
- }
-
- /**
- * Ensures that the requested resource is not present in the managed repository.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertNoMetadata( String requestedResource )
- throws Exception
- {
- File expectedFile = new File( managedDefaultDir, requestedResource );
- assertFalse( "metadata should not exist: " + expectedFile, expectedFile.exists() );
- }
-
- /**
- * Ensures that the proxied repository specific maven metadata file does NOT exist in the
- * managed repository.
- *
- * @param proxiedRepoId the proxied repository id to validate with.
- * @param requestedResource the resource requested.
- */
- private void assertNoRepoMetadata( String proxiedRepoId, String requestedResource )
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- File actualFile = new File( managedDefaultDir, proxiedFile );
- assertFalse( "Repo specific metadata should not exist: " + actualFile, actualFile.exists() );
- }
-
- private void assertGroupMetadataContents( String requestedResource, String expectedPlugins[] )
- throws Exception
- {
- File actualFile = new File( managedDefaultDir, requestedResource );
- assertTrue( "Snapshot Metadata should exist: " + requestedResource, actualFile.exists() );
-
- ProjectReference actualMetadata = createGroupReference( requestedResource );
-
- assertGroupMetadata( actualFile, actualMetadata, expectedPlugins );
- }
-
- private ProjectReference createGroupReference( String requestedResource )
- throws RepositoryMetadataException
- {
- ProjectReference projectReference = createProjectReference( requestedResource );
- projectReference.setGroupId( projectReference.getGroupId() + "." + projectReference.getArtifactId() );
- projectReference.setArtifactId( null );
- return projectReference;
- }
-
- private void assertRepoGroupMetadataContents( String proxiedRepoId, String requestedResource,
- String expectedPlugins[] )
- throws Exception
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- File actualFile = new File( managedDefaultDir, proxiedFile );
- assertTrue( "Repo Specific Group Metadata should exist: " + requestedResource, actualFile.exists() );
-
- ProjectReference actualMetadata = createGroupReference( requestedResource );
-
- assertGroupMetadata( actualFile, actualMetadata, expectedPlugins );
- }
-
- private void assertGroupMetadata( File actualFile, ProjectReference actualMetadata, String expectedPlugins[] )
- throws Exception
- {
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( actualMetadata.getGroupId() );
-
- for ( String pluginId : expectedPlugins )
- {
- Plugin p = new Plugin();
- p.setPrefix( pluginId );
- p.setArtifactId( pluginId + "-maven-plugin" );
- p.setName( "The " + pluginId + " Plugin" );
- m.getPlugins().add( p );
- }
-
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Test for the existance of the requestedResource in the default managed repository, and if it exists,
- * does it contain the specified list of expected versions?
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertProjectMetadataContents( String requestedResource, String expectedVersions[],
- String latestVersion, String releaseVersion )
- throws Exception
- {
- File actualFile = new File( managedDefaultDir, requestedResource );
- assertTrue( actualFile.exists() );
-
- ProjectReference metadata = createProjectReference( requestedResource );
-
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( metadata.getGroupId() );
- m.setArtifactId( metadata.getArtifactId() );
- m.setLatestVersion( latestVersion );
- m.setReleasedVersion( releaseVersion );
-
- if ( expectedVersions != null )
- {
- m.getAvailableVersions().addAll( Arrays.asList( expectedVersions ) );
- }
-
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Test for the existance of the requestedResource in the default managed repository, and if it exists,
- * does it contain the expected release maven-metadata.xml contents?
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertReleaseMetadataContents( String requestedResource )
- throws Exception
- {
- File actualFile = new File( managedDefaultDir, requestedResource );
- assertTrue( "Release Metadata should exist: " + requestedResource, actualFile.exists() );
-
- VersionedReference metadata = createVersionedReference( requestedResource );
-
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( metadata.getGroupId() );
- m.setArtifactId( metadata.getArtifactId() );
- m.setVersion( metadata.getVersion() );
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Test for the existance of the snapshot metadata in the default managed repository, and if it exists,
- * does it contain the expected release maven-metadata.xml contents?
- *
- * @param requestedResource the requested resource
- * @param expectedDate the date in "yyyyMMdd" format
- * @param expectedTime the time in "hhmmss" format
- * @param expectedBuildnumber the build number
- * @throws Exception
- */
- private void assertSnapshotMetadataContents( String requestedResource, String expectedDate, String expectedTime,
- int expectedBuildnumber )
- throws Exception
- {
- File actualFile = new File( managedDefaultDir, requestedResource );
- assertTrue( "Snapshot Metadata should exist: " + requestedResource, actualFile.exists() );
-
- VersionedReference actualMetadata = createVersionedReference( requestedResource );
-
- assertSnapshotMetadata( actualFile, actualMetadata, expectedDate, expectedTime, expectedBuildnumber );
- }
-
- /**
- * Test for the existance of the proxied repository specific snapshot metadata in the default managed
- * repository, and if it exists, does it contain the expected release maven-metadata.xml contents?
- *
- * @param proxiedRepoId the repository id of the proxied repository.
- * @param requestedResource the requested resource
- * @param expectedDate the date in "yyyyMMdd" format
- * @param expectedTime the time in "hhmmss" format
- * @param expectedBuildnumber the build number
- * @throws Exception
- */
- private void assertRepoSnapshotMetadataContents( String proxiedRepoId, String requestedResource,
- String expectedDate, String expectedTime, int expectedBuildnumber )
- throws Exception
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- File actualFile = new File( managedDefaultDir, proxiedFile );
- assertTrue( "Repo Specific Snapshot Metadata should exist: " + requestedResource, actualFile.exists() );
-
- VersionedReference actualMetadata = createVersionedReference( requestedResource );
-
- assertSnapshotMetadata( actualFile, actualMetadata, expectedDate, expectedTime, expectedBuildnumber );
- }
-
- private void assertSnapshotMetadata( File actualFile, VersionedReference actualMetadata, String expectedDate,
- String expectedTime, int expectedBuildnumber )
- throws RepositoryMetadataException, Exception
- {
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( actualMetadata.getGroupId() );
- m.setArtifactId( actualMetadata.getArtifactId() );
- m.setVersion( VersionUtil.getBaseVersion( actualMetadata.getVersion() ) );
-
- m.setSnapshotVersion( new SnapshotVersion() );
-
- if ( StringUtils.isNotBlank( expectedDate ) && StringUtils.isNotBlank( expectedTime ) )
- {
- m.getSnapshotVersion().setTimestamp( expectedDate + "." + expectedTime );
- }
-
- m.getSnapshotVersion().setBuildNumber( expectedBuildnumber );
-
- m.setLastUpdated( expectedDate + expectedTime );
-
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Ensures that the repository specific maven metadata file exists, and contains the appropriate
- * list of expected versions within.
- *
- * @param proxiedRepoId
- * @param requestedResource
- * @param expectedProxyVersions
- */
- private void assertRepoProjectMetadata( String proxiedRepoId, String requestedResource,
- String[] expectedProxyVersions )
- throws Exception
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- File actualFile = new File( managedDefaultDir, proxiedFile );
- assertTrue( actualFile.exists() );
-
- ProjectReference metadata = createProjectReference( requestedResource );
-
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( metadata.getGroupId() );
- m.setArtifactId( metadata.getArtifactId() );
-
- if ( expectedProxyVersions != null )
- {
- m.getAvailableVersions().addAll( Arrays.asList( expectedProxyVersions ) );
- }
-
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Ensures that the repository specific maven metadata file exists, and contains the appropriate
- * list of expected versions within.
- *
- * @param proxiedRepoId
- * @param requestedResource
- */
- private void assertRepoReleaseMetadataContents( String proxiedRepoId, String requestedResource )
- throws Exception
- {
- String proxiedFile = metadataTools.getRepositorySpecificName( proxiedRepoId, requestedResource );
-
- File actualFile = new File( managedDefaultDir, proxiedFile );
- assertTrue( "Release metadata for repo should exist: " + actualFile, actualFile.exists() );
-
- VersionedReference metadata = createVersionedReference( requestedResource );
-
- // Build expected metadata XML
- StringWriter expectedMetadataXml = new StringWriter();
- ArchivaRepositoryMetadata m = new ArchivaRepositoryMetadata();
- m.setGroupId( metadata.getGroupId() );
- m.setArtifactId( metadata.getArtifactId() );
- m.setVersion( metadata.getVersion() );
- RepositoryMetadataWriter.write( m, expectedMetadataXml );
-
- // Compare the file to the actual contents.
- assertMetadataEquals( expectedMetadataXml.toString(), actualFile );
- }
-
- /**
- * Test for the non-existance of the requestedResource in the default managed repository.
- *
- * @param requestedResource the requested resource
- * @throws Exception
- */
- private void assertResourceNotFound( String requestedResource )
- throws Exception
- {
- File actualFile = new File( managedDefaultDir, requestedResource );
- assertFalse( "Resource should not exist: " + requestedResource, actualFile.exists() );
- }
-
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.maven.archiva.configuration.ArchivaConfiguration;
-import org.apache.maven.archiva.configuration.Configuration;
-import org.apache.maven.archiva.configuration.ConfigurationListener;
-import org.apache.maven.archiva.configuration.FileType;
-import org.apache.maven.archiva.configuration.FileTypes;
-import org.apache.maven.archiva.configuration.RepositoryScanningConfiguration;
-import org.codehaus.plexus.registry.Registry;
-import org.codehaus.plexus.registry.RegistryException;
-import org.codehaus.plexus.registry.RegistryListener;
-import org.easymock.MockControl;
-import org.springframework.stereotype.Service;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import javax.annotation.PostConstruct;
-
-/**
- * MockConfiguration
- *
- * @version $Id$
- */
-@Service( "archivaConfiguration#mock" )
-public class MockConfiguration
- implements ArchivaConfiguration
-{
-
- private Configuration configuration = new Configuration();
-
- private Set<RegistryListener> registryListeners = new HashSet<RegistryListener>();
-
- private Set<ConfigurationListener> configListeners = new HashSet<ConfigurationListener>();
-
- private MockControl registryControl;
-
- private Registry registryMock;
-
- public MockConfiguration()
- {
- registryControl = MockControl.createNiceControl( Registry.class );
- registryMock = (Registry) registryControl.getMock();
- }
-
- @PostConstruct
- public void initialize()
- throws Exception
- {
-
- configuration.setRepositoryScanning( new RepositoryScanningConfiguration()
- {
- @Override
- public List<FileType> getFileTypes()
- {
- FileType fileType = new FileType();
- fileType.setId( FileTypes.ARTIFACTS );
- fileType.setPatterns( Collections.singletonList( "**/*" ) );
- return Collections.singletonList( fileType );
- }
- } );
- }
-
- public void addChangeListener( RegistryListener listener )
- {
- registryListeners.add( listener );
- }
-
- public Configuration getConfiguration()
- {
- return configuration;
- }
-
- public void save( Configuration configuration )
- throws RegistryException
- {
- /* do nothing */
- }
-
- public void triggerChange( String name, String value )
- {
- for ( RegistryListener listener : registryListeners )
- {
- try
- {
- listener.afterConfigurationChange( registryMock, name, value );
- }
- catch ( Exception e )
- {
- e.printStackTrace();
- }
- }
- }
-
- public void addListener( ConfigurationListener listener )
- {
- configListeners.add( listener );
- }
-
- public void removeListener( ConfigurationListener listener )
- {
- configListeners.remove( listener );
- }
-
- public boolean isDefaulted()
- {
- return false;
- }
-
- public void reload()
- {
- // no op
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import org.apache.maven.archiva.model.ArtifactReference;
-import org.apache.maven.archiva.policies.CachedFailuresPolicy;
-import org.apache.maven.archiva.policies.ChecksumPolicy;
-import org.apache.maven.archiva.policies.ReleasesPolicy;
-import org.apache.maven.archiva.policies.SnapshotsPolicy;
-import org.junit.Test;
-
-import java.io.File;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-/**
- * SnapshotTransferTest
- *
- * @version $Id$
- */
-public class SnapshotTransferTest
- extends AbstractProxyTestCase
-{
- @Test
- public void testSnapshotNonExistant()
- throws Exception
- {
- String path = "org/apache/maven/test/does-not-exist/1.0-SNAPSHOT/does-not-exist-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- expectedFile.delete();
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testTimestampDrivenSnapshotNotPresentAlready()
- throws Exception
- {
- String path = "org/apache/maven/test/get-timestamped-snapshot/1.0-SNAPSHOT/get-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- expectedFile.delete();
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testNewerTimestampDrivenSnapshotOnFirstRepo()
- throws Exception
- {
- String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
- expectedFile.setLastModified( getPastDate().getTime() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testOlderTimestampDrivenSnapshotOnFirstRepo()
- throws Exception
- {
- String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, path );
-
- setManagedNewerThanRemote( expectedFile, remoteFile );
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false );
-
- // Attempt to download.
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- // Should not have downloaded as managed is newer than remote.
- assertNotDownloaded( downloadedFile );
- assertNoTempFiles( expectedFile );
- }
-
- /**
- * TODO: Has problems with wagon implementation not preserving timestamp.
- */
- /*
- public void testNewerTimestampDrivenSnapshotOnSecondRepoThanFirstNotPresentAlready()
- throws Exception
- {
- String path = "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/get-timestamped-snapshot-in-both-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = createArtifactReference( "default", path );
-
- expectedFile.delete();
- assertFalse( expectedFile.exists() );
-
- // Create customized proxy / target repository
- File targetProxyDir = saveTargetedRepositoryConfig( ID_PROXIED1_TARGET, REPOPATH_PROXIED1,
- REPOPATH_PROXIED1_TARGET, "default" );
-
- new File( targetProxyDir, path ).setLastModified( getPastDate().getTime() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1_TARGET, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
- SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
- SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- // Should have downloaded the content from proxy2, as proxy1 has an old (by file.lastModified check) version.
- File proxiedFile = new File( REPOPATH_PROXIED2, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- public void testOlderTimestampDrivenSnapshotOnSecondRepoThanFirstNotPresentAlready()
- throws Exception
- {
- String path = "org/apache/maven/test/get-timestamped-snapshot-in-both/1.0-SNAPSHOT/get-timestamped-snapshot-in-both-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = createArtifactReference( "default", path );
-
- expectedFile.delete();
- assertFalse( expectedFile.exists() );
-
- // Create customized proxy / target repository
- File targetProxyDir = saveTargetedRepositoryConfig( ID_PROXIED2_TARGET, REPOPATH_PROXIED2,
- REPOPATH_PROXIED2_TARGET, "default" );
-
- new File( targetProxyDir, path ).setLastModified( getPastDate().getTime() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
- SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2_TARGET, ChecksumPolicy.IGNORED, ReleasesPolicy.IGNORED,
- SnapshotsPolicy.IGNORED, CachedFailuresPolicy.IGNORED );
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1_TARGET, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- } */
-
- @Test
- public void testTimestampDrivenSnapshotNotExpired()
- throws Exception
- {
- String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- File proxiedFile = new File( REPOPATH_PROXIED1, path );
- proxiedFile.setLastModified( getFutureDate().getTime() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testTimestampDrivenSnapshotNotUpdated()
- throws Exception
- {
- String path = "org/apache/maven/test/get-present-timestamped-snapshot/1.0-SNAPSHOT/get-present-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- File remoteFile = new File( REPOPATH_PROXIED1, path );
-
- setManagedNewerThanRemote( expectedFile, remoteFile, 12000000 );
- long expectedTimestamp = expectedFile.lastModified();
-
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- assertNotDownloaded( downloadedFile );
- assertNotModified( expectedFile, expectedTimestamp );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testTimestampDrivenSnapshotNotPresentAlreadyExpiredCacheFailure()
- throws Exception
- {
- String path = "org/apache/maven/test/get-timestamped-snapshot/1.0-SNAPSHOT/get-timestamped-snapshot-1.0-SNAPSHOT.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- expectedFile.delete();
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES , false);
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED2, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
- SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.YES , false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testMetadataDrivenSnapshotNotPresentAlready()
- throws Exception
- {
- String path = "org/apache/maven/test/get-metadata-snapshot/1.0-SNAPSHOT/get-metadata-snapshot-1.0-20050831.101112-1.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- expectedFile.delete();
- assertFalse( expectedFile.exists() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-
- @Test
- public void testGetMetadataDrivenSnapshotRemoteUpdate()
- throws Exception
- {
- // Metadata driven snapshots (using a full timestamp) are treated like a release. It is the timing of the
- // updates to the metadata files that triggers which will be downloaded
-
- String path = "org/apache/maven/test/get-present-metadata-snapshot/1.0-SNAPSHOT/get-present-metadata-snapshot-1.0-20050831.101112-1.jar";
- setupTestableManagedRepository( path );
-
- File expectedFile = new File( managedDefaultDir, path );
- ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
-
- assertTrue( expectedFile.exists() );
-
- expectedFile.setLastModified( getPastDate().getTime() );
-
- // Configure Connector (usually done within archiva.xml configuration)
- saveConnector( ID_DEFAULT_MANAGED, ID_PROXIED1, false);
-
- File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
-
- File proxiedFile = new File( REPOPATH_PROXIED1, path );
- assertFileEquals( expectedFile, downloadedFile, proxiedFile );
- assertNoTempFiles( expectedFile );
- }
-}
+++ /dev/null
-package org.apache.maven.archiva.proxy;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.maven.wagon.ConnectionException;
-import org.apache.maven.wagon.ResourceDoesNotExistException;
-import org.apache.maven.wagon.TransferFailedException;
-import org.apache.maven.wagon.Wagon;
-import org.apache.maven.wagon.authentication.AuthenticationException;
-import org.apache.maven.wagon.authentication.AuthenticationInfo;
-import org.apache.maven.wagon.authorization.AuthorizationException;
-import org.apache.maven.wagon.events.SessionListener;
-import org.apache.maven.wagon.events.TransferListener;
-import org.apache.maven.wagon.proxy.ProxyInfo;
-import org.apache.maven.wagon.proxy.ProxyInfoProvider;
-import org.apache.maven.wagon.repository.Repository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-/**
- * A dummy wagon implementation
- *
- */
-@Service("wagon#test")
-public class WagonDelegate
- implements Wagon
-{
- private Logger log = LoggerFactory.getLogger( WagonDelegate.class );
-
- private Wagon delegate;
-
- private String contentToGet;
-
- public void get( String resourceName, File destination )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- log.debug( ".get({}, {})", resourceName, destination );
- delegate.get( resourceName, destination );
- create( destination );
- }
-
- public boolean getIfNewer( String resourceName, File destination, long timestamp )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- log.info( ".getIfNewer(" + resourceName + ", " + destination + ", " + timestamp + ")" );
-
- boolean result = delegate.getIfNewer( resourceName, destination, timestamp );
- createIfMissing( destination );
- return result;
- }
-
- public void put( File source, String destination )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- delegate.put( source, destination );
- }
-
- public void putDirectory( File sourceDirectory, String destinationDirectory )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- delegate.putDirectory( sourceDirectory, destinationDirectory );
- }
-
- public boolean resourceExists( String resourceName )
- throws TransferFailedException, AuthorizationException
- {
- return delegate.resourceExists( resourceName );
- }
-
- @SuppressWarnings("unchecked")
- public List<String> getFileList( String destinationDirectory )
- throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
- {
- return delegate.getFileList( destinationDirectory );
- }
-
- public boolean supportsDirectoryCopy()
- {
- return delegate.supportsDirectoryCopy();
- }
-
- public void setTimeout(int val)
- {
- // ignore
- }
-
- public int getTimeout()
- {
- return 0;
- }
-
- public Repository getRepository()
- {
- return delegate.getRepository();
- }
-
- public void connect( Repository source )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source );
- }
-
- public void connect( Repository source, ProxyInfo proxyInfo )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, proxyInfo );
- }
-
- public void connect( Repository source, ProxyInfoProvider proxyInfoProvider )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, proxyInfoProvider );
- }
-
- public void connect( Repository source, AuthenticationInfo authenticationInfo )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, authenticationInfo );
- }
-
- public void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfo proxyInfo )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, authenticationInfo, proxyInfo );
- }
-
- public void connect( Repository source, AuthenticationInfo authenticationInfo, ProxyInfoProvider proxyInfoProvider )
- throws ConnectionException, AuthenticationException
- {
- delegate.connect( source, authenticationInfo, proxyInfoProvider );
- }
-
- @SuppressWarnings("deprecation")
- public void openConnection()
- throws ConnectionException, AuthenticationException
- {
- delegate.openConnection();
- }
-
- public void disconnect()
- throws ConnectionException
- {
- delegate.disconnect();
- }
-
- public void addSessionListener( SessionListener listener )
- {
- delegate.addSessionListener( listener );
- }
-
- public void removeSessionListener( SessionListener listener )
- {
- delegate.removeSessionListener( listener );
- }
-
- public boolean hasSessionListener( SessionListener listener )
- {
- return delegate.hasSessionListener( listener );
- }
-
- public void addTransferListener( TransferListener listener )
- {
- delegate.addTransferListener( listener );
- }
-
- public void removeTransferListener( TransferListener listener )
- {
- delegate.removeTransferListener( listener );
- }
-
- public boolean hasTransferListener( TransferListener listener )
- {
- return delegate.hasTransferListener( listener );
- }
-
- public boolean isInteractive()
- {
- return delegate.isInteractive();
- }
-
- public void setInteractive( boolean interactive )
- {
- delegate.setInteractive( interactive );
- }
-
- public void setDelegate( Wagon delegate )
- {
- this.delegate = delegate;
- }
-
- void setContentToGet( String content )
- {
- contentToGet = content;
- }
-
- private void createIfMissing( File destination )
- {
- // since the mock won't actually copy a file, create an empty one to simulate file existence
- if ( !destination.exists() )
- {
- create( destination );
- }
- }
-
- private void create( File destination )
- {
- try
- {
- destination.getParentFile().mkdirs();
- if ( contentToGet == null )
- {
- destination.createNewFile();
- }
- else
- {
- FileUtils.writeStringToFile( new File( destination.getAbsolutePath() ), contentToGet, null );
- }
- }
- catch ( IOException e )
- {
- throw new RuntimeException( e.getMessage(), e );
- }
- }
-}
<component>
<role>org.apache.maven.wagon.Wagon</role>
<role-hint>test</role-hint>
- <implementation>org.apache.maven.archiva.proxy.WagonDelegate</implementation>
+ <implementation>org.apache.archiva.proxy.WagonDelegate</implementation>
</component>
</components>
</component-set>
</bean>
- <bean name="repositoryProxyConnectors#test" class="org.apache.maven.archiva.proxy.DefaultRepositoryProxyConnectors">
+ <bean name="repositoryProxyConnectors#test" class="org.apache.archiva.proxy.DefaultRepositoryProxyConnectors">
<property name="archivaConfiguration" ref="archivaConfiguration#mock"/>
<property name="repositoryFactory" ref="repositoryContentFactory#mocked"/>
<property name="metadataTools" ref="metadataTools#mocked"/>
import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
import org.apache.maven.archiva.model.ArtifactReference;
import org.apache.maven.archiva.policies.ProxyDownloadException;
-import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
+import org.apache.archiva.proxy.RepositoryProxyConnectors;
import org.apache.maven.archiva.repository.ManagedRepositoryContent;
import org.apache.maven.archiva.repository.RepositoryContentFactory;
import org.apache.maven.archiva.repository.RepositoryException;
import org.apache.maven.archiva.configuration.ArchivaConfiguration;
import org.apache.maven.archiva.configuration.Configuration;
import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
-import org.apache.maven.archiva.proxy.DefaultRepositoryProxyConnectors;
+import org.apache.archiva.proxy.DefaultRepositoryProxyConnectors;
import org.apache.maven.archiva.repository.ManagedRepositoryContent;
import org.apache.maven.archiva.repository.RepositoryContentFactory;
import org.apache.maven.archiva.repository.content.LegacyPathParser;