o first push of a plug point for repository/transport in maven

git-svn-id: https://svn.apache.org/repos/asf/maven/components/trunk@746285 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Jason van Zyl 2009-02-20 16:27:27 +00:00
parent c4db569df7
commit a8cd789425
18 changed files with 655 additions and 1868 deletions

7
bs
View File

@ -5,9 +5,6 @@
# and maven-3 requires a specific default implementation
#
export CLASSPATH=./mercury-ant-tasks-1.0-alpha-6-SNAPSHOT.jar
export ANT_OPTS='-Dmercury.log.threshold=debug -Djavax.xml.stream.XMLInputFactory=com.ctc.wstx.stax.WstxInputFactory -Dmercury.repo.central=http://repository.sonatype.org/content/groups/public '
export ANT_OPTS='-Dmercury.log.threshold=warn -Djavax.xml.stream.XMLInputFactory=com.ctc.wstx.stax.WstxInputFactory -Dmaven.repo.central=http://repository.sonatype.org/content/groups/public '
#export ANT_OPTS=$ANT_OPTS' -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000'
echo ANT_OPTS=$ANT_OPTS
ant -f build-mercury.xml $*
ant -f build-mercury.xml

View File

@ -69,12 +69,6 @@ public class DefaultArtifactDeployer
public void deploy( File source, Artifact artifact, ArtifactRepository deploymentRepository, ArtifactRepository localRepository )
throws ArtifactDeploymentException
{
if ( !wagonManager.isOnline() )
{
// deployment shouldn't silently fail when offline
throw new ArtifactDeploymentException( "System is offline. Cannot deploy artifact: " + artifact + "." );
}
try
{
transformationManager.transformForDeployment( artifact, deploymentRepository, localRepository );

View File

@ -72,21 +72,14 @@ import org.codehaus.plexus.util.xml.Xpp3Dom;
@Component(role=WagonManager.class)
public class DefaultWagonManager
extends AbstractLogEnabled
implements WagonManager, Contextualizable
implements WagonManager
{
private static final String WILDCARD = "*";
private static final String EXTERNAL_WILDCARD = "external:*";
private static final String[] CHECKSUM_IDS = {"md5", "sha1"};
/** have to match the CHECKSUM_IDS */
private static final String[] CHECKSUM_ALGORITHMS = {"MD5", "SHA-1"};
private static final String MAVEN_ARTIFACT_PROPERTIES = "META-INF/maven/org.apache.maven.artifact/maven-artifact/pom.properties";
private static int anonymousMirrorIdSeed = 0;
@Requirement
private PlexusContainer container;
// TODO: proxies, authentication and mirrors are via settings, and should come in via an alternate method - perhaps
@ -119,7 +112,7 @@ public class DefaultWagonManager
@Requirement(role=Wagon.class)
private Map wagons;
/** encapsulates access to Server credentials */
//@Requirement
private CredentialsDataSource credentialsDataSource;
@Requirement
@ -138,6 +131,7 @@ public class DefaultWagonManager
throw new UnsupportedProtocolException( "The repository " + repository + " does not specify a protocol" );
}
Wagon wagon = getWagon( protocol );
configureWagon( wagon, repository.getId(), protocol );
@ -153,6 +147,7 @@ public class DefaultWagonManager
throw new UnsupportedProtocolException( "Unspecified protocol" );
}
String hint = protocol.toLowerCase( java.util.Locale.ENGLISH );
Wagon wagon = (Wagon) wagons.get( hint );
@ -162,8 +157,6 @@ public class DefaultWagonManager
"Cannot find wagon which supports the requested protocol: " + protocol );
}
wagon.setInteractive( interactive );
return wagon;
}
@ -190,8 +183,6 @@ public class DefaultWagonManager
TransferListener downloadMonitor )
throws TransferFailedException
{
failIfNotOnline();
String protocol = repository.getProtocol();
Wagon wagon;
@ -227,20 +218,6 @@ public class DefaultWagonManager
{
Repository artifactRepository = new Repository( repository.getId(), repository.getUrl() );
if ( serverPermissionsMap.containsKey( repository.getId() ) )
{
RepositoryPermissions perms = serverPermissionsMap.get( repository.getId() );
getLogger().debug(
"adding permissions to wagon connection: " + perms.getFileMode() + " " + perms.getDirectoryMode() );
artifactRepository.setPermissions( perms );
}
else
{
getLogger().debug( "not adding permissions to wagon connection" );
}
AuthenticationInfo authenticationInfo = getAuthenticationInfo( repository.getId() );
wagon.connect( artifactRepository, authenticationInfo, new ProxyInfoProvider()
@ -416,8 +393,7 @@ public class DefaultWagonManager
try
{
getRemoteFile( getMirrorRepository( repository ), artifact.getFile(), remotePath, downloadMonitor,
policy.getChecksumPolicy(), false );
getRemoteFile( repository, artifact.getFile(), remotePath, downloadMonitor, policy.getChecksumPolicy(), false );
}
finally
{
@ -442,8 +418,7 @@ public class DefaultWagonManager
try
{
getRemoteFile( getMirrorRepository( repository ), artifact.getFile(), remotePath, downloadMonitor,
policy.getChecksumPolicy(), false );
getRemoteFile( repository, artifact.getFile(), remotePath, downloadMonitor, policy.getChecksumPolicy(), false );
}
catch ( ResourceDoesNotExistException e )
{
@ -475,7 +450,7 @@ public class DefaultWagonManager
{
getLogger().debug( "Trying repository " + repository.getId() );
getRemoteFile( getMirrorRepository( repository ), artifact.getFile(), remotePath, downloadMonitor, policy.getChecksumPolicy(), false );
getRemoteFile( repository, artifact.getFile(), remotePath, downloadMonitor, policy.getChecksumPolicy(), false );
getLogger().debug( " Artifact resolved" );
@ -491,7 +466,7 @@ public class DefaultWagonManager
{
String remotePath = repository.pathOfRemoteRepositoryMetadata( metadata );
getRemoteFile( getMirrorRepository( repository ), destination, remotePath, null, checksumPolicy, true );
getRemoteFile( repository, destination, remotePath, null, checksumPolicy, true );
}
public void getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata, ArtifactRepository repository,
@ -511,10 +486,6 @@ public class DefaultWagonManager
boolean force )
throws TransferFailedException, ResourceDoesNotExistException
{
// TODO: better excetpions - transfer failed is not enough?
failIfNotOnline();
String protocol = repository.getProtocol();
Wagon wagon;
@ -736,35 +707,6 @@ public class DefaultWagonManager
}
}
public ArtifactRepository getMirrorRepository( ArtifactRepository repository )
{
ArtifactRepository mirror = getMirror( repository );
if ( mirror != null )
{
String id = mirror.getId();
if ( id == null )
{
// TODO: this should be illegal in settings.xml
id = repository.getId();
}
getLogger().debug( "Using mirror: " + mirror.getId() + " for repository: " + repository.getId() + "\n(mirror url: " + mirror.getUrl() + ")" );
repository = repositoryFactory.createArtifactRepository( id, mirror.getUrl(),
repository.getLayout(), repository.getSnapshots(),
repository.getReleases() );
}
return repository;
}
private void failIfNotOnline()
throws TransferFailedException
{
if ( !isOnline() )
{
throw new TransferFailedException( "System is offline." );
}
}
private void handleChecksumFailure( String checksumPolicy,
String message,
Throwable cause )
@ -878,92 +820,7 @@ public class DefaultWagonManager
public AuthenticationInfo getAuthenticationInfo( String id )
throws CredentialsDataSourceException
{
return credentialsDataSource == null
? authenticationInfoMap.get( id )
: credentialsDataSource.get( id );
}
/**
* This method finds a matching mirror for the selected repository. If there is an exact match, this will be used.
* If there is no exact match, then the list of mirrors is examined to see if a pattern applies.
*
* @param originalRepository See if there is a mirror for this repository.
* @return the selected mirror or null if none are found.
*/
public ArtifactRepository getMirror( ArtifactRepository originalRepository )
{
ArtifactRepository selectedMirror = mirrors.get( originalRepository.getId() );
if ( null == selectedMirror )
{
// Process the patterns in order. First one that matches wins.
Set<String> keySet = mirrors.keySet();
if ( keySet != null )
{
for (String pattern : keySet)
{
if (matchPattern(originalRepository, pattern))
{
selectedMirror = mirrors.get(pattern);
break;
}
}
}
}
return selectedMirror;
}
/**
* This method checks if the pattern matches the originalRepository.
* Valid patterns:
* * = everything
* external:* = everything not on the localhost and not file based.
* repo,repo1 = repo or repo1
* *,!repo1 = everything except repo1
*
* @param originalRepository to compare for a match.
* @param pattern used for match. Currently only '*' is supported.
* @return true if the repository is a match to this pattern.
*/
public boolean matchPattern( ArtifactRepository originalRepository, String pattern )
{
boolean result = false;
String originalId = originalRepository.getId();
// simple checks first to short circuit processing below.
if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) )
{
result = true;
}
else
{
// process the list
String[] repos = pattern.split( "," );
for (String repo : repos) {
// see if this is a negative match
if (repo.length() > 1 && repo.startsWith("!")) {
if (originalId.equals(repo.substring(1))) {
// explicitly exclude. Set result and stop processing.
result = false;
break;
}
}
// check for exact match
else if (originalId.equals(repo)) {
result = true;
break;
}
// check for external:*
else if (EXTERNAL_WILDCARD.equals(repo) && isExternalRepo(originalRepository)) {
result = true;
// don't stop processing in case a future segment explicitly excludes this repo
} else if (WILDCARD.equals(repo)) {
result = true;
// don't stop processing in case a future segment explicitly excludes this repo
}
}
}
return result;
return authenticationInfoMap.get( id );
}
/**
@ -1016,18 +873,6 @@ public class DefaultWagonManager
proxies.put( protocol, proxyInfo );
}
public void contextualize( Context context )
throws ContextException
{
container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
}
/** @todo I'd rather not be setting this explicitly. */
public void setDownloadMonitor( TransferListener downloadMonitor )
{
this.downloadMonitor = downloadMonitor;
}
// We are leaving this method here so that we can attempt to use the new maven-artifact
// library from the 2.0.x code so that we aren't maintaining two lines of code
// for the artifact management.
@ -1047,32 +892,6 @@ public class DefaultWagonManager
authenticationInfoMap.put( repositoryId, authInfo );
}
// This is the new way of handling authentication that will allow us to help users setup
// authentication requirements.
public void addAuthenticationCredentials( String repositoryId,
String username,
String password,
String privateKey,
String passphrase
)
throws CredentialsDataSourceException
{
AuthenticationInfo authInfo = new AuthenticationInfo();
authInfo.setUserName( username );
authInfo.setPassword( password );
authInfo.setPrivateKey( privateKey );
authInfo.setPassphrase( passphrase );
if ( credentialsDataSource == null )
{
authenticationInfoMap.put( repositoryId, authInfo );
}
else
{
credentialsDataSource.set( new CredentialsChangeRequest( repositoryId, authInfo, null ) );
}
}
public void addPermissionInfo( String repositoryId,
String filePermissions,
String directoryPermissions )
@ -1099,35 +918,6 @@ public class DefaultWagonManager
}
}
public void addMirror( String id,
String mirrorOf,
String url )
{
if ( id == null )
{
id = "mirror-" + anonymousMirrorIdSeed++;
getLogger().warn( "You are using a mirror that doesn't declare an <id/> element. Using \'" + id + "\' instead:\nId: " + id + "\nmirrorOf: " + mirrorOf + "\nurl: " + url + "\n" );
}
ArtifactRepository mirror = new DefaultArtifactRepository( id, url, null );
//to preserve first wins, don't add repeated mirrors.
if (!mirrors.containsKey( mirrorOf ))
{
mirrors.put( mirrorOf, mirror );
}
}
public void setOnline( boolean online )
{
this.online = online;
}
public boolean isOnline()
{
return online;
}
public void setInteractive( boolean interactive )
{
this.interactive = interactive;
@ -1161,23 +951,16 @@ public class DefaultWagonManager
* @param repository the repository that has the configuration
* @throws WagonConfigurationException wraps any error given during configuration of the wagon instance
*/
private void configureWagon( Wagon wagon,
ArtifactRepository repository )
private void configureWagon( Wagon wagon, ArtifactRepository repository )
throws WagonConfigurationException
{
configureWagon( wagon, repository.getId(), repository.getProtocol() );
}
private void configureWagon( Wagon wagon,
String repositoryId,
String protocol )
private void configureWagon( Wagon wagon, String repositoryId, String protocol )
throws WagonConfigurationException
{
PlexusConfiguration config = (PlexusConfiguration) serverConfigurationMap.get( repositoryId );
if ( protocol.startsWith( "http" ) || protocol.startsWith( "dav" ) )
{
config = updateUserAgentForHttp( wagon, config );
}
if ( config != null )
{
@ -1211,56 +994,6 @@ public class DefaultWagonManager
}
}
private PlexusConfiguration updateUserAgentForHttp( Wagon wagon, PlexusConfiguration config )
{
if ( config == null )
{
config = new XmlPlexusConfiguration( "configuration" );
}
XmlPlexusConfiguration propertyConfig = new XmlPlexusConfiguration( "property" );
PlexusConfiguration headerConfig = config.getChild( "httpHeaders", true );
headerConfig.addChild( propertyConfig );
XmlPlexusConfiguration nameConfig = new XmlPlexusConfiguration( "name" );
nameConfig.setValue( "User-Agent" );
propertyConfig.addChild( nameConfig );
XmlPlexusConfiguration versionConfig = new XmlPlexusConfiguration( "value" );
versionConfig.setValue( httpUserAgent );
propertyConfig.addChild( versionConfig );
return config;
}
public void addConfiguration( String repositoryId,
Xpp3Dom configuration )
{
if ( ( repositoryId == null ) || ( configuration == null ) )
{
throw new IllegalArgumentException( "arguments can't be null" );
}
final XmlPlexusConfiguration xmlConf = new XmlPlexusConfiguration( configuration );
serverConfigurationMap.put( repositoryId, xmlConf );
}
public void setDefaultRepositoryPermissions( RepositoryPermissions defaultRepositoryPermissions )
{
this.defaultRepositoryPermissions = defaultRepositoryPermissions;
}
public void registerCredentialsDataSource( CredentialsDataSource cds )
{
credentialsDataSource = cds;
}
public void setUpdateCheckManager( UpdateCheckManager updateCheckManager )
{
this.updateCheckManager = updateCheckManager;
}
/**
* {@inheritDoc}
*/
@ -1276,4 +1009,11 @@ public class DefaultWagonManager
{
return httpUserAgent;
}
// Things to remove
public void setDownloadMonitor( TransferListener listener )
{
this.downloadMonitor = listener;
}
}

View File

@ -112,65 +112,6 @@ public interface WagonManager
File file, String checksumPolicyWarn )
throws TransferFailedException, ResourceDoesNotExistException;
void setOnline( boolean online );
boolean isOnline();
void addProxy( String protocol,
String host,
int port,
String username,
String password,
String nonProxyHosts );
void registerCredentialsDataSource( CredentialsDataSource cds );
public void addAuthenticationCredentials( String repositoryId,
String username,
String password,
String privateKey,
String passphrase )
throws CredentialsDataSourceException;
void addAuthenticationInfo( String repositoryId,
String username,
String password,
String privateKey,
String passphrase );
void addMirror( String id,
String mirrorOf,
String url );
void setDownloadMonitor( TransferListener downloadMonitor );
void addPermissionInfo( String repositoryId,
String filePermissions,
String directoryPermissions );
ProxyInfo getProxy( String protocol );
AuthenticationInfo getAuthenticationInfo( String id )
throws CredentialsDataSourceException;
/**
* Set the configuration for a repository
*
* @param repositoryId id of the repository to set the configuration to
* @param configuration dom tree of the xml with the configuration for the {@link Wagon}
*/
void addConfiguration( String repositoryId,
Xpp3Dom configuration );
void setInteractive( boolean interactive );
@Deprecated
void registerWagons( Collection wagons,
PlexusContainer extensionContainer );
void findAndRegisterWagons( PlexusContainer container );
void setDefaultRepositoryPermissions( RepositoryPermissions permissions );
ArtifactRepository getMirrorRepository( ArtifactRepository repository );
// All the tests fail that are specifically look for the contents of the listener fail without this.
void setDownloadMonitor( TransferListener listener );
}

View File

@ -1,22 +1,18 @@
package org.apache.maven.artifact.repository.metadata;
/*
* 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
* 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.
* 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;
@ -68,77 +64,76 @@ public class DefaultRepositoryMetadataManager
{
}
public void resolve( RepositoryMetadata metadata,
List<ArtifactRepository> remoteRepositories,
ArtifactRepository localRepository )
public void resolve( RepositoryMetadata metadata, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository )
throws RepositoryMetadataResolutionException
{
for (ArtifactRepository repository : remoteRepositories) {
ArtifactRepositoryPolicy policy =
metadata.isSnapshot() ? repository.getSnapshots() : repository.getReleases();
for ( ArtifactRepository repository : remoteRepositories )
{
ArtifactRepositoryPolicy policy = metadata.isSnapshot() ? repository.getSnapshots() : repository.getReleases();
File file = new File(localRepository.getBasedir(),
localRepository.pathOfLocalRepositoryMetadata(metadata, repository));
File file = new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( metadata, repository ) );
if (wagonManager.isOnline()) {
if (updateCheckManager.isUpdateRequired(metadata, repository, file)) {
getLogger().info(metadata.getKey() + ": checking for updates from " + repository.getId());
try {
wagonManager.getArtifactMetadata(metadata, repository, file, policy.getChecksumPolicy());
if ( updateCheckManager.isUpdateRequired( metadata, repository, file ) )
{
getLogger().info( metadata.getKey() + ": checking for updates from " + repository.getId() );
try
{
wagonManager.getArtifactMetadata( metadata, repository, file, policy.getChecksumPolicy() );
}
catch (ResourceDoesNotExistException e) {
getLogger().debug(metadata + " could not be found on repository: " + repository.getId());
catch ( ResourceDoesNotExistException e )
{
getLogger().debug( metadata + " could not be found on repository: " + repository.getId() );
// delete the local copy so the old details aren't used.
if (file.exists()) {
if ( file.exists() )
{
file.delete();
}
}
catch (TransferFailedException e) {
getLogger().warn(metadata + " could not be retrieved from repository: " + repository.getId() +
" due to an error: " + e.getMessage());
getLogger().debug("Exception", e);
catch ( TransferFailedException e )
{
getLogger().warn( metadata + " could not be retrieved from repository: " + repository.getId() + " due to an error: " + e.getMessage() );
getLogger().debug( "Exception", e );
getLogger().info("Repository '" + repository.getId() + "' will be blacklisted");
repository.setBlacklisted(true);
getLogger().info( "Repository '" + repository.getId() + "' will be blacklisted" );
repository.setBlacklisted( true );
// TODO: [jc; 08-Nov-2005] revisit this for 2.1
// suppressing logging to avoid logging this error twice.
}
finally {
updateCheckManager.touch(metadata, repository, file);
finally
{
updateCheckManager.touch( metadata, repository, file );
}
}
} else {
getLogger().debug(
"System is offline. Cannot resolve metadata:\n" + metadata.extendedToString() + "\n\n");
else
{
getLogger().debug( "System is offline. Cannot resolve metadata:\n" + metadata.extendedToString() + "\n\n" );
}
// TODO: should this be inside the above check?
// touch file so that this is not checked again until interval has passed
if (file.exists()) {
file.setLastModified(System.currentTimeMillis());
if ( file.exists() )
{
file.setLastModified( System.currentTimeMillis() );
}
}
try
{
mergeMetadata( metadata, remoteRepositories, localRepository );
}
catch ( RepositoryMetadataStoreException e )
{
throw new RepositoryMetadataResolutionException(
"Unable to store local copy of metadata: " + e.getMessage(), e );
throw new RepositoryMetadataResolutionException( "Unable to store local copy of metadata: " + e.getMessage(), e );
}
catch ( RepositoryMetadataReadException e )
{
throw new RepositoryMetadataResolutionException( "Unable to read local copy of metadata: " + e.getMessage(),
e );
throw new RepositoryMetadataResolutionException( "Unable to read local copy of metadata: " + e.getMessage(), e );
}
}
private void mergeMetadata( RepositoryMetadata metadata,
List<ArtifactRepository> remoteRepositories,
ArtifactRepository localRepository )
private void mergeMetadata( RepositoryMetadata metadata, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository )
throws RepositoryMetadataStoreException, RepositoryMetadataReadException
{
// TODO: currently this is first wins, but really we should take the latest by comparing either the
@ -146,15 +141,15 @@ public class DefaultRepositoryMetadataManager
// TODO: this needs to be repeated here so the merging doesn't interfere with the written metadata
// - we'd be much better having a pristine input, and an ongoing metadata for merging instead
Map<ArtifactRepository,Metadata> previousMetadata = new HashMap<ArtifactRepository,Metadata>();
Map<ArtifactRepository, Metadata> previousMetadata = new HashMap<ArtifactRepository, Metadata>();
ArtifactRepository selected = null;
for (ArtifactRepository repository : remoteRepositories) {
ArtifactRepositoryPolicy policy =
metadata.isSnapshot() ? repository.getSnapshots() : repository.getReleases();
for ( ArtifactRepository repository : remoteRepositories )
{
ArtifactRepositoryPolicy policy = metadata.isSnapshot() ? repository.getSnapshots() : repository.getReleases();
if ((policy.isEnabled() && !repository.isBlacklisted())
&& (loadMetadata(metadata, repository, localRepository, previousMetadata))) {
metadata.setRepository(repository);
if ( ( policy.isEnabled() && !repository.isBlacklisted() ) && ( loadMetadata( metadata, repository, localRepository, previousMetadata ) ) )
{
metadata.setRepository( repository );
selected = repository;
}
}
@ -167,10 +162,7 @@ public class DefaultRepositoryMetadataManager
updateSnapshotMetadata( metadata, previousMetadata, selected, localRepository );
}
private void updateSnapshotMetadata( RepositoryMetadata metadata,
Map<ArtifactRepository,Metadata> previousMetadata,
ArtifactRepository selected,
ArtifactRepository localRepository )
private void updateSnapshotMetadata( RepositoryMetadata metadata, Map<ArtifactRepository, Metadata> previousMetadata, ArtifactRepository selected, ArtifactRepository localRepository )
throws RepositoryMetadataStoreException
{
// TODO: this could be a lot nicer... should really be in the snapshot transformation?
@ -178,22 +170,28 @@ public class DefaultRepositoryMetadataManager
{
Metadata prevMetadata = metadata.getMetadata();
for (ArtifactRepository repository : previousMetadata.keySet()) {
Metadata m = previousMetadata.get(repository);
if (repository.equals(selected)) {
if (m.getVersioning() == null) {
m.setVersioning(new Versioning());
for ( ArtifactRepository repository : previousMetadata.keySet() )
{
Metadata m = previousMetadata.get( repository );
if ( repository.equals( selected ) )
{
if ( m.getVersioning() == null )
{
m.setVersioning( new Versioning() );
}
if (m.getVersioning().getSnapshot() == null) {
m.getVersioning().setSnapshot(new Snapshot());
if ( m.getVersioning().getSnapshot() == null )
{
m.getVersioning().setSnapshot( new Snapshot() );
}
} else {
if ((m.getVersioning() != null) && (m.getVersioning().getSnapshot() != null) &&
m.getVersioning().getSnapshot().isLocalCopy()) {
m.getVersioning().getSnapshot().setLocalCopy(false);
metadata.setMetadata(m);
metadata.storeInLocalRepository(localRepository, repository);
}
else
{
if ( ( m.getVersioning() != null ) && ( m.getVersioning().getSnapshot() != null ) && m.getVersioning().getSnapshot().isLocalCopy() )
{
m.getVersioning().getSnapshot().setLocalCopy( false );
metadata.setMetadata( m );
metadata.storeInLocalRepository( localRepository, repository );
}
}
}
@ -202,16 +200,12 @@ public class DefaultRepositoryMetadataManager
}
}
private boolean loadMetadata( RepositoryMetadata repoMetadata,
ArtifactRepository remoteRepository,
ArtifactRepository localRepository,
Map<ArtifactRepository,Metadata> previousMetadata )
private boolean loadMetadata( RepositoryMetadata repoMetadata, ArtifactRepository remoteRepository, ArtifactRepository localRepository, Map<ArtifactRepository, Metadata> previousMetadata )
throws RepositoryMetadataReadException
{
boolean setRepository = false;
File metadataFile = new File( localRepository.getBasedir(),
localRepository.pathOfLocalRepositoryMetadata( repoMetadata, remoteRepository ) );
File metadataFile = new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( repoMetadata, remoteRepository ) );
if ( metadataFile.exists() )
{
@ -256,13 +250,11 @@ public class DefaultRepositoryMetadataManager
}
catch ( IOException e )
{
throw new RepositoryMetadataReadException(
"Cannot read metadata from '" + mappingFile + "': " + e.getMessage(), e );
throw new RepositoryMetadataReadException( "Cannot read metadata from '" + mappingFile + "': " + e.getMessage(), e );
}
catch ( XmlPullParserException e )
{
throw new RepositoryMetadataReadException(
"Cannot read metadata from '" + mappingFile + "': " + e.getMessage(), e );
throw new RepositoryMetadataReadException( "Cannot read metadata from '" + mappingFile + "': " + e.getMessage(), e );
}
finally
{
@ -271,18 +263,9 @@ public class DefaultRepositoryMetadataManager
return result;
}
public void resolveAlways( RepositoryMetadata metadata,
ArtifactRepository localRepository,
ArtifactRepository remoteRepository )
public void resolveAlways( RepositoryMetadata metadata, ArtifactRepository localRepository, ArtifactRepository remoteRepository )
throws RepositoryMetadataResolutionException
{
if ( !wagonManager.isOnline() )
{
// metadata is required for deployment, can't be offline
throw new RepositoryMetadataResolutionException(
"System is offline. Cannot resolve required metadata:\n" + metadata.extendedToString() );
}
File file;
try
{
@ -290,8 +273,7 @@ public class DefaultRepositoryMetadataManager
}
catch ( TransferFailedException e )
{
throw new RepositoryMetadataResolutionException( metadata + " could not be retrieved from repository: " +
remoteRepository.getId() + " due to an error: " + e.getMessage(), e );
throw new RepositoryMetadataResolutionException( metadata + " could not be retrieved from repository: " + remoteRepository.getId() + " due to an error: " + e.getMessage(), e );
}
try
@ -308,23 +290,18 @@ public class DefaultRepositoryMetadataManager
}
}
private File getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata,
ArtifactRepository localRepository,
ArtifactRepository remoteRepository )
private File getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata, ArtifactRepository localRepository, ArtifactRepository remoteRepository )
throws TransferFailedException
{
File file = new File( localRepository.getBasedir(),
localRepository.pathOfLocalRepositoryMetadata( metadata, remoteRepository ) );
File file = new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( metadata, remoteRepository ) );
try
{
wagonManager.getArtifactMetadataFromDeploymentRepository( metadata, remoteRepository, file,
ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN );
wagonManager.getArtifactMetadataFromDeploymentRepository( metadata, remoteRepository, file, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN );
}
catch ( ResourceDoesNotExistException e )
{
getLogger().info(
metadata + " could not be found on repository: " + remoteRepository.getId() + ", so will be created" );
getLogger().info( metadata + " could not be found on repository: " + remoteRepository.getId() + ", so will be created" );
// delete the local copy so the old details aren't used.
if ( file.exists() )
@ -342,18 +319,9 @@ public class DefaultRepositoryMetadataManager
return file;
}
public void deploy( ArtifactMetadata metadata,
ArtifactRepository localRepository,
ArtifactRepository deploymentRepository )
public void deploy( ArtifactMetadata metadata, ArtifactRepository localRepository, ArtifactRepository deploymentRepository )
throws RepositoryMetadataDeploymentException
{
if ( !wagonManager.isOnline() )
{
// deployment shouldn't silently fail when offline
throw new RepositoryMetadataDeploymentException(
"System is offline. Cannot deploy metadata:\n" + metadata.extendedToString() );
}
File file;
if ( metadata instanceof RepositoryMetadata )
{
@ -364,16 +332,13 @@ public class DefaultRepositoryMetadataManager
}
catch ( TransferFailedException e )
{
throw new RepositoryMetadataDeploymentException( metadata +
" could not be retrieved from repository: " + deploymentRepository.getId() + " due to an error: " +
e.getMessage(), e );
throw new RepositoryMetadataDeploymentException( metadata + " could not be retrieved from repository: " + deploymentRepository.getId() + " due to an error: " + e.getMessage(), e );
}
}
else
{
// It's a POM - we don't need to retrieve it first
file = new File( localRepository.getBasedir(),
localRepository.pathOfLocalRepositoryMetadata( metadata, deploymentRepository ) );
file = new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( metadata, deploymentRepository ) );
}
try
@ -395,8 +360,7 @@ public class DefaultRepositoryMetadataManager
}
}
public void install( ArtifactMetadata metadata,
ArtifactRepository localRepository )
public void install( ArtifactMetadata metadata, ArtifactRepository localRepository )
throws RepositoryMetadataInstallationException
{
try

View File

@ -1,24 +1,28 @@
package org.apache.maven.artifact.resolver;
/*
* 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
* 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.
* 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.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.manager.WagonManager;
@ -29,8 +33,8 @@ import org.apache.maven.artifact.repository.metadata.Metadata;
import org.apache.maven.artifact.repository.metadata.Snapshot;
import org.apache.maven.artifact.repository.metadata.SnapshotArtifactRepositoryMetadata;
import org.apache.maven.artifact.repository.metadata.Versioning;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.conflict.ConflictResolver;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.transform.ArtifactTransformationManager;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
@ -39,16 +43,6 @@ import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Jason van Zyl
*/
@ -77,15 +71,13 @@ public class DefaultArtifactResolver
// Implementation
// ----------------------------------------------------------------------
public void resolve( Artifact artifact, List<ArtifactRepository> remoteRepositories,
ArtifactRepository localRepository )
public void resolve( Artifact artifact, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
resolve( artifact, remoteRepositories, localRepository, false );
}
public void resolveAlways( Artifact artifact, List<ArtifactRepository> remoteRepositories,
ArtifactRepository localRepository )
public void resolveAlways( Artifact artifact, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
resolve( artifact, remoteRepositories, localRepository, true );
@ -100,6 +92,7 @@ public class DefaultArtifactResolver
return;
}
File destination;
if ( Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) )
{
File systemFile = artifact.getFile();
@ -139,23 +132,17 @@ public class DefaultArtifactResolver
boolean localCopy = isLocalCopy( artifact );
File destination = artifact.getFile();
destination = artifact.getFile();
boolean resolved = false;
if ( !wagonManager.isOnline() )
{
if ( !destination.exists() )
{
throw new ArtifactNotFoundException( "System is offline.", artifact );
}
}
// There are three conditions in which we'll go after the artifact here:
// 1. the force flag is set.
// 2. the artifact's file doesn't exist (this would be true for release or snapshot artifacts)
// 3. the artifact is a snapshot and is not a locally installed snapshot
// TODO: Should it matter whether it's a locally installed snapshot??
else if ( force || !destination.exists() || ( artifact.isSnapshot() && !localCopy ) )
if ( force || !destination.exists() || ( artifact.isSnapshot() && !localCopy ) )
{
try
{
@ -173,18 +160,16 @@ public class DefaultArtifactResolver
{
throw new ArtifactResolutionException(
"Failed to resolve artifact, possibly due to a repository list that is not appropriately equipped for this artifact's metadata.",
artifact, getMirroredRepositories( remoteRepositories ) );
artifact, remoteRepositories );
}
}
catch ( ResourceDoesNotExistException e )
{
throw new ArtifactNotFoundException( e.getMessage(), artifact,
getMirroredRepositories( remoteRepositories ), e );
throw new ArtifactNotFoundException( e.getMessage(), artifact, remoteRepositories, e );
}
catch ( TransferFailedException e )
{
throw new ArtifactResolutionException( e.getMessage(), artifact,
getMirroredRepositories( remoteRepositories ), e );
throw new ArtifactResolutionException( e.getMessage(), artifact, remoteRepositories, e );
}
resolved = true;
@ -216,7 +201,7 @@ public class DefaultArtifactResolver
catch ( IOException e )
{
throw new ArtifactResolutionException( "Unable to copy resolved artifact for local use: "
+ e.getMessage(), artifact, getMirroredRepositories( remoteRepositories ), e );
+ e.getMessage(), artifact, remoteRepositories, e );
}
}
@ -229,7 +214,6 @@ public class DefaultArtifactResolver
private boolean isLocalCopy( Artifact artifact )
{
boolean localCopy = false;
for ( ArtifactMetadata m : artifact.getMetadataList() )
@ -261,51 +245,37 @@ public class DefaultArtifactResolver
return localCopy;
}
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact,
ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories,
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories,
ArtifactMetadataSource source, ArtifactFilter filter )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return resolveTransitively( artifacts, originatingArtifact, Collections.EMPTY_MAP, localRepository,
remoteRepositories, source, filter );
return resolveTransitively( artifacts, originatingArtifact, Collections.EMPTY_MAP, localRepository, remoteRepositories, source, filter );
}
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories,
ArtifactMetadataSource source )
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact, Map managedVersions, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories, ArtifactMetadataSource source )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository,
remoteRepositories, source, null );
return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository, remoteRepositories, source, null );
}
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories,
ArtifactMetadataSource source, ArtifactFilter filter )
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact, Map managedVersions, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories, ArtifactMetadataSource source, ArtifactFilter filter )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository,
remoteRepositories, source, filter, null );
return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository, remoteRepositories, source, filter, null );
}
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact,
List<ArtifactRepository> remoteRepositories,
ArtifactRepository localRepository,
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository,
ArtifactMetadataSource source )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return resolveTransitively( artifacts, originatingArtifact, localRepository, remoteRepositories, source, null );
}
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact,
List<ArtifactRepository> remoteRepositories,
ArtifactRepository localRepository,
ArtifactMetadataSource source,
List<ResolutionListener> listeners )
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository,
ArtifactMetadataSource source, List<ResolutionListener> listeners )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return resolveTransitively( artifacts, originatingArtifact,
@ -313,22 +283,15 @@ public class DefaultArtifactResolver
Collections.EMPTY_MAP, localRepository, remoteRepositories, source, null, listeners );
}
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories,
ArtifactMetadataSource source, ArtifactFilter filter,
List<ResolutionListener> listeners )
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact, Map managedVersions, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories, ArtifactMetadataSource source, ArtifactFilter filter, List<ResolutionListener> listeners )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository,
remoteRepositories, source, filter, listeners, null );
return resolveTransitively( artifacts, originatingArtifact, managedVersions, localRepository, remoteRepositories, source, filter, listeners, null );
}
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories,
ArtifactMetadataSource source, ArtifactFilter filter,
List<ResolutionListener> listeners,
public ArtifactResolutionResult resolveTransitively( Set<Artifact> artifacts, Artifact originatingArtifact, Map managedVersions, ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepositories, ArtifactMetadataSource source, ArtifactFilter filter, List<ResolutionListener> listeners,
List<ConflictResolver> conflictResolvers )
throws ArtifactResolutionException, ArtifactNotFoundException
{
@ -346,9 +309,7 @@ public class DefaultArtifactResolver
ArtifactResolutionResult result;
result =
artifactCollector.collect( artifacts, originatingArtifact, managedVersions, localRepository,
remoteRepositories, source, filter, listeners, conflictResolvers );
result = artifactCollector.collect( artifacts, originatingArtifact, managedVersions, localRepository, remoteRepositories, source, filter, listeners, conflictResolvers );
// We have collected all the problems so let's mimic the way the old code worked and just blow up right here.
// That's right lets just let it rip right here and send a big incomprehensible blob of text at unsuspecting
@ -399,26 +360,12 @@ public class DefaultArtifactResolver
if ( missingArtifacts.size() > 0 )
{
throw new MultipleArtifactsNotFoundException( originatingArtifact, resolvedArtifacts, missingArtifacts,
getMirroredRepositories( remoteRepositories ) );
throw new MultipleArtifactsNotFoundException( originatingArtifact, resolvedArtifacts, missingArtifacts, remoteRepositories );
}
return result;
}
private List<ArtifactRepository> getMirroredRepositories( List<ArtifactRepository> remoteRepositories )
{
Map<String, ArtifactRepository> repos = new HashMap<String, ArtifactRepository>();
for ( ArtifactRepository repository : remoteRepositories )
{
ArtifactRepository repo = wagonManager.getMirrorRepository( repository );
repos.put( repo.getId(), repo );
}
return new ArrayList<ArtifactRepository>( repos.values() );
}
// ------------------------------------------------------------------------
//
// ------------------------------------------------------------------------
@ -444,8 +391,8 @@ public class DefaultArtifactResolver
// This is an attempt to get the metadata for the artifacts we are ultimately trying to resolve.
// We still
ArtifactResolutionResult result =
artifactCollector.collect( artifacts, originatingArtifact, managedVersions, localRepository,
ArtifactResolutionResult result = artifactCollector.collect( artifacts, originatingArtifact,
managedVersions, localRepository,
remoteRepositories, source, filter, listeners );
// Let's grab all the repositories that were gleaned. This we should know up front. I'm not sure

View File

@ -158,13 +158,6 @@ public class SnapshotTransformation
{
RepositoryMetadata metadata = new SnapshotArtifactRepositoryMetadata( artifact );
if ( !wagonManager.isOnline() )
{
// build number is a required feature for metadata consistency
throw new RepositoryMetadataResolutionException(
"System is offline. Cannot resolve metadata:\n" + metadata.extendedToString() + "\n\n" );
}
getLogger().info( "Retrieving previous build number from " + remoteRepository.getId() );
repositoryMetadataManager.resolveAlways( metadata, localRepository, remoteRepository );

View File

@ -91,130 +91,11 @@ public class DefaultWagonManagerTest
}
};
TransferListener listener = new TransferListener();
wagonManager.setDownloadMonitor(listener);
wagonManager.getArtifact( artifact, repos, false );
assertEquals(1, listener.events.size());
}
public void testGetMissingPomUncached() throws TransferFailedException, UnsupportedProtocolException, IOException
{
Artifact artifact = createTestPomArtifact( "target/test-data/get-missing-pom" );
ArtifactRepository repo = createStringRepo();
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
updateCheckManager.isPomUpdateRequired( artifact, repo );
control.setReturnValue( true );
updateCheckManager.touch( artifact, repo );
control.replay();
try
{
wagonManager.getArtifact( artifact, repo, false );
fail();
}
catch ( ResourceDoesNotExistException e )
{
assertTrue( true );
}
assertFalse( artifact.getFile().exists() );
control.verify();
}
public void testGetMissingPomCached() throws TransferFailedException, UnsupportedProtocolException, IOException
{
Artifact artifact = createTestPomArtifact( "target/test-data/get-missing-pom" );
ArtifactRepository repo = createStringRepo();
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
updateCheckManager.isPomUpdateRequired( artifact, repo );
control.setReturnValue( false );
control.replay();
try
{
wagonManager.getArtifact( artifact, repo, false );
fail();
}
catch ( ResourceDoesNotExistException e )
{
assertTrue( true );
}
assertFalse( artifact.getFile().exists() );
control.verify();
}
public void testGetMissingPomCachedForced() throws TransferFailedException, UnsupportedProtocolException, IOException
{
Artifact artifact = createTestPomArtifact( "target/test-data/get-missing-pom" );
ArtifactRepository repo = createStringRepo();
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
updateCheckManager.touch( artifact, repo );
control.replay();
try
{
wagonManager.getArtifact( artifact, repo, true );
fail();
}
catch ( ResourceDoesNotExistException e )
{
assertTrue( true );
}
assertFalse( artifact.getFile().exists() );
control.verify();
}
public void testGetRemotePom()
throws TransferFailedException, ResourceDoesNotExistException, UnsupportedProtocolException, IOException,
AuthorizationException
{
Artifact artifact = createTestPomArtifact( "target/test-data/get-remote-pom" );
ArtifactRepository repo = createStringRepo();
StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" );
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
updateCheckManager.isPomUpdateRequired( artifact, repo );
control.setReturnValue( true );
control.replay();
wagonManager.getArtifact( artifact, repo, false );
assertTrue( artifact.getFile().exists() );
assertEquals( "expected", FileUtils.fileRead( artifact.getFile(), "UTF-8" ) );
control.verify();
}
public void testGetPomExistsLocallyForced()
throws IOException, TransferFailedException, ResourceDoesNotExistException, UnsupportedProtocolException
{
@ -229,7 +110,6 @@ public class DefaultWagonManagerTest
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
control.replay();
@ -294,7 +174,6 @@ public class DefaultWagonManagerTest
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
control.replay();
@ -320,125 +199,6 @@ public class DefaultWagonManagerTest
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
control.replay();
wagonManager.getArtifact( artifact, repo, true );
assertTrue( artifact.getFile().exists() );
assertEquals( "expected", FileUtils.fileRead( artifact.getFile(), "UTF-8" ) );
control.verify();
}
public void testGetRemoteSnapshotJar()
throws TransferFailedException, ResourceDoesNotExistException, UnsupportedProtocolException, IOException,
AuthorizationException
{
Artifact artifact = createTestArtifact( "target/test-data/get-remote-jar", "1.0-SNAPSHOT", "jar" );
ArtifactRepository repo = createStringRepo();
StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" );
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
updateCheckManager.isUpdateRequired( artifact, repo );
control.setReturnValue( true );
updateCheckManager.touch( artifact, repo );
control.replay();
wagonManager.getArtifact( artifact, repo, false );
assertTrue( artifact.getFile().exists() );
assertEquals( "expected", FileUtils.fileRead( artifact.getFile(), "UTF-8" ) );
control.verify();
}
public void testGetSnapshotJarExistsLocally()
throws IOException, TransferFailedException, ResourceDoesNotExistException, UnsupportedProtocolException
{
Artifact artifact = createTestArtifact( "target/test-data/get-remote-jar", "1.0-SNAPSHOT", "jar" );
artifact.getFile().createNewFile();
artifact.getFile().setLastModified( System.currentTimeMillis() - 60 * 1000 );
ArtifactRepository repo = createStringRepo();
StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" );
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
updateCheckManager.isUpdateRequired( artifact, repo );
control.setReturnValue( false );
control.replay();
wagonManager.getArtifact( artifact, repo, false );
assertTrue( artifact.getFile().exists() );
assertEquals( "", FileUtils.fileRead( artifact.getFile(), "UTF-8" ) );
control.verify();
}
public void testGetSnapshotJarExistsLocallyExpired()
throws IOException, TransferFailedException, ResourceDoesNotExistException, UnsupportedProtocolException
{
Artifact artifact = createTestArtifact( "target/test-data/get-remote-jar", "1.0-SNAPSHOT", "jar" );
artifact.getFile().createNewFile();
artifact.getFile().setLastModified( System.currentTimeMillis() - 60 * 1000 );
ArtifactRepository repo = createStringRepo();
StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" );
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
updateCheckManager.isUpdateRequired( artifact, repo );
control.setReturnValue( true );
updateCheckManager.touch( artifact, repo );
control.replay();
wagonManager.getArtifact( artifact, repo, false );
assertTrue( artifact.getFile().exists() );
assertEquals( "expected", FileUtils.fileRead( artifact.getFile(), "UTF-8" ) );
control.verify();
}
public void testGetSnapshotJarExistsLocallyForced()
throws IOException, TransferFailedException, ResourceDoesNotExistException, UnsupportedProtocolException
{
Artifact artifact = createTestArtifact( "target/test-data/get-remote-jar", "1.0-SNAPSHOT", "jar" );
artifact.getFile().createNewFile();
artifact.getFile().setLastModified( System.currentTimeMillis() - 60 * 1000 );
ArtifactRepository repo = createStringRepo();
StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" );
MockControl control = MockControl.createControl( UpdateCheckManager.class );
UpdateCheckManager updateCheckManager = (UpdateCheckManager) control.getMock();
wagonManager.setUpdateCheckManager( updateCheckManager );
updateCheckManager.touch( artifact, repo );
control.replay();
@ -482,27 +242,6 @@ public class DefaultWagonManagerTest
return artifact;
}
public void testAddMirrorWithNullRepositoryId()
{
wagonManager.addMirror( null, "test", "http://www.nowhere.com/" );
}
public void testGetArtifactSha1MissingMd5Present()
throws IOException, UnsupportedProtocolException, TransferFailedException, ResourceDoesNotExistException
{
Artifact artifact = createTestPomArtifact( "target/test-data/get-remote-artifact" );
ArtifactRepository repo = createStringRepo();
StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ) + ".md5", "bad_checksum" );
wagonManager.getArtifact( artifact, repo, true );
assertTrue( artifact.getFile().exists() );
}
private ArtifactRepository createStringRepo()
{
ArtifactRepository repo =
@ -510,174 +249,6 @@ public class DefaultWagonManagerTest
return repo;
}
/**
* checks the handling of urls
*/
public void testExternalURL()
{
DefaultWagonManager mgr = new DefaultWagonManager();
assertTrue( mgr.isExternalRepo( getRepo( "foo", "http://somehost" ) ) );
assertTrue( mgr.isExternalRepo( getRepo( "foo", "http://somehost:9090/somepath" ) ) );
assertTrue( mgr.isExternalRepo( getRepo( "foo", "ftp://somehost" ) ) );
assertTrue( mgr.isExternalRepo( getRepo( "foo", "http://192.168.101.1" ) ) );
assertTrue( mgr.isExternalRepo( getRepo( "foo", "http://" ) ) );
// these are local
assertFalse( mgr.isExternalRepo( getRepo( "foo", "http://localhost:8080" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "http://127.0.0.1:9090" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "file://localhost/somepath" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "file://localhost/D:/somepath" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "http://localhost" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "http://127.0.0.1" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "file:///somepath" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "file://D:/somepath" ) ) );
// not a proper url so returns false;
assertFalse( mgr.isExternalRepo( getRepo( "foo", "192.168.101.1" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "" ) ) );
}
/**
* Check that lookups with exact matches work and that no matches don't corrupt the repo.
*/
public void testMirrorLookup()
{
wagonManager.addMirror( "a", "a", "http://a" );
wagonManager.addMirror( "b", "b", "http://b" );
ArtifactRepository repo = null;
repo = wagonManager.getMirrorRepository( getRepo( "a", "http://a.a" ) );
assertEquals( "http://a", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "b", "http://a.a" ) );
assertEquals( "http://b", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "c", "http://c.c" ) );
assertEquals( "http://c.c", repo.getUrl() );
}
/**
* Check that wildcards don't override exact id matches.
*/
public void testMirrorWildcardLookup()
{
wagonManager.addMirror( "a", "a", "http://a" );
wagonManager.addMirror( "b", "b", "http://b" );
wagonManager.addMirror( "c", "*", "http://wildcard" );
ArtifactRepository repo = null;
repo = wagonManager.getMirrorRepository( getRepo( "a", "http://a.a" ) );
assertEquals( "http://a", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "b", "http://a.a" ) );
assertEquals( "http://b", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "c", "http://c.c" ) );
assertEquals( "http://wildcard", repo.getUrl() );
}
/**
* Check that first match wins
*/
public void testMirrorStopOnFirstMatch()
{
//exact matches win first
wagonManager.addMirror( "a2", "a,b", "http://a2" );
wagonManager.addMirror( "a", "a", "http://a" );
//make sure repeated entries are skipped
wagonManager.addMirror( "a", "a", "http://a3" );
wagonManager.addMirror( "b", "b", "http://b" );
wagonManager.addMirror( "c", "d,e", "http://de" );
wagonManager.addMirror( "c", "*", "http://wildcard" );
wagonManager.addMirror( "c", "e,f", "http://ef" );
ArtifactRepository repo = null;
repo = wagonManager.getMirrorRepository( getRepo( "a", "http://a.a" ) );
assertEquals( "http://a", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "b", "http://a.a" ) );
assertEquals( "http://b", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "c", "http://c.c" ) );
assertEquals( "http://wildcard", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "d", "http://d" ) );
assertEquals( "http://de", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "e", "http://e" ) );
assertEquals( "http://de", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "f", "http://f" ) );
assertEquals( "http://wildcard", repo.getUrl() );
}
/**
* Check that patterns are processed correctly Valid patterns: * = everything external:* = everything not on the
* localhost and not file based. repo,repo1 = repo or repo1 *,!repo1 = everything except repo1
*/
public void testPatterns()
{
DefaultWagonManager mgr = new DefaultWagonManager();
assertTrue( mgr.matchPattern( getRepo( "a" ), "*" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), ",*," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "a" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "a," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), ",a," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "a," ) );
assertFalse( mgr.matchPattern( getRepo( "b" ), "a" ) );
assertFalse( mgr.matchPattern( getRepo( "b" ), "a," ) );
assertFalse( mgr.matchPattern( getRepo( "b" ), ",a" ) );
assertFalse( mgr.matchPattern( getRepo( "b" ), ",a," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "a,b" ) );
assertTrue( mgr.matchPattern( getRepo( "b" ), "a,b" ) );
assertFalse( mgr.matchPattern( getRepo( "c" ), "a,b" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*,b" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*,!b" ) );
assertFalse( mgr.matchPattern( getRepo( "a" ), "*,!a" ) );
assertFalse( mgr.matchPattern( getRepo( "a" ), "!a,*" ) );
assertTrue( mgr.matchPattern( getRepo( "c" ), "*,!a" ) );
assertTrue( mgr.matchPattern( getRepo( "c" ), "!a,*" ) );
assertFalse( mgr.matchPattern( getRepo( "c" ), "!a,!c" ) );
assertFalse( mgr.matchPattern( getRepo( "d" ), "!a,!c*" ) );
}
/**
* make sure the external if is fully exercised. We can assume file and ips are also handled because they have a
* separate test above.
*/
public void testPatternsWithExternal()
{
DefaultWagonManager mgr = new DefaultWagonManager();
assertTrue( mgr.matchPattern( getRepo( "a", "http://localhost" ), "*" ) );
assertFalse( mgr.matchPattern( getRepo( "a", "http://localhost" ), "external:*" ) );
assertTrue( mgr.matchPattern( getRepo( "a", "http://localhost" ), "external:*,a" ) );
assertFalse( mgr.matchPattern( getRepo( "a", "http://localhost" ), "external:*,!a" ) );
assertTrue( mgr.matchPattern( getRepo( "a", "http://localhost" ), "a,external:*" ) );
assertFalse( mgr.matchPattern( getRepo( "a", "http://localhost" ), "!a,external:*" ) );
assertFalse( mgr.matchPattern( getRepo( "c", "http://localhost" ), "!a,external:*" ) );
assertTrue( mgr.matchPattern( getRepo( "c", "http://somehost" ), "!a,external:*" ) );
}
/**
* Build an ArtifactRepository object.
@ -728,30 +299,6 @@ public class DefaultWagonManagerTest
}
}
public void testGetWagonRepository()
throws Exception
{
assertWagonRepository( "a" );
assertWagonRepository( "b1" );
assertWagonRepository( "b2" );
assertWagonRepository( "c" );
try
{
assertWagonRepository( "d" );
fail( "Expected :" + UnsupportedProtocolException.class.getName() );
}
catch ( UnsupportedProtocolException e )
{
// ok
assertTrue( true );
}
}
public void testGetWagonRepositoryNullProtocol()
throws Exception
{
@ -772,21 +319,6 @@ public class DefaultWagonManagerTest
}
}
/**
* Checks that lookup by protocol/scheme is case-insensitive as suggested by RFC 2396, "3.1. Scheme Component".
*/
public void testGetWagonCaseInsensitive()
throws Exception
{
assertWagon( "a" );
assertWagon( "A" );
assertWagonRepository( "a" );
assertWagonRepository( "A" );
}
/**
* Check that transfer listeners are properly removed after getArtifact and putArtifact
*/
@ -945,8 +477,6 @@ public class DefaultWagonManagerTest
conf.addChild( configurableField );
wagonManager.addConfiguration( repository.getId(), conf );
WagonMock wagon = (WagonMock) wagonManager.getWagon( repository );
assertNotNull( "Check wagon, protocol=" + protocol, wagon );

View File

@ -1,94 +0,0 @@
package org.apache.maven.artifact.repository;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.UnknownRepositoryLayoutException;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.codehaus.plexus.PlexusTestCase;
import org.codehaus.plexus.util.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class DefaultArtifactRepositoryFactoryTest
extends PlexusTestCase
{
private ArtifactRepositoryFactory repoFactory;
private Set<File> toDelete = new HashSet<File>();
public void setUp()
throws Exception
{
super.setUp();
repoFactory = (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.ROLE );
}
public void tearDown()
throws Exception
{
for ( File f : toDelete )
{
if ( f.exists() )
{
FileUtils.forceDelete( f );
}
}
}
private File createTempDir()
throws IOException
{
File f = File.createTempFile( "DefaultArtifactRepositoryFactoryTest.", ".dir" );
FileUtils.forceDelete( f );
f.mkdirs();
toDelete.add( f );
return f;
}
public void test_createLocalRepository()
throws IOException, InvalidRepositoryException
{
File dir = createTempDir();
ArtifactRepository localRepo = repoFactory.createLocalRepository( dir );
assertEquals( dir.getAbsolutePath(), localRepo.getBasedir() );
assertEquals( ArtifactRepositoryFactory.LOCAL_REPOSITORY_ID, localRepo.getId() );
assertTrue( localRepo.getLayout() instanceof DefaultRepositoryLayout );
}
public void test_getLayout_ReturnDefaultLayout()
throws UnknownRepositoryLayoutException
{
ArtifactRepositoryLayout layout = repoFactory.getLayout( "default" );
assertTrue( layout instanceof DefaultRepositoryLayout );
}
public void testRetrievalOfKnownRepositoryLayouts()
throws Exception
{
ArtifactRepositoryLayout defaultLayout = repoFactory.getLayout( "default" );
assertNotNull( defaultLayout );
ArtifactRepositoryLayout legacyLayout = repoFactory.getLayout( "legacy" );
assertNotNull( legacyLayout );
ArtifactRepositoryLayout flatLayout = repoFactory.getLayout( "flat" );
assertNotNull( flatLayout );
}
public void testCreationOfDeploymentRepository()
throws Exception
{
ArtifactRepository repository = repoFactory.createDeploymentArtifactRepository( "id", "file:///tmp/repo", "default", false );
assertNotNull( repository );
assertNotNull( repository.getLayout() );
assertEquals( "id", repository.getId() );
}
}

View File

@ -1,180 +0,0 @@
package org.apache.maven.artifact.repository.metadata;
/*
* 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 junit.framework.TestCase;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.testutils.MockManager;
import org.apache.maven.artifact.testutils.TestFileManager;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.easymock.MockControl;
import java.io.File;
import java.io.IOException;
public class AbstractRepositoryMetadataTest
extends TestCase
{
private MockManager mm = new MockManager();
private TestFileManager fileManager = new TestFileManager( "AbstractRepositoryMetadataTest.test.", "" );
public void tearDown() throws IOException
{
fileManager.cleanUp();
}
public void testUpdateRepositoryMetadata_NoVersionTagIfMainVersionIsLATEST()
throws IOException, XmlPullParserException
{
MockAndControlForArtifactRepository local = new MockAndControlForArtifactRepository();
MockAndControlForArtifactRepository remote = new MockAndControlForArtifactRepository();
File basedir = fileManager.createTempDir();
String path = "metadata.xml";
Metadata m = new Metadata();
m.setVersion( Artifact.LATEST_VERSION );
TestRepoMetadata trm = new TestRepoMetadata( m );
local.expectGetBasedir( basedir );
local.expectPathOfLocalRepositoryMetadata( trm, remote.repository, path );
mm.replayAll();
trm.updateRepositoryMetadata( local.repository, remote.repository );
fileManager.assertFileExistence( basedir, path, true );
assertTrue( fileManager.getFileContents( new File( basedir, path ), "UTF-8" ).indexOf( "<version>"
+ Artifact.LATEST_VERSION + "</version>" ) < 0 );
mm.verifyAll();
}
public void testUpdateRepositoryMetadata_NoVersionTagIfVersionIsRELEASE()
throws IOException, XmlPullParserException
{
MockAndControlForArtifactRepository local = new MockAndControlForArtifactRepository();
MockAndControlForArtifactRepository remote = new MockAndControlForArtifactRepository();
File basedir = fileManager.createTempDir();
String path = "metadata.xml";
Metadata m = new Metadata();
m.setVersion( Artifact.RELEASE_VERSION );
TestRepoMetadata trm = new TestRepoMetadata( m );
local.expectGetBasedir( basedir );
local.expectPathOfLocalRepositoryMetadata( trm, remote.repository, path );
mm.replayAll();
trm.updateRepositoryMetadata( local.repository, remote.repository );
fileManager.assertFileExistence( basedir, path, true );
assertTrue( fileManager.getFileContents( new File( basedir, path ), "UTF-8" ).indexOf( "<version>"
+ Artifact.RELEASE_VERSION + "</version>" ) < 0 );
mm.verifyAll();
}
private final class MockAndControlForArtifactRepository
{
MockControl control;
ArtifactRepository repository;
public MockAndControlForArtifactRepository()
{
control = MockControl.createControl( ArtifactRepository.class );
mm.add( control );
repository = ( ArtifactRepository ) control.getMock();
}
public void expectPathOfLocalRepositoryMetadata( TestRepoMetadata trm, ArtifactRepository remote, String path )
{
repository.pathOfLocalRepositoryMetadata( trm, remote );
control.setReturnValue( path, MockControl.ONE_OR_MORE );
}
public void expectGetBasedir( File basedir )
{
repository.getBasedir();
control.setReturnValue( basedir.getAbsolutePath(), MockControl.ONE_OR_MORE );
}
}
private static final class TestRepoMetadata
extends AbstractRepositoryMetadata
{
protected TestRepoMetadata( Metadata metadata )
{
super( metadata );
}
public boolean isSnapshot()
{
return false;
}
public void setRepository( ArtifactRepository remoteRepository )
{
}
public String getArtifactId()
{
return null;
}
public String getBaseVersion()
{
return null;
}
public String getGroupId()
{
return null;
}
public Object getKey()
{
return null;
}
public boolean storedInArtifactVersionDirectory()
{
return false;
}
public boolean storedInGroupDirectory()
{
return false;
}
}
}

View File

@ -1,458 +0,0 @@
package org.apache.maven.artifact.repository.metadata;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Collections;
import java.util.Date;
import junit.framework.TestCase;
import org.apache.maven.artifact.manager.DefaultUpdateCheckManager;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
import org.apache.maven.artifact.testutils.MockManager;
import org.apache.maven.artifact.testutils.TestFileManager;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.easymock.MockControl;
public class DefaultRepositoryMetadataManagerTest
extends TestCase
{
private MockManager mockManager = new MockManager();
private TestFileManager testFileManager = new TestFileManager(
"DefaultRepositoryMetadataManager.test.",
"" );
private MockControl wagonManagerCtl;
private WagonManager wagonManager;
private DefaultUpdateCheckManager updateCheckManager;
@Override
public void setUp()
throws Exception
{
super.setUp();
wagonManagerCtl = MockControl.createControl( WagonManager.class );
mockManager.add( wagonManagerCtl );
wagonManager = (WagonManager) wagonManagerCtl.getMock();
updateCheckManager = new DefaultUpdateCheckManager( new ConsoleLogger( Logger.LEVEL_DEBUG, "test" ) );
}
@Override
public void tearDown()
throws Exception
{
testFileManager.cleanUp();
super.tearDown();
}
public void testResolveAlways_MarkTouchfileOnResourceNotFoundException()
throws RepositoryMetadataResolutionException, IOException, XmlPullParserException,
ParseException, InterruptedException
{
Date start = new Date();
// helps the lastUpdate interval be significantly different.
Thread.sleep( 1000 );
MockControl localRepoCtl = MockControl.createControl( ArtifactRepository.class );
mockManager.add( localRepoCtl );
ArtifactRepository localRepo = (ArtifactRepository) localRepoCtl.getMock();
File dir = testFileManager.createTempDir();
String filename = "metadata.xml";
String path = "path/to/" + filename;
localRepo.getBasedir();
localRepoCtl.setReturnValue( dir.getAbsolutePath(), MockControl.ZERO_OR_MORE );
localRepo.pathOfLocalRepositoryMetadata( null, null );
localRepoCtl.setMatcher( MockControl.ALWAYS_MATCHER );
localRepoCtl.setReturnValue( path, MockControl.ZERO_OR_MORE );
localRepo.getId();
localRepoCtl.setReturnValue( "local", MockControl.ZERO_OR_MORE );
wagonManager.isOnline();
wagonManagerCtl.setReturnValue( true, MockControl.ZERO_OR_MORE );
try
{
wagonManager.getArtifactMetadataFromDeploymentRepository( null, null, null, null );
wagonManagerCtl.setMatcher( MockControl.ALWAYS_MATCHER );
wagonManagerCtl.setThrowable( new ResourceDoesNotExistException( "Test error" ) );
}
catch ( TransferFailedException e )
{
fail( "Should not happen during mock setup." );
}
catch ( ResourceDoesNotExistException e )
{
fail( "Should not happen during mock setup." );
}
MockControl metadataCtl = MockControl.createControl( RepositoryMetadata.class );
mockManager.add( metadataCtl );
RepositoryMetadata metadata = (RepositoryMetadata) metadataCtl.getMock();
String groupId = "group";
String artifactId = "artifact";
String baseVersion = "1-SNAPSHOT";
metadata.getGroupId();
metadataCtl.setReturnValue( groupId, MockControl.ZERO_OR_MORE );
metadata.getArtifactId();
metadataCtl.setReturnValue( artifactId, MockControl.ZERO_OR_MORE );
metadata.getBaseVersion();
metadataCtl.setReturnValue( baseVersion, MockControl.ZERO_OR_MORE );
mockManager.replayAll();
Logger logger = new ConsoleLogger( Logger.LEVEL_DEBUG, "test" );
new DefaultRepositoryMetadataManager( wagonManager, updateCheckManager, logger ).resolveAlways( metadata,
localRepo,
localRepo );
// helps the lastUpdate interval be significantly different.
Thread.sleep( 1000 );
Date end = new Date();
Date checkDate = updateCheckManager.readLastUpdated( metadata, localRepo, new File( dir, path ) );
assertNotNull( checkDate );
assertTrue( checkDate.after( start ) );
assertTrue( checkDate.before( end ) );
mockManager.verifyAll();
}
public void testResolveAlways_MarkTouchfileOnTransferFailedException()
throws RepositoryMetadataResolutionException, IOException, XmlPullParserException,
ParseException, InterruptedException
{
Date start = new Date();
// helps the lastUpdate interval be significantly different.
Thread.sleep( 1000 );
MockControl localRepoCtl = MockControl.createControl( ArtifactRepository.class );
mockManager.add( localRepoCtl );
ArtifactRepository localRepo = (ArtifactRepository) localRepoCtl.getMock();
File dir = testFileManager.createTempDir();
String filename = "metadata.xml";
String path = "path/to/" + filename;
localRepo.getBasedir();
localRepoCtl.setReturnValue( dir.getAbsolutePath(), MockControl.ZERO_OR_MORE );
localRepo.pathOfLocalRepositoryMetadata( null, null );
localRepoCtl.setMatcher( MockControl.ALWAYS_MATCHER );
localRepoCtl.setReturnValue( path, MockControl.ZERO_OR_MORE );
localRepo.getId();
localRepoCtl.setReturnValue( "local", MockControl.ZERO_OR_MORE );
localRepo.setBlacklisted( false );
localRepoCtl.setVoidCallable( MockControl.ZERO_OR_MORE );
wagonManager.isOnline();
wagonManagerCtl.setReturnValue( true, MockControl.ZERO_OR_MORE );
try
{
wagonManager.getArtifactMetadataFromDeploymentRepository( null, null, null, null );
wagonManagerCtl.setMatcher( MockControl.ALWAYS_MATCHER );
wagonManagerCtl.setThrowable( new TransferFailedException( "Test error" ) );
}
catch ( TransferFailedException e )
{
fail( "Should not happen during mock setup." );
}
catch ( ResourceDoesNotExistException e )
{
fail( "Should not happen during mock setup." );
}
MockControl metadataCtl = MockControl.createControl( RepositoryMetadata.class );
mockManager.add( metadataCtl );
RepositoryMetadata metadata = (RepositoryMetadata) metadataCtl.getMock();
String groupId = "group";
String artifactId = "artifact";
String baseVersion = "1-SNAPSHOT";
metadata.getGroupId();
metadataCtl.setReturnValue( groupId, MockControl.ZERO_OR_MORE );
metadata.getArtifactId();
metadataCtl.setReturnValue( artifactId, MockControl.ZERO_OR_MORE );
metadata.getBaseVersion();
metadataCtl.setReturnValue( baseVersion, MockControl.ZERO_OR_MORE );
mockManager.replayAll();
Logger logger = new ConsoleLogger( Logger.LEVEL_DEBUG, "test" );
try
{
new DefaultRepositoryMetadataManager( wagonManager, updateCheckManager, logger ).resolveAlways( metadata,
localRepo,
localRepo );
fail( "Should have thrown an exception due to transfer failure" );
}
catch ( RepositoryMetadataResolutionException e )
{
assertTrue( true );
}
// helps the lastUpdate interval be significantly different.
Thread.sleep( 1000 );
Date end = new Date();
Date checkDate = updateCheckManager.readLastUpdated( metadata, localRepo, new File( dir, path ) );
assertNotNull( checkDate );
assertTrue( checkDate.after( start ) );
assertTrue( checkDate.before( end ) );
mockManager.verifyAll();
}
public void testResolveAlways_MarkTouchfileOnSuccess()
throws RepositoryMetadataResolutionException, IOException, XmlPullParserException,
ParseException, InterruptedException
{
Date start = new Date();
// helps the lastUpdate interval be significantly different.
Thread.sleep( 1000 );
MockControl localRepoCtl = MockControl.createControl( ArtifactRepository.class );
mockManager.add( localRepoCtl );
ArtifactRepository localRepo = (ArtifactRepository) localRepoCtl.getMock();
File dir = testFileManager.createTempDir();
String filename = "metadata.xml";
String path = "path/to/" + filename;
localRepo.getBasedir();
localRepoCtl.setReturnValue( dir.getAbsolutePath(), MockControl.ZERO_OR_MORE );
localRepo.pathOfLocalRepositoryMetadata( null, null );
localRepoCtl.setMatcher( MockControl.ALWAYS_MATCHER );
localRepoCtl.setReturnValue( path, MockControl.ZERO_OR_MORE );
localRepo.getId();
localRepoCtl.setReturnValue( "local", MockControl.ZERO_OR_MORE );
wagonManager.isOnline();
wagonManagerCtl.setReturnValue( true, MockControl.ZERO_OR_MORE );
try
{
wagonManager.getArtifactMetadataFromDeploymentRepository( null, null, null, null );
wagonManagerCtl.setMatcher( MockControl.ALWAYS_MATCHER );
wagonManagerCtl.setVoidCallable();
}
catch ( TransferFailedException e )
{
fail( "Should not happen during mock setup." );
}
catch ( ResourceDoesNotExistException e )
{
fail( "Should not happen during mock setup." );
}
MockControl metadataCtl = MockControl.createControl( RepositoryMetadata.class );
mockManager.add( metadataCtl );
RepositoryMetadata metadata = (RepositoryMetadata) metadataCtl.getMock();
String groupId = "group";
String artifactId = "artifact";
String baseVersion = "1-SNAPSHOT";
metadata.getGroupId();
metadataCtl.setReturnValue( groupId, MockControl.ZERO_OR_MORE );
metadata.getArtifactId();
metadataCtl.setReturnValue( artifactId, MockControl.ZERO_OR_MORE );
metadata.getBaseVersion();
metadataCtl.setReturnValue( baseVersion, MockControl.ZERO_OR_MORE );
mockManager.replayAll();
Logger logger = new ConsoleLogger( Logger.LEVEL_DEBUG, "test" );
new DefaultRepositoryMetadataManager( wagonManager, updateCheckManager, logger ).resolveAlways( metadata,
localRepo,
localRepo );
// helps the lastUpdate interval be significantly different.
Thread.sleep( 1000 );
Date end = new Date();
Date checkDate = updateCheckManager.readLastUpdated( metadata, localRepo, new File( dir, path ) );
assertNotNull( checkDate );
assertTrue( checkDate.after( start ) );
assertTrue( checkDate.before( end ) );
mockManager.verifyAll();
}
public void testResolve_DontRecheckWhenTouchfileIsWritten()
throws RepositoryMetadataResolutionException, IOException, XmlPullParserException,
ParseException, InterruptedException
{
Date start = new Date();
// helps the lastUpdate interval be significantly different.
Thread.sleep( 1000 );
MockControl localRepoCtl = MockControl.createControl( ArtifactRepository.class );
mockManager.add( localRepoCtl );
ArtifactRepository localRepo = (ArtifactRepository) localRepoCtl.getMock();
MockControl remoteRepoCtl = MockControl.createControl( ArtifactRepository.class );
mockManager.add( remoteRepoCtl );
ArtifactRepository remoteRepo = (ArtifactRepository) remoteRepoCtl.getMock();
String repoId = "remote";
remoteRepo.getId();
remoteRepoCtl.setReturnValue( repoId, MockControl.ZERO_OR_MORE );
ArtifactRepositoryPolicy pol = new ArtifactRepositoryPolicy();
pol.setEnabled( true );
remoteRepo.getSnapshots();
remoteRepoCtl.setReturnValue( pol, MockControl.ZERO_OR_MORE );
remoteRepo.isBlacklisted();
remoteRepoCtl.setReturnValue( false, MockControl.ZERO_OR_MORE );
File dir = testFileManager.createTempDir();
String filename = "metadata.xml";
String path = "path/to/" + filename;
localRepo.getBasedir();
localRepoCtl.setReturnValue( dir.getAbsolutePath(), MockControl.ZERO_OR_MORE );
localRepo.pathOfLocalRepositoryMetadata( null, null );
localRepoCtl.setMatcher( MockControl.ALWAYS_MATCHER );
localRepoCtl.setReturnValue( path, MockControl.ZERO_OR_MORE );
localRepo.getId();
localRepoCtl.setReturnValue( "local", MockControl.ZERO_OR_MORE );
wagonManager.isOnline();
wagonManagerCtl.setReturnValue( true, MockControl.ZERO_OR_MORE );
try
{
wagonManager.getArtifactMetadata( null, null, null, null );
wagonManagerCtl.setMatcher( MockControl.ALWAYS_MATCHER );
wagonManagerCtl.setThrowable( new ResourceDoesNotExistException( "Test error" ), 1 );
}
catch ( TransferFailedException e )
{
fail( "Should not happen during mock setup." );
}
catch ( ResourceDoesNotExistException e )
{
fail( "Should not happen during mock setup." );
}
MockControl metadataCtl = MockControl.createControl( RepositoryMetadata.class );
mockManager.add( metadataCtl );
RepositoryMetadata metadata = (RepositoryMetadata) metadataCtl.getMock();
metadata.isSnapshot();
metadataCtl.setReturnValue( true, MockControl.ZERO_OR_MORE );
String groupId = "group";
String artifactId = "artifact";
String baseVersion = "1-SNAPSHOT";
metadata.getGroupId();
metadataCtl.setReturnValue( groupId, MockControl.ZERO_OR_MORE );
metadata.getArtifactId();
metadataCtl.setReturnValue( artifactId, MockControl.ZERO_OR_MORE );
metadata.getBaseVersion();
metadataCtl.setReturnValue( baseVersion, MockControl.ZERO_OR_MORE );
metadata.getKey();
metadataCtl.setReturnValue( "Test metadata for: " + groupId + ":" + artifactId + ":" + baseVersion, MockControl.ZERO_OR_MORE );
Metadata md = new Metadata();
metadata.getMetadata();
metadataCtl.setReturnValue( md, MockControl.ZERO_OR_MORE );
metadata.setMetadata( null );
metadataCtl.setMatcher( MockControl.ALWAYS_MATCHER );
metadataCtl.setVoidCallable( MockControl.ZERO_OR_MORE );
mockManager.replayAll();
Logger logger = new ConsoleLogger( Logger.LEVEL_DEBUG, "test" );
System.out.println( "Testing re-check proofing..." );
RepositoryMetadataManager mgr = new DefaultRepositoryMetadataManager( wagonManager, updateCheckManager, logger );
mgr.resolve( metadata, Collections.singletonList( remoteRepo ), localRepo );
Date checkDate = updateCheckManager.readLastUpdated( metadata, remoteRepo, new File( dir, path ) );
assertNotNull( checkDate );
mgr.resolve( metadata, Collections.singletonList( remoteRepo ), localRepo );
checkDate = updateCheckManager.readLastUpdated( metadata, remoteRepo, new File( dir, path ) );
assertNotNull( checkDate );
// helps the lastUpdate interval be significantly different.
Thread.sleep( 1000 );
Date end = new Date();
assertTrue( checkDate.after( start ) );
assertTrue( checkDate.before( end ) );
mockManager.verifyAll();
}
}

View File

@ -91,8 +91,6 @@ public class ArtifactUpdatePolicyTest
protected void tearDown()
throws Exception
{
wagonManager.setDownloadMonitor( null );
wagonManager.setOnline( true );
super.tearDown();
}
@ -140,17 +138,6 @@ public class ArtifactUpdatePolicyTest
return a;
}
public void testForceLocalDoesNotExist()
throws Exception
{
Artifact a = createRemoteArtifact( "o", "0.0.1-SNAPSHOT" );
artifactResolver.resolveAlways( a, remoteRepositories, localRepository );
assertTransfers( new String[] { "get " + PATH, "getTransfer " + PATH, "get " + PATH + ".sha1",
"get " + PATH + ".md5" } );
}
public void testForceButNoNewUpdates()
throws Exception
{
@ -326,18 +313,6 @@ public class ArtifactUpdatePolicyTest
assertTrue( j.getFile().canRead() );
}
public void testResolveExistingLocalArtifactInOfflineMode()
throws Exception
{
Artifact a = createLocalArtifact( "a", "1.0.0" );
wagonManager.setOnline( false );
artifactResolver.resolve( a, remoteRepositories(), localRepository() );
assertTrue( a.isResolved() );
}
public void testMultipleRemoteRepositories()
throws Exception
{

View File

@ -24,7 +24,11 @@ import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.maven.Maven;
import org.apache.maven.artifact.Artifact;
@ -55,14 +59,21 @@ import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.monitor.event.DefaultEventDispatcher;
import org.apache.maven.monitor.event.EventDispatcher;
import org.apache.maven.plugin.*;
import org.apache.maven.plugin.InvalidPluginException;
import org.apache.maven.plugin.MavenPluginCollector;
import org.apache.maven.plugin.MavenPluginDiscoverer;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.PluginContext;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.PluginManagerException;
import org.apache.maven.plugin.PluginNotFoundException;
import org.apache.maven.plugin.PluginRepository;
import org.apache.maven.plugin.version.PluginVersionNotFoundException;
import org.apache.maven.plugin.version.PluginVersionResolutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.MavenProjectBuildingResult;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.plugin.PluginRepository;
import org.apache.maven.reactor.MavenExecutionException;
import org.apache.maven.reactor.MissingModuleException;
import org.apache.maven.settings.Settings;
@ -258,7 +269,6 @@ public class MavenEmbedder
modelWriter.write( writer, model );
}
// ----------------------------------------------------------------------
// Settings
// ----------------------------------------------------------------------

View File

@ -60,7 +60,6 @@ import org.codehaus.plexus.component.repository.exception.ComponentLifecycleExce
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException;
@ -84,9 +83,6 @@ public class DefaultMavenExecutionRequestPopulator
@Requirement
private PlexusContainer container;
@Requirement
private WagonManager wagonManager;
@Requirement
private MavenSettingsBuilder settingsBuilder;
@ -392,21 +388,17 @@ public class DefaultMavenExecutionRequestPopulator
if ( request.isOffline() )
{
wagonManager.setOnline( false );
mavenTools.setOnline( false );
}
else if ( ( request.getSettings() != null ) && request.getSettings().isOffline() )
{
wagonManager.setOnline( false );
mavenTools.setOnline( false );
}
else
{
wagonManager.findAndRegisterWagons( container );
mavenTools.setDownloadMonitor( request.getTransferListener() );
wagonManager.setInteractive( request.isInteractiveMode() );
wagonManager.setDownloadMonitor( request.getTransferListener() );
wagonManager.setOnline( true );
mavenTools.setOnline( true );
}
try
@ -435,7 +427,7 @@ public class DefaultMavenExecutionRequestPopulator
throw new SettingsConfigurationException( "Proxy in settings.xml has no host" );
}
wagonManager.addProxy( proxy.getProtocol(), proxy.getHost(), proxy.getPort(), proxy.getUsername(), proxy.getPassword(), proxy.getNonProxyHosts() );
mavenTools.addProxy( proxy.getProtocol(), proxy.getHost(), proxy.getPort(), proxy.getUsername(), proxy.getPassword(), proxy.getNonProxyHosts() );
}
for ( Iterator i = settings.getServers().iterator(); i.hasNext(); )
@ -446,29 +438,18 @@ public class DefaultMavenExecutionRequestPopulator
String phrase = securityDispatcher.decrypt( server.getPassphrase() );
wagonManager.addAuthenticationInfo( server.getId(), server.getUsername(), pass, server.getPrivateKey(), phrase );
mavenTools.addAuthenticationInfo( server.getId(), server.getUsername(), pass, server.getPrivateKey(), phrase );
wagonManager.addPermissionInfo( server.getId(), server.getFilePermissions(), server.getDirectoryPermissions() );
if ( server.getConfiguration() != null )
{
wagonManager.addConfiguration( server.getId(), (Xpp3Dom) server.getConfiguration() );
}
mavenTools.addPermissionInfo( server.getId(), server.getFilePermissions(), server.getDirectoryPermissions() );
}
RepositoryPermissions defaultPermissions = new RepositoryPermissions();
defaultPermissions.setDirectoryMode( "775" );
defaultPermissions.setFileMode( "664" );
wagonManager.setDefaultRepositoryPermissions( defaultPermissions );
for ( Iterator i = settings.getMirrors().iterator(); i.hasNext(); )
{
Mirror mirror = (Mirror) i.next();
wagonManager.addMirror( mirror.getId(), mirror.getMirrorOf(), mirror.getUrl() );
mavenTools.addMirror( mirror.getId(), mirror.getMirrorOf(), mirror.getUrl() );
}
}
catch ( SecDispatcherException e )

View File

@ -1,6 +1,5 @@
package org.apache.maven.embedder.execution;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.embedder.DefaultConfiguration;
import org.apache.maven.embedder.MavenEmbedderException;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
@ -12,15 +11,12 @@ public class DefaultMavenExecutionRequestPopulatorTest
{
private MavenExecutionRequestPopulator populator;
private WagonManager wagonManager;
public void setUp()
throws Exception
{
super.setUp();
populator = (MavenExecutionRequestPopulator) lookup( MavenExecutionRequestPopulator.class );
wagonManager = (WagonManager) lookup( WagonManager.class );
}
public void testWagonManagerOfflineFlagIsPopulatedFromSettings()
@ -28,11 +24,6 @@ public class DefaultMavenExecutionRequestPopulatorTest
{
MavenExecutionRequest req = new DefaultMavenExecutionRequest().setOffline( true );
assertTrue( wagonManager.isOnline() );
populator.populateDefaults( req, new DefaultConfiguration() );
assertFalse( wagonManager.isOnline() );
}
}

View File

@ -21,18 +21,25 @@ package org.apache.maven;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
import org.apache.maven.artifact.repository.DefaultArtifactRepository;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
@ -41,8 +48,11 @@ import org.apache.maven.model.DeploymentRepository;
import org.apache.maven.model.Model;
import org.apache.maven.model.Repository;
import org.apache.maven.model.RepositoryPolicy;
import org.apache.maven.project.MissingRepositoryElementException;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.wagon.authentication.AuthenticationInfo;
import org.apache.maven.wagon.events.TransferListener;
import org.apache.maven.wagon.proxy.ProxyInfo;
import org.apache.maven.wagon.repository.RepositoryPermissions;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.LogEnabled;
@ -68,6 +78,9 @@ public class DefaultMavenTools
@Requirement
private ArtifactRepositoryLayout defaultArtifactRepositoryLayout;
@Requirement
private WagonManager wagonManager;
@Requirement
private Logger logger;
@ -396,4 +409,408 @@ public class DefaultMavenTools
throw new IOException( e.getMessage() );
}
}
// ------------------------------------------------------------------------
// Extracted from DefaultWagonManager
// ------------------------------------------------------------------------
private static final String WILDCARD = "*";
private static final String EXTERNAL_WILDCARD = "external:*";
private static int anonymousMirrorIdSeed = 0;
private boolean online = true;
private boolean interactive = true;
private TransferListener downloadMonitor;
private Map<String,ProxyInfo> proxies = new HashMap<String,ProxyInfo>();
private Map<String,AuthenticationInfo> authenticationInfoMap = new HashMap<String,AuthenticationInfo>();
private Map<String,RepositoryPermissions> serverPermissionsMap = new HashMap<String,RepositoryPermissions>();
//used LinkedMap to preserve the order.
private Map<String,ArtifactRepository> mirrors = new LinkedHashMap<String,ArtifactRepository>();
public ArtifactRepository getMirrorRepository( ArtifactRepository repository )
{
ArtifactRepository mirror = getMirror( repository );
if ( mirror != null )
{
String id = mirror.getId();
if ( id == null )
{
// TODO: this should be illegal in settings.xml
id = repository.getId();
}
logger.debug( "Using mirror: " + mirror.getId() + " for repository: " + repository.getId() + "\n(mirror url: " + mirror.getUrl() + ")" );
repository = artifactRepositoryFactory.createArtifactRepository( id, mirror.getUrl(),
repository.getLayout(), repository.getSnapshots(),
repository.getReleases() );
}
return repository;
}
/**
* This method finds a matching mirror for the selected repository. If there is an exact match, this will be used.
* If there is no exact match, then the list of mirrors is examined to see if a pattern applies.
*
* @param originalRepository See if there is a mirror for this repository.
* @return the selected mirror or null if none are found.
*/
public ArtifactRepository getMirror( ArtifactRepository originalRepository )
{
ArtifactRepository selectedMirror = mirrors.get( originalRepository.getId() );
if ( null == selectedMirror )
{
// Process the patterns in order. First one that matches wins.
Set<String> keySet = mirrors.keySet();
if ( keySet != null )
{
for ( String pattern : keySet )
{
if ( matchPattern( originalRepository, pattern ) )
{
selectedMirror = mirrors.get( pattern );
}
}
}
}
return selectedMirror;
}
/**
* This method checks if the pattern matches the originalRepository.
* Valid patterns:
* * = everything
* external:* = everything not on the localhost and not file based.
* repo,repo1 = repo or repo1
* *,!repo1 = everything except repo1
*
* @param originalRepository to compare for a match.
* @param pattern used for match. Currently only '*' is supported.
* @return true if the repository is a match to this pattern.
*/
public boolean matchPattern( ArtifactRepository originalRepository, String pattern )
{
boolean result = false;
String originalId = originalRepository.getId();
// simple checks first to short circuit processing below.
if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) )
{
result = true;
}
else
{
// process the list
String[] repos = pattern.split( "," );
for (String repo : repos) {
// see if this is a negative match
if (repo.length() > 1 && repo.startsWith("!")) {
if (originalId.equals(repo.substring(1))) {
// explicitly exclude. Set result and stop processing.
result = false;
break;
}
}
// check for exact match
else if (originalId.equals(repo)) {
result = true;
break;
}
// check for external:*
else if (EXTERNAL_WILDCARD.equals(repo) && isExternalRepo(originalRepository)) {
result = true;
// don't stop processing in case a future segment explicitly excludes this repo
} else if (WILDCARD.equals(repo)) {
result = true;
// don't stop processing in case a future segment explicitly excludes this repo
}
}
}
return result;
}
/**
* Checks the URL to see if this repository refers to an external repository
*
* @param originalRepository
* @return true if external.
*/
public boolean isExternalRepo( ArtifactRepository originalRepository )
{
try
{
URL url = new URL( originalRepository.getUrl() );
return !( url.getHost().equals( "localhost" ) || url.getHost().equals( "127.0.0.1" ) || url.getProtocol().equals("file" ) );
}
catch ( MalformedURLException e )
{
// bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it
return false;
}
}
public void addMirror( String id, String mirrorOf, String url )
{
if ( id == null )
{
id = "mirror-" + anonymousMirrorIdSeed++;
logger.warn( "You are using a mirror that doesn't declare an <id/> element. Using \'" + id + "\' instead:\nId: " + id + "\nmirrorOf: " + mirrorOf + "\nurl: " + url + "\n" );
}
ArtifactRepository mirror = new DefaultArtifactRepository( id, url, null );
mirrors.put( mirrorOf, mirror );
}
public void setOnline( boolean online )
{
this.online = online;
}
public boolean isOnline()
{
return online;
}
public void setInteractive( boolean interactive )
{
this.interactive = interactive;
}
public void setDownloadMonitor( TransferListener downloadMonitor )
{
this.downloadMonitor = downloadMonitor;
}
public void addProxy( String protocol, String host, int port, String username, String password, String nonProxyHosts )
{
ProxyInfo proxyInfo = new ProxyInfo();
proxyInfo.setHost( host );
proxyInfo.setType( protocol );
proxyInfo.setPort( port );
proxyInfo.setNonProxyHosts( nonProxyHosts );
proxyInfo.setUserName( username );
proxyInfo.setPassword( password );
proxies.put( protocol, proxyInfo );
}
public void addAuthenticationInfo( String repositoryId, String username, String password, String privateKey, String passphrase )
{
AuthenticationInfo authInfo = new AuthenticationInfo();
authInfo.setUserName( username );
authInfo.setPassword( password );
authInfo.setPrivateKey( privateKey );
authInfo.setPassphrase( passphrase );
authenticationInfoMap.put( repositoryId, authInfo );
}
public void addPermissionInfo( String repositoryId, String filePermissions, String directoryPermissions )
{
RepositoryPermissions permissions = new RepositoryPermissions();
boolean addPermissions = false;
if ( filePermissions != null )
{
permissions.setFileMode( filePermissions );
addPermissions = true;
}
if ( directoryPermissions != null )
{
permissions.setDirectoryMode( directoryPermissions );
addPermissions = true;
}
if ( addPermissions )
{
serverPermissionsMap.put( repositoryId, permissions );
}
}
// Test for this stuff
/*
public void testAddMirrorWithNullRepositoryId()
{
wagonManager.addMirror( null, "test", "http://www.nowhere.com/" );
}
public void testGetArtifactSha1MissingMd5Present()
throws IOException, UnsupportedProtocolException, TransferFailedException, ResourceDoesNotExistException
{
Artifact artifact = createTestPomArtifact( "target/test-data/get-remote-artifact" );
ArtifactRepository repo = createStringRepo();
StringWagon wagon = (StringWagon) wagonManager.getWagon( "string" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ), "expected" );
wagon.addExpectedContent( repo.getLayout().pathOf( artifact ) + ".md5", "bad_checksum" );
wagonManager.getArtifact( artifact, repo, true );
assertTrue( artifact.getFile().exists() );
}
public void testExternalURL()
{
DefaultWagonManager mgr = new DefaultWagonManager();
assertTrue( mgr.isExternalRepo( getRepo( "foo", "http://somehost" ) ) );
assertTrue( mgr.isExternalRepo( getRepo( "foo", "http://somehost:9090/somepath" ) ) );
assertTrue( mgr.isExternalRepo( getRepo( "foo", "ftp://somehost" ) ) );
assertTrue( mgr.isExternalRepo( getRepo( "foo", "http://192.168.101.1" ) ) );
assertTrue( mgr.isExternalRepo( getRepo( "foo", "http://" ) ) );
// these are local
assertFalse( mgr.isExternalRepo( getRepo( "foo", "http://localhost:8080" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "http://127.0.0.1:9090" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "file://localhost/somepath" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "file://localhost/D:/somepath" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "http://localhost" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "http://127.0.0.1" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "file:///somepath" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "file://D:/somepath" ) ) );
// not a proper url so returns false;
assertFalse( mgr.isExternalRepo( getRepo( "foo", "192.168.101.1" ) ) );
assertFalse( mgr.isExternalRepo( getRepo( "foo", "" ) ) );
}
public void testMirrorLookup()
{
wagonManager.addMirror( "a", "a", "http://a" );
wagonManager.addMirror( "b", "b", "http://b" );
ArtifactRepository repo = null;
repo = wagonManager.getMirrorRepository( getRepo( "a", "http://a.a" ) );
assertEquals( "http://a", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "b", "http://a.a" ) );
assertEquals( "http://b", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "c", "http://c.c" ) );
assertEquals( "http://c.c", repo.getUrl() );
}
public void testMirrorWildcardLookup()
{
wagonManager.addMirror( "a", "a", "http://a" );
wagonManager.addMirror( "b", "b", "http://b" );
wagonManager.addMirror( "c", "*", "http://wildcard" );
ArtifactRepository repo = null;
repo = wagonManager.getMirrorRepository( getRepo( "a", "http://a.a" ) );
assertEquals( "http://a", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "b", "http://a.a" ) );
assertEquals( "http://b", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "c", "http://c.c" ) );
assertEquals( "http://wildcard", repo.getUrl() );
}
public void testMirrorStopOnFirstMatch()
{
//exact matches win first
wagonManager.addMirror( "a2", "a,b", "http://a2" );
wagonManager.addMirror( "a", "a", "http://a" );
//make sure repeated entries are skipped
wagonManager.addMirror( "a", "a", "http://a3" );
wagonManager.addMirror( "b", "b", "http://b" );
wagonManager.addMirror( "c", "d,e", "http://de" );
wagonManager.addMirror( "c", "*", "http://wildcard" );
wagonManager.addMirror( "c", "e,f", "http://ef" );
ArtifactRepository repo = null;
repo = wagonManager.getMirrorRepository( getRepo( "a", "http://a.a" ) );
assertEquals( "http://a", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "b", "http://a.a" ) );
assertEquals( "http://b", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "c", "http://c.c" ) );
assertEquals( "http://wildcard", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "d", "http://d" ) );
assertEquals( "http://de", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "e", "http://e" ) );
assertEquals( "http://de", repo.getUrl() );
repo = wagonManager.getMirrorRepository( getRepo( "f", "http://f" ) );
assertEquals( "http://wildcard", repo.getUrl() );
}
public void testPatterns()
{
DefaultWagonManager mgr = new DefaultWagonManager();
assertTrue( mgr.matchPattern( getRepo( "a" ), "*" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), ",*," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "a" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "a," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), ",a," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "a," ) );
assertFalse( mgr.matchPattern( getRepo( "b" ), "a" ) );
assertFalse( mgr.matchPattern( getRepo( "b" ), "a," ) );
assertFalse( mgr.matchPattern( getRepo( "b" ), ",a" ) );
assertFalse( mgr.matchPattern( getRepo( "b" ), ",a," ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "a,b" ) );
assertTrue( mgr.matchPattern( getRepo( "b" ), "a,b" ) );
assertFalse( mgr.matchPattern( getRepo( "c" ), "a,b" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*,b" ) );
assertTrue( mgr.matchPattern( getRepo( "a" ), "*,!b" ) );
assertFalse( mgr.matchPattern( getRepo( "a" ), "*,!a" ) );
assertFalse( mgr.matchPattern( getRepo( "a" ), "!a,*" ) );
assertTrue( mgr.matchPattern( getRepo( "c" ), "*,!a" ) );
assertTrue( mgr.matchPattern( getRepo( "c" ), "!a,*" ) );
assertFalse( mgr.matchPattern( getRepo( "c" ), "!a,!c" ) );
assertFalse( mgr.matchPattern( getRepo( "d" ), "!a,!c*" ) );
}
public void testPatternsWithExternal()
{
DefaultWagonManager mgr = new DefaultWagonManager();
assertTrue( mgr.matchPattern( getRepo( "a", "http://localhost" ), "*" ) );
assertFalse( mgr.matchPattern( getRepo( "a", "http://localhost" ), "external:*" ) );
assertTrue( mgr.matchPattern( getRepo( "a", "http://localhost" ), "external:*,a" ) );
assertFalse( mgr.matchPattern( getRepo( "a", "http://localhost" ), "external:*,!a" ) );
assertTrue( mgr.matchPattern( getRepo( "a", "http://localhost" ), "a,external:*" ) );
assertFalse( mgr.matchPattern( getRepo( "a", "http://localhost" ), "!a,external:*" ) );
assertFalse( mgr.matchPattern( getRepo( "c", "http://localhost" ), "!a,external:*" ) );
assertTrue( mgr.matchPattern( getRepo( "c", "http://somehost" ), "!a,external:*" ) );
}
*/
}

View File

@ -19,18 +19,18 @@ package org.apache.maven;
* under the License.
*/
import java.io.IOException;
import java.util.List;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.model.DeploymentRepository;
import org.apache.maven.model.Model;
import org.apache.maven.model.Repository;
import org.apache.maven.project.ProjectBuildingException;
import java.io.IOException;
import java.util.List;
import org.apache.maven.wagon.events.TransferListener;
/**
* @author Jason van Zyl
@ -69,4 +69,30 @@ public interface MavenTools
void resolve( Artifact artifact, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories )
throws IOException;
// WagonManager
ArtifactRepository getMirrorRepository( ArtifactRepository repository );
ArtifactRepository getMirror( ArtifactRepository originalRepository );
boolean matchPattern( ArtifactRepository originalRepository, String pattern );
boolean isExternalRepo( ArtifactRepository originalRepository );
void addMirror( String id, String mirrorOf, String url );
void setOnline( boolean online );
boolean isOnline();
void setInteractive( boolean interactive );
void setDownloadMonitor( TransferListener downloadMonitor );
void addProxy( String protocol, String host, int port, String username, String password, String nonProxyHosts );
void addAuthenticationInfo( String repositoryId, String username, String password, String privateKey, String passphrase );
void addPermissionInfo( String repositoryId, String filePermissions, String directoryPermissions );
}

View File

@ -812,6 +812,19 @@ public class PomConstructionTest
assertTrue( pom.getValue( "build/filters[7]" ).toString().endsWith( "parent-d.properties" ) );
}
/** MNG-4027
public void testProjectInjectedDependencies()
throws Exception
{
PomTestWrapper pom = buildPom( "profile-injected-dependencies" );
assertEquals( 4, ( (List<?>) pom.getValue( "dependencies" ) ).size() );
assertEquals( "a", pom.getValue( "dependencies[1]/artifactId" ) );
assertEquals( "c", pom.getValue( "dependencies[2]/artifactId" ) );
assertEquals( "b", pom.getValue( "dependencies[3]/artifactId" ) );
assertEquals( "d", pom.getValue( "dependencies[4]/artifactId" ) );
}
//*/
/** MNG-4027
public void testProfileInjectedDependencies()
throws Exception